1 import { Observable, throwError as observableThrowError } from 'rxjs'
2 import { catchError, switchMap } from 'rxjs/operators'
3 import { Injectable, Injector } from '@angular/core'
4 import { HTTP_INTERCEPTORS, HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http'
5 import { AuthService } from '../../core'
8 export class AuthInterceptor implements HttpInterceptor {
9 private authService: AuthService
11 // https://github.com/angular/angular/issues/18224#issuecomment-316957213
12 constructor (private injector: Injector) {}
14 intercept (req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
15 if (this.authService === undefined) {
16 this.authService = this.injector.get(AuthService)
19 const authReq = this.cloneRequestWithAuth(req)
21 // Pass on the cloned request instead of the original request
22 // Catch 401 errors (refresh token expired)
23 return next.handle(authReq)
26 if (err.status === 401 && err.error && err.error.code === 'invalid_token') {
27 return this.handleTokenExpired(req, next)
30 return observableThrowError(err)
35 private handleTokenExpired (req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
36 return this.authService.refreshAccessToken()
39 const authReq = this.cloneRequestWithAuth(req)
41 return next.handle(authReq)
46 private cloneRequestWithAuth (req: HttpRequest<any>) {
47 const authHeaderValue = this.authService.getRequestHeaderValue()
49 if (authHeaderValue === null) return req
51 // Clone the request to add the new header
52 return req.clone({ headers: req.headers.set('Authorization', authHeaderValue) })
56 export const AUTH_INTERCEPTOR_PROVIDER = {
57 provide: HTTP_INTERCEPTORS,
58 useClass: AuthInterceptor,