aboutsummaryrefslogtreecommitdiffhomepage
path: root/client/src/app/shared/auth/auth-interceptor.service.ts
blob: 1e890d8f3846cba5003b871d62dda1f8da3c3dae (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import { Injectable, Injector } from '@angular/core'
import {
  HttpInterceptor,
  HttpRequest,
  HttpEvent,
  HttpHandler, HTTP_INTERCEPTORS
} from '@angular/common/http'
import { Observable } from 'rxjs/Observable'

import { AuthService } from '../../core'
import 'rxjs/add/operator/switchMap'

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
  private authService: AuthService

  // https://github.com/angular/angular/issues/18224#issuecomment-316957213
  constructor (private injector: Injector) {}

  intercept (req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    if (this.authService === undefined) {
      this.authService = this.injector.get(AuthService)
    }

    const authReq = this.cloneRequestWithAuth(req)

    // Pass on the cloned request instead of the original request
    // Catch 401 errors (refresh token expired)
    return next.handle(authReq)
               .catch(err => {
                 if (err.status === 401) {
                   return this.handleTokenExpired(req, next)
                 }

                 return Observable.throw(err)
               })
  }

  private handleTokenExpired (req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return this.authService.refreshAccessToken()
                           .switchMap(() => {
                             const authReq = this.cloneRequestWithAuth(req)

                             return next.handle(authReq)
                           })
  }

  private cloneRequestWithAuth (req: HttpRequest<any>) {
    const authHeaderValue = this.authService.getRequestHeaderValue()

    if (authHeaderValue === null) return req

    // Clone the request to add the new header
    return req.clone({ headers: req.headers.set('Authorization', authHeaderValue) })
  }
}

export const AUTH_INTERCEPTOR_PROVIDER = {
  provide: HTTP_INTERCEPTORS,
  useClass: AuthInterceptor,
  multi: true
}