44 lines
1.3 KiB
TypeScript
44 lines
1.3 KiB
TypeScript
import { HttpClient } from '@angular/common/http';
|
|
import { Inject, Injectable, signal } from '@angular/core';
|
|
import { Router } from '@angular/router';
|
|
import { catchError, EMPTY, 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 {
|
|
this.http.post<void>(`${this.apiBaseUrl}/auth/logout`, {}).pipe(catchError(() => EMPTY)).subscribe();
|
|
localStorage.removeItem('accessToken');
|
|
localStorage.removeItem('username');
|
|
this.username.set(null);
|
|
void this.router.navigateByUrl('/login');
|
|
}
|
|
}
|