]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame_incremental - client/src/app/shared/shared-main/auth/auth-interceptor.service.ts
Stricter email options typings
[github/Chocobozzz/PeerTube.git] / client / src / app / shared / shared-main / auth / auth-interceptor.service.ts
... / ...
CommitLineData
1import { Observable, of, throwError as observableThrowError } from 'rxjs'
2import { catchError, switchMap } from 'rxjs/operators'
3import { HTTP_INTERCEPTORS, HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpErrorResponse } from '@angular/common/http'
4import { Injectable, Injector } from '@angular/core'
5import { AuthService } from '@app/core/auth/auth.service'
6import { Router } from '@angular/router'
7import { HttpStatusCode } from '@shared/core-utils/miscs/http-error-codes'
8
9@Injectable()
10export class AuthInterceptor implements HttpInterceptor {
11 private authService: AuthService
12
13 // https://github.com/angular/angular/issues/18224#issuecomment-316957213
14 constructor (private injector: Injector, private router: Router) {}
15
16 intercept (req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
17 if (this.authService === undefined) {
18 this.authService = this.injector.get(AuthService)
19 }
20
21 const authReq = this.cloneRequestWithAuth(req)
22
23 // Pass on the cloned request instead of the original request
24 // Catch 401 errors (refresh token expired)
25 return next.handle(authReq)
26 .pipe(
27 catchError((err: HttpErrorResponse) => {
28 if (err.status === HttpStatusCode.UNAUTHORIZED_401 && err.error && err.error.code === 'invalid_token') {
29 return this.handleTokenExpired(req, next)
30 } else if (err.status === HttpStatusCode.UNAUTHORIZED_401) {
31 return this.handleNotAuthenticated(err)
32 }
33
34 return observableThrowError(err)
35 })
36 )
37 }
38
39 private handleTokenExpired (req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
40 return this.authService.refreshAccessToken()
41 .pipe(
42 switchMap(() => {
43 const authReq = this.cloneRequestWithAuth(req)
44
45 return next.handle(authReq)
46 })
47 )
48 }
49
50 private cloneRequestWithAuth (req: HttpRequest<any>) {
51 const authHeaderValue = this.authService.getRequestHeaderValue()
52
53 if (authHeaderValue === null) return req
54
55 // Clone the request to add the new header
56 return req.clone({ headers: req.headers.set('Authorization', authHeaderValue) })
57 }
58
59 private handleNotAuthenticated (err: HttpErrorResponse, path = '/login'): Observable<any> {
60 this.router.navigateByUrl(path)
61 return of(err.message)
62 }
63}
64
65export const AUTH_INTERCEPTOR_PROVIDER = {
66 provide: HTTP_INTERCEPTORS,
67 useClass: AuthInterceptor,
68 multi: true
69}