49 lines
1.3 KiB
TypeScript
49 lines
1.3 KiB
TypeScript
import { Injectable, inject } from '@angular/core';
|
|
import { HttpClient } from '@angular/common/http';
|
|
import { Observable, firstValueFrom, tap } from 'rxjs';
|
|
import { API_URL } from '../tokens/index';
|
|
|
|
@Injectable({
|
|
providedIn: 'root'
|
|
})
|
|
export class AuthService {
|
|
private url: string;
|
|
|
|
constructor(private http: HttpClient) {
|
|
const api_url = inject(API_URL);
|
|
this.url = `${api_url}/auth`;
|
|
}
|
|
|
|
login(credentials: { username: string; password: string }): Observable<any> {
|
|
return this.http.post(`${this.url}/login`, credentials).pipe(
|
|
tap({
|
|
next: res => this.#IsAuthenticated = true,
|
|
error: () => this.#IsAuthenticated = false
|
|
})
|
|
)
|
|
}
|
|
|
|
logout(): Observable<any> {
|
|
return this.http.post(`${this.url}/logout`, {}).pipe(
|
|
tap({
|
|
next: res => this.#IsAuthenticated = false,
|
|
error: () => this.#IsAuthenticated = true
|
|
})
|
|
);
|
|
}
|
|
|
|
async logoutAsync(): Promise<void> {
|
|
return await firstValueFrom(this.logout());
|
|
}
|
|
|
|
isAuthenticated(): Observable<boolean> {
|
|
return this.http.get<boolean>(`${this.url}/check`).pipe(
|
|
tap(isAuthenticated => this.#IsAuthenticated = isAuthenticated)
|
|
);
|
|
}
|
|
|
|
#IsAuthenticated = false;
|
|
get IsAuthenticated(): boolean {
|
|
return this.#IsAuthenticated;
|
|
}
|
|
} |