36 lines
1.2 KiB
TypeScript
36 lines
1.2 KiB
TypeScript
import {Injectable} from '@angular/core';
|
|
import {HttpRequest, HttpHandler, HttpEvent, HttpInterceptor} from '@angular/common/http';
|
|
import {Observable} from 'rxjs';
|
|
|
|
import {AuthService} from '../auth/auth.service';
|
|
|
|
@Injectable()
|
|
export class JwtInterceptor implements HttpInterceptor {
|
|
private isRefreshing = false;
|
|
|
|
constructor(private authService: AuthService) {
|
|
}
|
|
|
|
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
|
|
// add authorization header with jwt token if available
|
|
|
|
// We use this line to debug token refreshing
|
|
// console.log("intercepting:\nisRefreshing: ", this.isRefreshing, "\n user: ", this.authService.user,"\n needsRefreshing: ", this.authService.needsRefreshing());
|
|
if (!this.isRefreshing && this.authService.user && this.authService.needsRefreshing()) {
|
|
this.isRefreshing = true;
|
|
this.authService.refreshToken().subscribe( x => this.isRefreshing = false);
|
|
}
|
|
const currentUser = this.authService.user;
|
|
if (currentUser?.access_token) {
|
|
request = request.clone({
|
|
setHeaders: {
|
|
Authorization: `Bearer ${currentUser.access_token}`
|
|
}
|
|
});
|
|
}
|
|
|
|
|
|
return next.handle(request);
|
|
}
|
|
}
|