-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtokeninterceptor.service.ts
More file actions
39 lines (32 loc) · 1.16 KB
/
tokeninterceptor.service.ts
File metadata and controls
39 lines (32 loc) · 1.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
//a token interceptor service file
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpEvent, HttpHandler, HttpRequest } from '@angular/common/http';
import {Observable} from "rxjs";
import { Router } from '@angular/router';
@Injectable({
providedIn: 'root'
})
export class TokenInterceptorService implements HttpInterceptor {
constructor(private router:Router) { }
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
let date: Date = new Date()
date.setTime(date.getTime()+(date.getTimezoneOffset()*60*1000)+10800000)
let expiry = new Date(localStorage.getItem('expiresAt'))
//the no-auth custom header is to check whether this request needs authorization or not
if (req.headers.get('No-Auth') == "True")
return next.handle(req.clone());
if(!expiry){
this.router.navigate(['login']);
return
}else if(expiry < date){
this.router.navigate(['login']);
return
}
let tokenizedReq = req.clone({
setHeaders: {
Authorization: 'Bearer ' + localStorage.getItem('accessToken')
}
})
return next.handle(tokenizedReq)
}
}