argos/dmp-frontend/src/common/http/interceptors/unauthorized-response.inter...

52 lines
1.8 KiB
TypeScript

import { HttpErrorResponse, HttpHandler, HttpHeaderResponse, HttpProgressEvent, HttpRequest, HttpResponse, HttpSentEvent, HttpUserEvent } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { Observable, throwError } from 'rxjs';
import { catchError, mergeMap, tap } from 'rxjs/operators';
import { AuthService } from '../../../app/core/services/auth/auth.service';
import { BaseInterceptor } from './base.interceptor';
import { InterceptorType } from './interceptor-type';
import { ConfigurationService } from '@app/core/services/configuration/configuration.service';
@Injectable()
export class UnauthorizedResponseInterceptor extends BaseInterceptor {
constructor(
public router: Router,
private authService: AuthService,
configurationService: ConfigurationService
) { super(configurationService); }
get type(): InterceptorType { return InterceptorType.UnauthorizedResponse; }
interceptRequest(req: HttpRequest<any>, next: HttpHandler): Observable<HttpSentEvent | HttpHeaderResponse | HttpProgressEvent | HttpResponse<any> | HttpUserEvent<any>> {
return next.handle(req).pipe(
catchError(error => {
if (error instanceof HttpErrorResponse) {
switch ((<HttpErrorResponse>error).status) {
case 401:
this.logoutUser();
return throwError(error);
default:
return throwError(error);
}
} else {
return throwError(error);
}
}));
}
private logoutUser() {
//this.authService.clear();
if (!this.isLoginRoute() && !this.isSignupRoute()) { this.router.navigate(['/unauthorized']); }
}
private isLoginRoute(): boolean {
return this.router.isActive('login', false);
}
private isSignupRoute(): boolean {
return this.router.isActive('signup-register', false) || this.router.isActive('signup-invitation', false);
}
}