Files
pyrofetes-frontend/src/app/interceptors/auth-interceptor.ts
T
2026-05-28 14:27:46 +01:00

48 lines
1.9 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import {HttpInterceptorFn, HttpErrorResponse, HttpRequest, HttpHandlerFn} from '@angular/common/http';
import {inject} from '@angular/core';
import {AuthService} from '../services/auth.service';
import {RefreshService} from '../services/api';
import {NzNotificationService} from 'ng-zorro-antd/notification';
import {catchError, switchMap, throwError} from 'rxjs';
export const authInterceptor: HttpInterceptorFn = (req: HttpRequest<any>, next: HttpHandlerFn) => {
const authService = inject(AuthService);
const refreshService = inject(RefreshService);
const notification = inject(NzNotificationService);
const token = authService.getToken();
let authReq = req;
if (token) {
authReq = req.clone({
setHeaders: {Authorization: `Bearer ${token}`}
});
}
return next(authReq).pipe(
catchError((error: HttpErrorResponse) => {
if (error.status === 401 && token) {
return refreshService.refreshTokenEndpoint({token})
.pipe(
switchMap((res: any) => {
authService.setToken(res.token);
const newReq = req.clone({
setHeaders: {Authorization: `Bearer ${res.token}`}
});
return next(newReq);
}),
catchError((refreshErr) => {
authService.logout();
notification.error('Session expirée', 'Veuillez vous reconnecter.');
return throwError(() => refreshErr);
})
);
}
if (error.status === 403) {
notification.error('Accès refusé', 'Vous navez pas les droits pour cette action.');
}
return throwError(() => error);
})
);
};