fix(interceptor): added missing files

This commit is contained in:
2025-01-24 14:23:27 +01:00
parent 1d94fb28e1
commit c03705c2cc
2 changed files with 76 additions and 0 deletions

View File

@ -0,0 +1,16 @@
import { TestBed } from '@angular/core/testing';
import { AuthInterceptor } from './auth.interceptor';
describe('AuthInterceptor', () => {
beforeEach(() =>
TestBed.configureTestingModule({
providers: [AuthInterceptor],
})
);
it('should be created', () => {
const interceptor: AuthInterceptor = TestBed.inject(AuthInterceptor);
expect(interceptor).toBeTruthy();
});
});

View File

@ -0,0 +1,60 @@
import { Injectable } from '@angular/core';
import {
HttpRequest,
HttpHandler,
HttpEvent,
HttpInterceptor,
HttpResponse,
HttpErrorResponse,
} from '@angular/common/http';
import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';
function logout() {
localStorage.removeItem('id_token');
localStorage.removeItem('id_session');
location.href = '/login';
}
function handle_request(handler: HttpHandler, req: HttpRequest<any>) {
return handler.handle(req).pipe(
tap(
(event: HttpEvent<any>) => {
if (event instanceof HttpResponse) {
// console.log(cloned);
// console.log("Service Response thr Interceptor");
}
},
(err: any) => {
if (err instanceof HttpErrorResponse) {
console.log('err.status', err);
if (err.status === 401) {
logout();
}
}
}
)
);
}
@Injectable({
providedIn: 'root',
})
export class AuthInterceptor implements HttpInterceptor {
intercept(
req: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
const idToken = localStorage.getItem('id_token');
if (idToken) {
const cloned = req.clone({
headers: req.headers.set('Authorization', 'Bearer ' + idToken),
});
return handle_request(next, cloned);
} else {
return handle_request(next, req);
}
}
}