Files
grimmory/booklore-ui/src/app/auth-interceptor.service.ts
T
aditya.chandel 39616dabd7 - Create UserCreation service
- Logout and redirect to login page when token expires
2025-03-07 21:34:35 -07:00

30 lines
883 B
TypeScript

import {HttpInterceptorFn} from '@angular/common/http';
import {inject} from '@angular/core';
import {Router} from '@angular/router';
import {HttpErrorResponse} from '@angular/common/http';
import {catchError} from 'rxjs/operators';
import {throwError} from 'rxjs';
import {AuthService} from './core/service/auth.service';
export const AuthInterceptorService: HttpInterceptorFn = (req, next) => {
const authService = inject(AuthService);
const router = inject(Router);
const token = localStorage.getItem('token');
if (token) {
req = req.clone({
setHeaders: {Authorization: `Bearer ${token}`}
});
}
return next(req).pipe(
catchError((error: HttpErrorResponse) => {
if (error.status === 403 || error.status === 401) {
authService.logout();
router.navigate(['/login']);
}
return throwError(() => error);
})
);
};