Вход: без всплывающего окна браузера — API без токена отвечает 401 без Basic, интерфейс уводит на форму входа
α Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -1,16 +1,22 @@
|
||||
import { HttpInterceptorFn, HttpRequest, HttpHandlerFn } from '@angular/common/http';
|
||||
import { HttpErrorResponse, HttpInterceptorFn, HttpRequest, HttpHandlerFn } from '@angular/common/http';
|
||||
import { inject } from '@angular/core';
|
||||
import { Router } from '@angular/router';
|
||||
import { catchError, throwError } from 'rxjs';
|
||||
|
||||
export const authInterceptor: HttpInterceptorFn = (req: HttpRequest<unknown>, next: HttpHandlerFn) => {
|
||||
const router = inject(Router);
|
||||
const token = localStorage.getItem('token');
|
||||
|
||||
if (token) {
|
||||
const cloned = req.clone({
|
||||
setHeaders: {
|
||||
Authorization: `Bearer ${token}`
|
||||
const request = token ? req.clone({ setHeaders: { Authorization: `Bearer ${token}` } }) : req;
|
||||
|
||||
return next(request).pipe(
|
||||
catchError((error: unknown) => {
|
||||
// not logged in or the token expired → to the login form
|
||||
if (error instanceof HttpErrorResponse && error.status === 401 && !req.url.endsWith('/login')) {
|
||||
localStorage.removeItem('token');
|
||||
localStorage.removeItem('email');
|
||||
router.navigate(['/login']);
|
||||
}
|
||||
});
|
||||
return next(cloned);
|
||||
}
|
||||
|
||||
return next(req);
|
||||
return throwError(() => error);
|
||||
})
|
||||
);
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user