-
-
Notifications
You must be signed in to change notification settings - Fork 41
/
interceptor.ts
81 lines (71 loc) · 2.33 KB
/
interceptor.ts
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import { Injectable } from '@angular/core';
import {
HttpRequest,
HttpHandler,
HttpEvent,
HttpInterceptor,
HttpErrorResponse,
HttpClient
} from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError, switchMap } from 'rxjs/operators';
import { Router } from '@angular/router';
import { tokenKeys } from '../modules/pages/area-education/utils';
import { educationApi } from './utils';
interface RefreshResponse {
access: string;
}
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
constructor(
private router: Router,
private http: HttpClient,
) {}
refreshToken(token: string) {
return this.http.post(educationApi + 'token/refresh/', {
refresh: token
});
}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
request = this.addAuthHeader(request);
return next.handle(request).pipe(catchError(error => {
return this.handleResponseError(error, request, next);
}));
}
addAuthHeader(request: HttpRequest<any>) {
const token = localStorage.getItem(tokenKeys.token);
if (token && location.href.includes('educacao')) {
return request.clone({
setHeaders: {
'Authorization': 'Bearer ' + token
}
});
}
return request;
}
handleResponseError(err: HttpErrorResponse, request?: HttpRequest<any>, next?: HttpHandler): Observable<any> {
const refreshToken = localStorage.getItem(tokenKeys.refresh);
if (err.status === 401 && next && request && location.href.includes('educacao') && refreshToken && !request.url.includes('refresh')) {
return this.refreshToken(refreshToken as string).pipe(
switchMap(response => {
localStorage.setItem(tokenKeys.token, (response as RefreshResponse).access);
request = this.addAuthHeader(request as HttpRequest<any>);
return next.handle(request);
}),
catchError(e => {
if (e.status !== 401) {
return this.handleResponseError(e);
} else {
this.redirectLogin();
return e;
}
}));
}
return throwError(err);
}
redirectLogin() {
localStorage.removeItem(tokenKeys.refresh);
localStorage.removeItem(tokenKeys.token);
this.router.navigate(['/educacao'], {queryParams: {login: 'open'}})
}
}