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; } private accountRefresh$: Observable = null; interceptRequest(req: HttpRequest, next: HttpHandler): Observable | HttpUserEvent> { return next.handle(req).pipe( catchError(error => { if (error instanceof HttpErrorResponse) { switch ((error).status) { case 401: this.logoutUser(); return throwError(error); //return this.handle401Error(req, next); default: return throwError(error); } } else { return throwError(error); } })); } // private handle401Error(req: HttpRequest, next: HttpHandler) { // if (!this.accountRefresh$) { // this.accountRefresh$ = this.authService.refreshToken().pipe( // tap(account => { // this.accountRefresh$ = null; // if (!account) { throw throwError('missing_authentication_token'); } // }), // catchError(error => { // this.logoutUser(); // return throwError(error); // })); // } // return this.accountRefresh$.pipe(mergeMap(account => this.repeatRequest(account, req, next))); // } private repeatRequest(account: Account, originalRequest: HttpRequest, next: HttpHandler) { const newAuthenticationToken: String = this.authService.current().token; const newRequest = originalRequest.clone({ setHeaders: { Authorization: `Bearer ${newAuthenticationToken}` } }); return next.handle(newRequest); } 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); } }