46 lines
1.2 KiB
TypeScript
46 lines
1.2 KiB
TypeScript
import { inject } from '@angular/core';
|
|
import {
|
|
HttpRequest,
|
|
HttpHandlerFn,
|
|
HttpInterceptorFn,
|
|
HttpErrorResponse
|
|
} from '@angular/common/http';
|
|
import { Observable, throwError } from 'rxjs';
|
|
import { catchError } from 'rxjs/operators';
|
|
import { AuthService } from '../services/auth.service';
|
|
import { Router } from '@angular/router';
|
|
|
|
export const authInterceptor: HttpInterceptorFn = (
|
|
request: HttpRequest<unknown>,
|
|
next: HttpHandlerFn
|
|
): Observable<any> => {
|
|
const authService = inject(AuthService);
|
|
const router = inject(Router);
|
|
|
|
// Get the auth token
|
|
const token = authService.getToken();
|
|
|
|
// Clone the request and add the token if it exists
|
|
if (token) {
|
|
const authRequest = request.clone({
|
|
setHeaders: {
|
|
Authorization: `Bearer ${token}`
|
|
}
|
|
});
|
|
|
|
// Handle the authenticated request
|
|
return next(authRequest).pipe(
|
|
catchError((error: HttpErrorResponse) => {
|
|
// Handle 401 Unauthorized errors by logging out and redirecting to login
|
|
if (error.status === 401) {
|
|
authService.logout();
|
|
router.navigate(['/login']);
|
|
}
|
|
return throwError(() => error);
|
|
})
|
|
);
|
|
}
|
|
|
|
// If no token, just pass the request through
|
|
return next(request);
|
|
}; |