import { Injectable , Injector } from '@angular/core' ; import { HttpRequest , HttpHandler , HttpEvent , HttpInterceptor , HttpErrorResponse } from '@angular/common/http' ; import { BehaviorSubject , Observable , throwError } from 'rxjs' ; import { HubstaffService } from './../services/hubstaff.service' ; import { catchError , filter , take , switchMap , finalize } from 'rxjs/operators' ; import { HttpStatus } from '@gauzy/contracts' ; @ Injectable ( ) export class HubstaffTokenInterceptor implements HttpInterceptor { private refreshTokenInProgress = false ; private refreshTokenSubject : BehaviorSubject < any > = new BehaviorSubject < any > ( null ) ; constructor ( private injector ) { } intercept ( req , next ) { if ( ! req . url . includes ( '/integrations/hubstaff/' ) ) { return next . handle ( req ) ; } return next . handle ( req ) . pipe ( catchError ( ( error ) => { if ( error && error . status === HttpStatus . UNAUTHORIZED ) { if ( this . refreshTokenInProgress ) { return this . refreshTokenSubject . pipe ( filter ( ( result ) => result !== null ) , take ( 1 ) , switchMap ( ( { access_token } ) => next . handle ( this . addAuthenticationToken ( req , access_token ) ) ) ) ; } else { this . refreshTokenInProgress = true ; this . refreshTokenSubject . next ( null ) ; return this . refreshAccessToken ( ) . pipe ( switchMap ( ( { access_token } ) => { this . refreshTokenSubject . next ( access_token ) ; return next . handle ( this . addAuthenticationToken ( req , access_token ) ) ; } ) , finalize ( ( ) => ( this . refreshTokenInProgress = false ) ) ) ; } } else { return throwError ( error ) ; } } ) ) ; } private refreshAccessToken ( ) { const hubstaffService = this . injector . get ( HubstaffService ) ; return hubstaffService . refreshToken ( ) ; } private addAuthenticationToken ( request , token ) { return request . clone ( { body : { token } } ) ; } }