2020-11-16 14:36:12 +01:00
|
|
|
import {Injectable} from "@angular/core";
|
|
|
|
import {HttpEvent, HttpHandler, HttpInterceptor, HttpRequest} from "@angular/common/http";
|
2021-04-28 16:42:11 +02:00
|
|
|
import {Observable, throwError, TimeoutError} from "rxjs";
|
2020-11-16 14:36:12 +01:00
|
|
|
import {catchError} from "rxjs/operators";
|
|
|
|
import {Session} from "./login/utils/helper.class";
|
|
|
|
import {Router} from "@angular/router";
|
|
|
|
import {LoginErrorCodes} from "./login/utils/guardHelper.class";
|
|
|
|
import {properties} from "../../environments/environment";
|
2020-11-25 17:45:41 +01:00
|
|
|
import {isArray} from "util";
|
2020-11-16 14:36:12 +01:00
|
|
|
|
|
|
|
@Injectable()
|
|
|
|
export class ErrorInterceptorService implements HttpInterceptor {
|
|
|
|
|
2021-03-04 19:06:13 +01:00
|
|
|
private static UNAUTHORIZED_WHITELIST = [properties.userInfoUrl, properties.orcidAPIURL, properties.registryUrl + 'verification/'];
|
2020-11-25 17:45:41 +01:00
|
|
|
|
2020-11-16 14:36:12 +01:00
|
|
|
constructor(private router: Router) {
|
|
|
|
}
|
|
|
|
|
|
|
|
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
|
|
|
|
return next.handle(req).pipe(catchError(err => {
|
2021-04-28 16:42:11 +02:00
|
|
|
if(err instanceof TimeoutError) {
|
|
|
|
console.error(req.url, "Timeout");
|
|
|
|
}
|
2021-03-11 13:55:59 +01:00
|
|
|
if ((err.status === 0 && properties.registryUrl && this.isService(req, properties.registryUrl) && req.method !== 'GET') ||
|
2020-11-25 18:32:20 +01:00
|
|
|
(err.status === 401 && !this.isService(req, ErrorInterceptorService.UNAUTHORIZED_WHITELIST))) {
|
2020-11-16 14:36:12 +01:00
|
|
|
this.logOut();
|
2021-03-04 15:30:31 +01:00
|
|
|
} else if(err.status === 403 && !this.isService(req, ErrorInterceptorService.UNAUTHORIZED_WHITELIST)) {
|
2020-11-25 18:32:20 +01:00
|
|
|
this.unauthorized();
|
2020-11-16 14:36:12 +01:00
|
|
|
}
|
|
|
|
return throwError(err);
|
|
|
|
}));
|
|
|
|
}
|
|
|
|
|
2020-11-25 17:45:41 +01:00
|
|
|
isService(req: HttpRequest<any>, service: string | string[]):boolean {
|
|
|
|
if(isArray(service)) {
|
|
|
|
return !!service.find(element => req.url.indexOf(element) !== -1);
|
|
|
|
} else {
|
|
|
|
return req.url.indexOf(service) !== -1;
|
|
|
|
}
|
2020-11-16 14:36:12 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
logOut() {
|
|
|
|
Session.removeUser();
|
|
|
|
this.router.navigate(['/user-info'], {
|
|
|
|
queryParams: {
|
|
|
|
'errorCode': LoginErrorCodes.NOT_LOGIN,
|
|
|
|
'redirectUrl': this.router.url
|
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
2020-11-25 18:32:20 +01:00
|
|
|
|
|
|
|
unauthorized() {
|
|
|
|
this.router.navigate(['/user-info'], {
|
|
|
|
queryParams: {
|
|
|
|
'errorCode': LoginErrorCodes.NOT_AUTHORIZED,
|
|
|
|
'redirectUrl': this.router.url
|
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
2020-11-16 14:36:12 +01:00
|
|
|
}
|