added refresh

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

View File

@@ -4,12 +4,15 @@ import {
} from '@angular/common/http'; } from '@angular/common/http';
import { inject } from '@angular/core'; import { inject } from '@angular/core';
import { AuthService } from '../services/auth.service'; import { AuthService } from '../services/auth.service';
import { RefreshService, RefreshTokenDto } from '../services/api';
import { NzNotificationService } from 'ng-zorro-antd/notification'; import { NzNotificationService } from 'ng-zorro-antd/notification';
import { catchError, throwError } from 'rxjs'; import { catchError, switchMap, throwError } from 'rxjs';
export const authInterceptor: HttpInterceptorFn = (req, next) => { export const authInterceptor: HttpInterceptorFn = (req, next) => {
const authService = inject(AuthService); const authService = inject(AuthService);
const notificationService = inject(NzNotificationService); const refreshService = inject(RefreshService);
const notification = inject(NzNotificationService);
const token = authService.getToken(); const token = authService.getToken();
if (token) { if (token) {
@@ -20,16 +23,34 @@ export const authInterceptor: HttpInterceptorFn = (req, next) => {
return next(req).pipe( return next(req).pipe(
catchError((error: HttpErrorResponse) => { catchError((error: HttpErrorResponse) => {
if (error.status === 401) { if (error.status === 401 && token) {
notificationService.error( const dto: RefreshTokenDto = { token };
'Session expirée',
'Veuillez vous reconnecter.' 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) { if (error.status === 403) {
notificationService.error( notification.error(
'Accès refusé', 'Accès refusé',
'Vous navez pas les droits pour cette action.' 'Vous navez pas les droits pour cette action.'
); );