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";
|
|
|
|
|
|
|
|
@Injectable()
|
|
|
|
export class ErrorInterceptorService implements HttpInterceptor {
|
|
|
|
|
2022-10-05 15:52:04 +02:00
|
|
|
private static UNAUTHORIZED_WHITELIST = [properties.userInfoUrl, properties.orcidAPIURL, properties.registryUrl? (properties.registryUrl + 'verification/'):null, properties.eoscDataTransferAPI].filter(value => !!value);
|
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 {
|
2021-09-17 19:13:35 +02:00
|
|
|
if(Array.isArray(service)) {
|
2020-11-25 17:45:41 +01:00
|
|
|
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
|
|
|
}
|