initial
This commit is contained in:
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