import {Injectable} from "@angular/core"; import {HttpEvent, HttpHandler, HttpInterceptor, HttpRequest} from "@angular/common/http"; import {Observable, throwError} 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]; constructor(private router: Router) { } intercept(req: HttpRequest, next: HttpHandler): Observable> { return next.handle(req).pipe(catchError(err => { if ((err.status === 0 && properties.registryUrl && this.isService(req, properties.registryUrl)) || (err.status === 401 && !this.isService(req, ErrorInterceptorService.UNAUTHORIZED_WHITELIST))) { this.logOut(); } else if(err.status === 403) { this.unauthorized(); } return throwError(err); })); } isService(req: HttpRequest, 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 } }); } }