1 import { Observable, of, throwError as observableThrowError } from 'rxjs'
2 import { catchError, switchMap } from 'rxjs/operators'
3 import { HTTP_INTERCEPTORS, HttpErrorResponse, HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http'
4 import { Injectable, Injector } from '@angular/core'
5 import { Router } from '@angular/router'
6 import { AuthService } from '@app/core/auth/auth.service'
7 import { HttpStatusCode } from '@shared/models'
8 import { OAuth2ErrorCode, PeerTubeProblemDocument } from '@shared/models/server'
11 export class AuthInterceptor implements HttpInterceptor {
12 private authService: AuthService
14 // https://github.com/angular/angular/issues/18224#issuecomment-316957213
15 constructor (private injector: Injector, private router: Router) {}
17 intercept (req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
18 if (this.authService === undefined) {
19 this.authService = this.injector.get(AuthService)
22 const authReq = this.cloneRequestWithAuth(req)
24 // Pass on the cloned request instead of the original request
25 // Catch 401 errors (refresh token expired)
26 return next.handle(authReq)
28 catchError((err: HttpErrorResponse) => {
29 const error = err.error as PeerTubeProblemDocument
30 const isOTPMissingError = this.authService.isOTPMissingError(err)
32 if (!isOTPMissingError) {
33 if (err.status === HttpStatusCode.UNAUTHORIZED_401 && error && error.code === OAuth2ErrorCode.INVALID_TOKEN) {
34 return this.handleTokenExpired(req, next)
37 if (err.status === HttpStatusCode.UNAUTHORIZED_401) {
38 return this.handleNotAuthenticated(err)
42 return observableThrowError(() => err)
47 private handleTokenExpired (req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
48 return this.authService.refreshAccessToken()
51 const authReq = this.cloneRequestWithAuth(req)
53 return next.handle(authReq)
58 private cloneRequestWithAuth (req: HttpRequest<any>) {
59 const authHeaderValue = this.authService.getRequestHeaderValue()
61 if (authHeaderValue === null) return req
63 // Clone the request to add the new header
64 return req.clone({ headers: req.headers.set('Authorization', authHeaderValue) })
67 private handleNotAuthenticated (err: HttpErrorResponse): Observable<any> {
68 this.router.navigate([ '/401' ], { state: { obj: err }, skipLocationChange: true })
69 return of(err.message)
73 export const AUTH_INTERCEPTOR_PROVIDER = {
74 provide: HTTP_INTERCEPTORS,
75 useClass: AuthInterceptor,