openaire-library/error-interceptor.service.ts

61 lines
2.0 KiB
TypeScript

import {Injectable} from "@angular/core";
import {HttpEvent, HttpHandler, HttpInterceptor, HttpRequest} from "@angular/common/http";
import {Observable, throwError, TimeoutError} from "rxjs";
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";
import {isArray} from "util";
@Injectable()
export class ErrorInterceptorService implements HttpInterceptor {
private static UNAUTHORIZED_WHITELIST = [properties.userInfoUrl, properties.orcidAPIURL, properties.registryUrl + 'verification/'];
constructor(private router: Router) {
}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(req).pipe(catchError(err => {
if(err instanceof TimeoutError) {
console.error(req.url, "Timeout");
}
if ((err.status === 0 && properties.registryUrl && this.isService(req, properties.registryUrl) && req.method !== 'GET') ||
(err.status === 401 && !this.isService(req, ErrorInterceptorService.UNAUTHORIZED_WHITELIST))) {
this.logOut();
} else if(err.status === 403 && !this.isService(req, ErrorInterceptorService.UNAUTHORIZED_WHITELIST)) {
this.unauthorized();
}
return throwError(err);
}));
}
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;
}
}
logOut() {
Session.removeUser();
this.router.navigate(['/user-info'], {
queryParams: {
'errorCode': LoginErrorCodes.NOT_LOGIN,
'redirectUrl': this.router.url
}
});
}
unauthorized() {
this.router.navigate(['/user-info'], {
queryParams: {
'errorCode': LoginErrorCodes.NOT_AUTHORIZED,
'redirectUrl': this.router.url
}
});
}
}