initial
This commit is contained in:
3
apps/web/src/app/shared/api-base-url.ts
Normal file
3
apps/web/src/app/shared/api-base-url.ts
Normal file
@@ -0,0 +1,3 @@
|
||||
import { InjectionToken } from '@angular/core';
|
||||
|
||||
export const API_BASE_URL = new InjectionToken<string>('API_BASE_URL');
|
||||
15
apps/web/src/app/shared/api-error.ts
Normal file
15
apps/web/src/app/shared/api-error.ts
Normal file
@@ -0,0 +1,15 @@
|
||||
import { HttpErrorResponse } from '@angular/common/http';
|
||||
|
||||
export function apiErrorMessage(error: unknown): string {
|
||||
if (error instanceof HttpErrorResponse) {
|
||||
const message = error.error?.message;
|
||||
if (Array.isArray(message)) {
|
||||
return message.join(' ');
|
||||
}
|
||||
if (typeof message === 'string') {
|
||||
return message;
|
||||
}
|
||||
}
|
||||
|
||||
return 'Die Anfrage konnte nicht verarbeitet werden.';
|
||||
}
|
||||
42
apps/web/src/app/shared/auth.service.ts
Normal file
42
apps/web/src/app/shared/auth.service.ts
Normal file
@@ -0,0 +1,42 @@
|
||||
import { HttpClient } from '@angular/common/http';
|
||||
import { Inject, Injectable, signal } from '@angular/core';
|
||||
import { Router } from '@angular/router';
|
||||
import { tap } from 'rxjs';
|
||||
import { API_BASE_URL } from './api-base-url';
|
||||
|
||||
interface LoginResponse {
|
||||
accessToken: string;
|
||||
user: {
|
||||
username: string;
|
||||
};
|
||||
}
|
||||
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class AuthService {
|
||||
readonly username = signal<string | null>(localStorage.getItem('username'));
|
||||
|
||||
constructor(
|
||||
private readonly http: HttpClient,
|
||||
private readonly router: Router,
|
||||
@Inject(API_BASE_URL) private readonly apiBaseUrl: string,
|
||||
) {}
|
||||
|
||||
login(username: string, password: string) {
|
||||
return this.http
|
||||
.post<LoginResponse>(`${this.apiBaseUrl}/auth/login`, { username, password })
|
||||
.pipe(
|
||||
tap((response) => {
|
||||
localStorage.setItem('accessToken', response.accessToken);
|
||||
localStorage.setItem('username', response.user.username);
|
||||
this.username.set(response.user.username);
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
logout(): void {
|
||||
localStorage.removeItem('accessToken');
|
||||
localStorage.removeItem('username');
|
||||
this.username.set(null);
|
||||
void this.router.navigateByUrl('/login');
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user