Front-End-Authentifizierungsdienst und Authentifizierungswächter erstellt.
This commit is contained in:
@@ -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();
|
||||
});
|
||||
});
|
||||
@@ -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;
|
||||
})
|
||||
);
|
||||
};
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
@@ -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`);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user