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(null); private readonly _username = signal(null); public readonly accessToken: Signal = this._accessToken; public readonly username: Signal = 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 { const loginView = await firstValueFrom( this.http.post( this.endpointService.getUrl('authLogin'), { username, password }, { withCredentials: true, }, ), ); this._accessToken.set(loginView.accessToken); this._username.set(loginView.username); return loginView; } public async logout(): Promise { 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 { this._accessToken.set(null); this._username.set(null); return this.http .post(this.endpointService.getUrl('authRefresh'), null, { withCredentials: true, }) .pipe( tap((loginView) => { this._username.set(loginView.username); this._accessToken.set(loginView.accessToken); }), ); } }