1
|
import {Injectable} from "@angular/core";
|
2
|
import {HttpEvent, HttpHandler, HttpInterceptor, HttpRequest} from "@angular/common/http";
|
3
|
import {Observable, throwError} from "rxjs";
|
4
|
import {catchError} from "rxjs/operators";
|
5
|
import {Session} from "./login/utils/helper.class";
|
6
|
import {Router} from "@angular/router";
|
7
|
import {LoginErrorCodes} from "./login/utils/guardHelper.class";
|
8
|
import {properties} from "../../environments/environment";
|
9
|
import {isArray} from "util";
|
10
|
|
11
|
@Injectable()
|
12
|
export class ErrorInterceptorService implements HttpInterceptor {
|
13
|
|
14
|
private static UNAUTHORIZED_WHITELIST = [properties.userInfoUrl, properties.orcidAPIURL, properties.registryUrl + 'verification/'];
|
15
|
|
16
|
constructor(private router: Router) {
|
17
|
}
|
18
|
|
19
|
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
|
20
|
return next.handle(req).pipe(catchError(err => {
|
21
|
if ((err.status === 0 && properties.registryUrl && this.isService(req, properties.registryUrl) && req.method !== 'GET') ||
|
22
|
(err.status === 401 && !this.isService(req, ErrorInterceptorService.UNAUTHORIZED_WHITELIST))) {
|
23
|
this.logOut();
|
24
|
} else if(err.status === 403 && !this.isService(req, ErrorInterceptorService.UNAUTHORIZED_WHITELIST)) {
|
25
|
this.unauthorized();
|
26
|
}
|
27
|
return throwError(err);
|
28
|
}));
|
29
|
}
|
30
|
|
31
|
isService(req: HttpRequest<any>, service: string | string[]):boolean {
|
32
|
if(isArray(service)) {
|
33
|
return !!service.find(element => req.url.indexOf(element) !== -1);
|
34
|
} else {
|
35
|
return req.url.indexOf(service) !== -1;
|
36
|
}
|
37
|
}
|
38
|
|
39
|
logOut() {
|
40
|
Session.removeUser();
|
41
|
this.router.navigate(['/user-info'], {
|
42
|
queryParams: {
|
43
|
'errorCode': LoginErrorCodes.NOT_LOGIN,
|
44
|
'redirectUrl': this.router.url
|
45
|
}
|
46
|
});
|
47
|
}
|
48
|
|
49
|
unauthorized() {
|
50
|
this.router.navigate(['/user-info'], {
|
51
|
queryParams: {
|
52
|
'errorCode': LoginErrorCodes.NOT_AUTHORIZED,
|
53
|
'redirectUrl': this.router.url
|
54
|
}
|
55
|
});
|
56
|
}
|
57
|
}
|