auth guard
This commit is contained in:
@@ -23,7 +23,7 @@ export class APIService {
|
||||
return this.http.post(this.apiUrl + '/auth/logout', {});
|
||||
}
|
||||
checkAuthStatus(): Observable<boolean> {
|
||||
return this.http.get(`${this.apiUrl}/auth/status`, { withCredentials: true }).pipe(
|
||||
return this.http.get(`${this.apiUrl}/auth/status`, { withCredentials: true}).pipe(
|
||||
map(() => true),
|
||||
catchError(() => of(false)),
|
||||
tap({
|
||||
|
||||
17
client/src/app/services/auth-guard.spec.ts
Normal file
17
client/src/app/services/auth-guard.spec.ts
Normal file
@@ -0,0 +1,17 @@
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { CanActivateFn } from '@angular/router';
|
||||
|
||||
import { authGuard } from './auth-guard';
|
||||
|
||||
describe('authGuard', () => {
|
||||
const executeGuard: CanActivateFn = (...guardParameters) =>
|
||||
TestBed.runInInjectionContext(() => authGuard(...guardParameters));
|
||||
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({});
|
||||
});
|
||||
|
||||
it('should be created', () => {
|
||||
expect(executeGuard).toBeTruthy();
|
||||
});
|
||||
});
|
||||
20
client/src/app/services/auth-guard.ts
Normal file
20
client/src/app/services/auth-guard.ts
Normal file
@@ -0,0 +1,20 @@
|
||||
import { inject } from '@angular/core';
|
||||
import { CanActivateFn, Router } from '@angular/router';
|
||||
import { APIService } from './api';
|
||||
import { map } from 'rxjs/operators';
|
||||
|
||||
export const authGuard: CanActivateFn = (route, state) => {
|
||||
const api = inject(APIService);
|
||||
const router = inject(Router);
|
||||
|
||||
return api.isAuthenticated$.pipe(
|
||||
map((isAuthenticated) => {
|
||||
if (isAuthenticated) {
|
||||
return true;
|
||||
} else {
|
||||
router.navigate(['/login'], { queryParams: { returnUrl: state.url } });
|
||||
return false;
|
||||
}
|
||||
})
|
||||
);
|
||||
};
|
||||
Reference in New Issue
Block a user