added refresh
This commit is contained in:
@@ -1,16 +1,41 @@
|
||||
import { HttpInterceptorFn } from '@angular/common/http';
|
||||
import {
|
||||
HttpInterceptorFn,
|
||||
HttpErrorResponse
|
||||
} from '@angular/common/http';
|
||||
import { inject } from '@angular/core';
|
||||
import { AuthService } from '../services/auth.service';
|
||||
import { NzNotificationService } from 'ng-zorro-antd/notification';
|
||||
import { catchError, throwError } from 'rxjs';
|
||||
|
||||
export const authInterceptor: HttpInterceptorFn = (req, next) => {
|
||||
const authService = inject(AuthService);
|
||||
const notificationService = inject(NzNotificationService);
|
||||
const token = authService.getToken();
|
||||
|
||||
if (token) {
|
||||
req = req.clone({
|
||||
setHeaders: { Authorization: `Bearer ${token}` }
|
||||
setHeaders: {Authorization: `Bearer ${token}`}
|
||||
});
|
||||
}
|
||||
|
||||
return next(req);
|
||||
return next(req).pipe(
|
||||
catchError((error: HttpErrorResponse) => {
|
||||
if (error.status === 401) {
|
||||
notificationService.error(
|
||||
'Session expirée',
|
||||
'Veuillez vous reconnecter.'
|
||||
);
|
||||
authService.logout?.();
|
||||
}
|
||||
|
||||
if (error.status === 403) {
|
||||
notificationService.error(
|
||||
'Accès refusé',
|
||||
'Vous n’avez pas les droits pour cette action.'
|
||||
);
|
||||
}
|
||||
|
||||
return throwError(() => error);
|
||||
})
|
||||
);
|
||||
};
|
||||
|
||||
@@ -26,4 +26,13 @@ export class AuthService {
|
||||
getToken(): string | null {
|
||||
return localStorage.getItem('jwt');
|
||||
}
|
||||
|
||||
setToken(token: string) {
|
||||
localStorage.setItem('jwt', token);
|
||||
}
|
||||
|
||||
logout() {
|
||||
localStorage.removeItem('jwt');
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user