Last active
September 28, 2020 22:36
-
-
Save nicobytes/fde5c7ee6e62c69b6f8bbba5f71e259f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Injectable } from '@angular/core'; | |
import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http'; | |
import { Router } from '@angular/router'; | |
import { Observable, throwError } from 'rxjs'; | |
import { catchError, switchMap } from 'rxjs/operators'; | |
import { AuthService } from '@auth/services/auth.service'; | |
import { TokenService } from '@auth/services/token.service'; | |
@Injectable() | |
export class AuthInterceptor implements HttpInterceptor { | |
constructor( | |
private tokenService: TokenService, | |
private authService: AuthService, | |
private router: Router | |
) { } | |
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { | |
if (request.url.includes('refresh-token')) { | |
return next.handle(this.addRefreshToken(request)); | |
} | |
request = this.addToken(request); | |
return next.handle(request) | |
.pipe( | |
catchError(response => { | |
if (response.status === 401) { | |
return this.authService.refreshToken() | |
.pipe( | |
switchMap(() => next.handle(this.addToken(request))), | |
catchError(msg => { | |
if (msg === 'Token has expired' || msg === 'Missing Authorization Header') { | |
this.authService.logout(); | |
this.router.navigate(['/login']) | |
} | |
return throwError(msg); | |
}) | |
); | |
} | |
return throwError(response); | |
}) | |
); | |
} | |
addRefreshToken(request: HttpRequest<any>) { | |
const token = this.tokenService.getRefreshToken(); | |
if (token) { | |
request = request.clone({ | |
setHeaders: { | |
Authorization: `Bearer ${token}` | |
} | |
}); | |
} | |
return request; | |
} | |
addToken(request: HttpRequest<any>) { | |
const token = this.tokenService.getToken(); | |
if (token) { | |
request = request.clone({ | |
setHeaders: { | |
Authorization: `Bearer ${token}` | |
} | |
}); | |
} | |
return request; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment