77 lines
2.3 KiB
TypeScript
77 lines
2.3 KiB
TypeScript
import {HTTP_INTERCEPTORS, HttpErrorResponse, HttpEvent} from '@angular/common/http';
|
|
import { Injectable } from '@angular/core';
|
|
import { HttpInterceptor, HttpHandler, HttpRequest } from '@angular/common/http';
|
|
|
|
import { TokenStorageService } from '../services/token-storage.service';
|
|
import {catchError, Observable, switchMap, throwError} from 'rxjs';
|
|
import {EventBusService} from '../_shared/event-bus.service';
|
|
import {EventData} from '../_shared/event.class';
|
|
import {environment} from '../../environments/environment';
|
|
import {AuthService} from '../services/auth.service';
|
|
|
|
const TOKEN_HEADER_KEY = 'Authorization'; // for Spring Boot back-end
|
|
|
|
@Injectable()
|
|
export class AuthInterceptor implements HttpInterceptor {
|
|
private isRefreshing = false;
|
|
enviorment = environment;
|
|
|
|
constructor(
|
|
private tokenStorageService: TokenStorageService,
|
|
private eventBusService: EventBusService,
|
|
private authService:AuthService
|
|
) { }
|
|
|
|
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
|
|
|
|
// req = req.clone({
|
|
// withCredentials: true,
|
|
// });
|
|
|
|
return next.handle(req).pipe(
|
|
catchError((error) => {
|
|
if (
|
|
error instanceof HttpErrorResponse &&
|
|
!req.url.includes('auth/signin') &&
|
|
(error.status === 401) /// must be only 401 without 500 and 0
|
|
) {
|
|
return this.handle401Error(req, next);
|
|
}
|
|
|
|
return throwError(() => error);
|
|
})
|
|
);
|
|
}
|
|
|
|
private handle401Error(request: HttpRequest<any>, next: HttpHandler) {
|
|
if (!this.isRefreshing) {
|
|
this.isRefreshing = true;
|
|
|
|
if (this.tokenStorageService.isLoggedIn()) {
|
|
return this.authService.refreshToken().pipe(
|
|
switchMap(() => {
|
|
this.isRefreshing = false;
|
|
console.log("refresh token");
|
|
return next.handle(request);
|
|
}),
|
|
catchError((error) => {
|
|
this.isRefreshing = false;
|
|
|
|
if (error.status == '403') {
|
|
this.eventBusService.emit(new EventData('logout', null));
|
|
}
|
|
|
|
return throwError(() => error);
|
|
})
|
|
);
|
|
}
|
|
}
|
|
|
|
return next.handle(request);
|
|
}
|
|
}
|
|
|
|
export const authInterceptorProviders = [
|
|
{ provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true }
|
|
];
|