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, 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 n’avez pas les droits pour cette action.'); } return throwError(() => error); }) ); };