feat(client): auth interceptor
This commit is contained in:
@@ -24,15 +24,22 @@ export class APIService {
|
||||
);
|
||||
}
|
||||
logout(): Observable<any>{
|
||||
return this.http.post(`${this.apiUrl}/auth/logout`, {});
|
||||
return this.http.post(`${this.apiUrl}/auth/logout`, {}).pipe(
|
||||
tap({
|
||||
next: () => this.isAuthenticatedSubject.next(false),
|
||||
error: () => this.isAuthenticatedSubject.next(false),
|
||||
})
|
||||
);
|
||||
}
|
||||
clearAuthState() {
|
||||
this.isAuthenticatedSubject.next(false);
|
||||
}
|
||||
checkAuthStatus(): Observable<boolean> {
|
||||
return this.http.get(`${this.apiUrl}/auth/status`).pipe(
|
||||
map(() => true),
|
||||
catchError(() => of(false)),
|
||||
tap({
|
||||
next: () => this.isAuthenticatedSubject.next(true),
|
||||
error: () => this.isAuthenticatedSubject.next(false),
|
||||
tap( authenticated => {
|
||||
this.isAuthenticatedSubject.next(authenticated);
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
17
client/src/app/services/auth-interceptor.spec.ts
Normal file
17
client/src/app/services/auth-interceptor.spec.ts
Normal file
@@ -0,0 +1,17 @@
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { HttpInterceptorFn } from '@angular/common/http';
|
||||
|
||||
import { authInterceptor } from './auth-interceptor';
|
||||
|
||||
describe('authInterceptor', () => {
|
||||
const interceptor: HttpInterceptorFn = (req, next) =>
|
||||
TestBed.runInInjectionContext(() => authInterceptor(req, next));
|
||||
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({});
|
||||
});
|
||||
|
||||
it('should be created', () => {
|
||||
expect(interceptor).toBeTruthy();
|
||||
});
|
||||
});
|
||||
19
client/src/app/services/auth-interceptor.ts
Normal file
19
client/src/app/services/auth-interceptor.ts
Normal file
@@ -0,0 +1,19 @@
|
||||
import { HttpErrorResponse, HttpEventType, HttpInterceptorFn } from '@angular/common/http';
|
||||
import { catchError, throwError } from 'rxjs';
|
||||
import { APIService } from './api';
|
||||
import { inject } from '@angular/core';
|
||||
import { Router } from '@angular/router';
|
||||
|
||||
export const authInterceptor: HttpInterceptorFn = (req, next) => {
|
||||
const api = inject(APIService);
|
||||
const router = inject(Router)
|
||||
return next(req).pipe(
|
||||
catchError((err: HttpErrorResponse) => {
|
||||
if (err.status === 401){
|
||||
api.clearAuthState();
|
||||
router.createUrlTree(['/login']);
|
||||
}
|
||||
return throwError(() => err);
|
||||
})
|
||||
)
|
||||
};
|
||||
Reference in New Issue
Block a user