You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
49 lines
1.4 KiB
49 lines
1.4 KiB
import {
|
|
HttpInterceptorFn,
|
|
HttpRequest,
|
|
HttpHandlerFn,
|
|
HttpEvent,
|
|
HttpErrorResponse,
|
|
} from '@angular/common/http';
|
|
import { Observable, from, throwError } from 'rxjs';
|
|
import { catchError, switchMap } from 'rxjs/operators';
|
|
import { inject } from '@angular/core';
|
|
import { CookiesService } from './services/cookies/cookies.service';
|
|
import { ModalService } from './services/modal/modal.service';
|
|
import { Router } from '@angular/router';
|
|
|
|
export const AuthInterceptor: HttpInterceptorFn = (
|
|
req: HttpRequest<unknown>,
|
|
next: HttpHandlerFn
|
|
): Observable<HttpEvent<unknown>> => {
|
|
// Exclure l'endpoint de refresh token pour éviter la récursion infinie
|
|
if (req.url.includes('/refresh-token')) {
|
|
return next(req);
|
|
}
|
|
|
|
const cookiesService = inject(CookiesService);
|
|
const router = inject(Router);
|
|
const modalService = inject(ModalService);
|
|
|
|
return from(cookiesService.getValidToken()).pipe(
|
|
switchMap((token) => {
|
|
const authReq = token
|
|
? req.clone({
|
|
setHeaders: { Authorization: `Bearer ${token}` },
|
|
})
|
|
: req;
|
|
|
|
return next(authReq);
|
|
}),
|
|
catchError((err: HttpErrorResponse) => {
|
|
if (err.status === 401) {
|
|
cookiesService.clearSession();
|
|
router.navigate(['/']).then(() => {
|
|
modalService.openModal('login-modal');
|
|
});
|
|
}
|
|
return throwError(() => err);
|
|
})
|
|
);
|
|
};
|