added interceptor and authService to manage log
This commit is contained in:
@@ -0,0 +1,46 @@
|
||||
import {HttpInterceptorFn, HttpErrorResponse, HttpRequest, HttpHandlerFn} from '@angular/common/http';
|
||||
import {inject} from '@angular/core';
|
||||
import {catchError, switchMap, throwError} from 'rxjs';
|
||||
import {AuthManageService} from "../services/auth-manage";
|
||||
import {AuthService} from "../services/api";
|
||||
|
||||
export const authInterceptor: HttpInterceptorFn = (req: HttpRequest<any>, next: HttpHandlerFn) => {
|
||||
const authManageService = inject(AuthManageService);
|
||||
const authService = inject(AuthService);
|
||||
const token = authManageService.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 authService.refreshTokenEndpoint({token})
|
||||
.pipe(
|
||||
switchMap((res: any) => {
|
||||
authManageService.setToken(res.token);
|
||||
const newReq = req.clone({
|
||||
setHeaders: {Authorization: `Bearer ${res.token}`}
|
||||
});
|
||||
return next(newReq);
|
||||
}),
|
||||
catchError((refreshErr) => {
|
||||
authManageService.logout();
|
||||
console.log('Session expirée', 'Veuillez vous reconnecter.');
|
||||
return throwError(() => refreshErr);
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
if (error.status === 403) {
|
||||
console.log('Accès refusé', 'Vous n’avez pas les droits pour cette action.');
|
||||
}
|
||||
|
||||
return throwError(() => error);
|
||||
})
|
||||
);
|
||||
};
|
||||
Reference in New Issue
Block a user