openaire-library/error-interceptor.service.ts

58 lines
1.7 KiB
TypeScript
Raw Normal View History

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];
constructor(private router: Router) {
}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(req).pipe(catchError(err => {
if ((err.status === 0 && 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<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
}
});
}
}