Spaces:
Building
Building
import { HttpInterceptorFn, HttpErrorResponse } from '@angular/common/http'; | |
import { inject } from '@angular/core'; | |
import { Router } from '@angular/router'; | |
import { catchError, throwError } from 'rxjs'; | |
import { AuthService } from '../services/auth.service'; | |
export const authInterceptor: HttpInterceptorFn = (req, next) => { | |
const authService = inject(AuthService); | |
const router = inject(Router); | |
// Skip auth for login endpoint | |
if (req.url.includes('/api/login')) { | |
return next(req); | |
} | |
// Add auth token to requests | |
const token = authService.getToken(); | |
if (token) { | |
req = req.clone({ | |
setHeaders: { | |
Authorization: `Bearer ${token}` | |
} | |
}); | |
} | |
return next(req).pipe( | |
catchError((error: HttpErrorResponse) => { | |
if (error.status === 401) { | |
authService.logout(); | |
router.navigate(['/login']); | |
} else if (error.status === 409) { | |
// Race condition - let components handle this | |
console.warn('Race condition detected:', error.error?.detail); | |
} | |
return throwError(() => error); | |
}) | |
); | |
}; |