add login component and auth service

This commit is contained in:
Roland Schneider
2025-11-10 17:33:05 +01:00
parent 327c641137
commit e09110346e
14 changed files with 218 additions and 350 deletions

View File

@@ -0,0 +1,23 @@
import { Injectable } from '@angular/core';
import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree } from '@angular/router';
import { Observable } from 'rxjs';
import { AuthService } from './auth.service';
@Injectable({
providedIn: 'root',
})
export class AuthGuard implements CanActivate {
constructor(private authService: AuthService, private router: Router) {}
canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
if (this.authService.isLoggedIn()) {
return true;
} else {
// Redirect to the login page
return this.router.createUrlTree(['/login']);
}
}
}

View File

@@ -0,0 +1,36 @@
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { tap } from 'rxjs/operators';
@Injectable({
providedIn: 'root',
})
export class AuthService {
private readonly TOKEN_KEY = 'access_token';
private apiUrl = 'http://localhost:3000/auth'; // Adjust if your server URL is different
constructor(private http: HttpClient) {}
login(credentials: { username: string; password: string }): Observable<any> {
return this.http.post<{ access_token: string }>(`${this.apiUrl}/login`, credentials).pipe(
tap((response) => this.setToken(response.access_token))
);
}
logout(): void {
localStorage.removeItem(this.TOKEN_KEY);
}
getToken(): string | null {
return localStorage.getItem(this.TOKEN_KEY);
}
isLoggedIn(): boolean {
return this.getToken() !== null;
}
private setToken(token: string): void {
localStorage.setItem(this.TOKEN_KEY, token);
}
}

View File

@@ -0,0 +1,29 @@
import { Injectable } from '@angular/core';
import {
HttpEvent,
HttpHandler,
HttpInterceptor,
HttpRequest,
} from '@angular/common/http';
import { Observable } from 'rxjs';
import { AuthService } from './auth.service';
@Injectable()
export class JwtInterceptor implements HttpInterceptor {
constructor(private authService: AuthService) {}
intercept(
request: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
const token = this.authService.getToken();
if (token) {
request = request.clone({
setHeaders: {
Authorization: `Bearer ${token}`,
},
});
}
return next.handle(request);
}
}