59 lines
2.0 KiB
TypeScript
59 lines
2.0 KiB
TypeScript
import { inject, Injectable, Signal, signal } from '@angular/core';
|
|
import { HttpClient } from '@angular/common/http';
|
|
import { LoginView } from '../models/LoginView.model';
|
|
import { firstValueFrom, Observable, tap } from 'rxjs';
|
|
import { Router } from '@angular/router';
|
|
import { EndpointService } from './EndpointService';
|
|
|
|
@Injectable({
|
|
providedIn: 'root',
|
|
})
|
|
export class AuthService {
|
|
private readonly _accessToken = signal<string | null>(null);
|
|
private readonly _username = signal<string | null>(null);
|
|
|
|
public readonly accessToken: Signal<string | null> = this._accessToken;
|
|
public readonly username: Signal<string | null> = this._username;
|
|
|
|
private readonly http = inject(HttpClient);
|
|
private readonly router = inject(Router);
|
|
private readonly endpointService = inject(EndpointService);
|
|
|
|
public async login(username: string, password: string): Promise<LoginView> {
|
|
const loginView = await firstValueFrom(
|
|
this.http.post<LoginView>(
|
|
this.endpointService.getUrl('authLogin'),
|
|
{ username, password },
|
|
{
|
|
withCredentials: true,
|
|
},
|
|
),
|
|
);
|
|
this._accessToken.set(loginView.accessToken);
|
|
this._username.set(loginView.username);
|
|
return loginView;
|
|
}
|
|
|
|
public async logout(): Promise<void> {
|
|
await firstValueFrom(this.http.post(this.endpointService.getUrl('authLogout'), null));
|
|
this._username.set(null);
|
|
this._accessToken.set(null);
|
|
await this.router.navigate(['/']);
|
|
}
|
|
|
|
public refresh(): Observable<LoginView> {
|
|
this._accessToken.set(null);
|
|
this._username.set(null);
|
|
return this.http
|
|
.post<LoginView>(this.endpointService.getUrl('authRefresh'), null, {
|
|
withCredentials: true,
|
|
})
|
|
.pipe(
|
|
tap((loginView) => {
|
|
this._username.set(loginView.username);
|
|
this._accessToken.set(loginView.accessToken);
|
|
}),
|
|
);
|
|
}
|
|
}
|