From 9c8488febba5de5672106aaf5a88ca0d224b093f Mon Sep 17 00:00:00 2001 From: sgiannopoulos Date: Thu, 12 Oct 2023 18:29:27 +0300 Subject: [PATCH] refresh token for api requests (401) --- .../unauthorized-response.interceptor.ts | 36 ++++++++++++++++--- 1 file changed, 32 insertions(+), 4 deletions(-) diff --git a/dmp-frontend/src/common/http/interceptors/unauthorized-response.interceptor.ts b/dmp-frontend/src/common/http/interceptors/unauthorized-response.interceptor.ts index 76b56c400..d207e126c 100644 --- a/dmp-frontend/src/common/http/interceptors/unauthorized-response.interceptor.ts +++ b/dmp-frontend/src/common/http/interceptors/unauthorized-response.interceptor.ts @@ -1,8 +1,8 @@ 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 { Observable, from, throwError } from 'rxjs'; +import { catchError, filter, mergeMap, tap } from 'rxjs/operators'; import { AuthService } from '../../../app/core/services/auth/auth.service'; import { BaseInterceptor } from './base.interceptor'; import { InterceptorType } from './interceptor-type'; @@ -19,14 +19,15 @@ export class UnauthorizedResponseInterceptor extends BaseInterceptor { 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); } @@ -36,6 +37,33 @@ export class UnauthorizedResponseInterceptor extends BaseInterceptor { })); } + private handle401Error(req: HttpRequest, next: HttpHandler) { + if (!this.accountRefresh$) { + this.accountRefresh$ = from( + this.authService.refreshToken().then((isRefreshed) => { + this.accountRefresh$ = null; + if (!isRefreshed) { + this.logoutUser(); + return false; + } + + return true; + }) + ).pipe(filter((x) => x)); + } + return this.accountRefresh$.pipe(mergeMap(account => this.repeatRequest(req, next))); + } + + private repeatRequest(originalRequest: HttpRequest, next: HttpHandler) { + const newAuthenticationToken: String = this.authService.currentAuthenticationToken(); + 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']); }