added refresh

This commit is contained in:
2025-12-08 12:51:25 +01:00
parent f2a9f24bd5
commit b2aa7bdfdb

View File

@@ -4,32 +4,53 @@ import {
} from '@angular/common/http';
import { inject } from '@angular/core';
import { AuthService } from '../services/auth.service';
import { RefreshService, RefreshTokenDto } from '../services/api';
import { NzNotificationService } from 'ng-zorro-antd/notification';
import { catchError, throwError } from 'rxjs';
import { catchError, switchMap, throwError } from 'rxjs';
export const authInterceptor: HttpInterceptorFn = (req, next) => {
const authService = inject(AuthService);
const notificationService = inject(NzNotificationService);
const refreshService = inject(RefreshService);
const notification = inject(NzNotificationService);
const token = authService.getToken();
if (token) {
req = req.clone({
setHeaders: {Authorization: `Bearer ${token}`}
setHeaders: { Authorization: `Bearer ${token}` }
});
}
return next(req).pipe(
catchError((error: HttpErrorResponse) => {
if (error.status === 401) {
notificationService.error(
'Session expirée',
'Veuillez vous reconnecter.'
if (error.status === 401 && token) {
const dto: RefreshTokenDto = { token };
return refreshService.refreshTokenEndpoint(dto).pipe(
switchMap((res) => {
const newToken = res.token;
if (!newToken) {
notification.error('Erreur', 'Impossible de rafraîchir le token.');
authService.logout();
return throwError(() => error);
}
authService.setToken(newToken);
const retryReq = req.clone({
setHeaders: { Authorization: `Bearer ${newToken}` }
});
return next(retryReq);
}),
catchError(() => {
notification.error('Erreur', 'Session expirée, veuillez vous reconnecter.');
authService.logout();
return throwError(() => error);
})
);
authService.logout?.();
}
if (error.status === 403) {
notificationService.error(
notification.error(
'Accès refusé',
'Vous navez pas les droits pour cette action.'
);