Front-End-Authentifizierungsdienst und Authentifizierungswächter erstellt.

This commit is contained in:
Developer 02
2024-06-13 17:01:38 +02:00
parent 4d040959a5
commit 5f161d81f2
4 changed files with 79 additions and 0 deletions

View 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();
});
});

View File

@@ -0,0 +1,19 @@
// src/app/guards/auth.guard.ts
import { inject } from '@angular/core';
import { CanActivateFn, Router } from '@angular/router';
import { AuthService } from '../services/auth.service';
import { map } from 'rxjs/operators';
import { Observable } from 'rxjs';
export const authGuard: CanActivateFn = (route, state) => {
const authService = inject(AuthService);
const router = inject(Router);
return authService.isAuthenticated().pipe(
map(isAuthenticated => {
if (!isAuthenticated) {
router.navigate(['/']);
}
return isAuthenticated;
})
);
};

View File

@@ -0,0 +1,16 @@
import { TestBed } from '@angular/core/testing';
import { AuthService } from './auth.service';
describe('AuthService', () => {
let service: AuthService;
beforeEach(() => {
TestBed.configureTestingModule({});
service = TestBed.inject(AuthService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
});

View File

@@ -0,0 +1,27 @@
import { Injectable, Inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { APP_BASE_HREF } from '@angular/common';
@Injectable({
providedIn: 'root'
})
export class AuthService {
private baseUrl: string;
constructor(private http: HttpClient, @Inject(APP_BASE_HREF) baseHref: string) {
this.baseUrl = `${baseHref}api/auth`;
}
login(credentials: { username: string; password: string }): Observable<any> {
return this.http.post(`${this.baseUrl}api/login`, credentials);
}
logout(): Observable<any> {
return this.http.post(`${this.baseUrl}api/logout`, {});
}
isAuthenticated(): Observable<boolean> {
return this.http.get<boolean>(`${this.baseUrl}api/check`);
}
}