|
| 1 | +import { Injectable, inject } from '@angular/core'; |
| 2 | +import { HttpClient } from '@angular/common/http'; |
| 3 | +import { Store } from '@ngxs/store'; |
| 4 | +import { firstValueFrom } from 'rxjs'; |
| 5 | +import { LoginCredentials, AuthResponse } from './auth.entity'; |
| 6 | +import { SetAuthToken, ClearAuth } from '@core/store/auth'; |
| 7 | + |
| 8 | +@Injectable({ |
| 9 | + providedIn: 'root', |
| 10 | +}) |
| 11 | +export class AuthService { |
| 12 | + private readonly API_URL: string = 'VALID_API_URL'; |
| 13 | + private readonly AUTH_TOKEN_KEY: string = ''; |
| 14 | + |
| 15 | + private readonly http: HttpClient = inject(HttpClient); |
| 16 | + private readonly store: Store = inject(Store); |
| 17 | + |
| 18 | + async login(credentials: LoginCredentials): Promise<void> { |
| 19 | + try { |
| 20 | + const response: AuthResponse = await firstValueFrom( |
| 21 | + this.http.post<AuthResponse>(`${this.API_URL}/auth/login`, credentials), |
| 22 | + ); |
| 23 | + |
| 24 | + if (response.accessToken) { |
| 25 | + this.setAuthToken(response.accessToken); |
| 26 | + this.store.dispatch(new SetAuthToken(response.accessToken)); |
| 27 | + } |
| 28 | + } catch (error) { |
| 29 | + console.error('Login failed:', error); |
| 30 | + throw error; |
| 31 | + } |
| 32 | + } |
| 33 | + |
| 34 | + logout(): void { |
| 35 | + localStorage.removeItem(this.AUTH_TOKEN_KEY); |
| 36 | + this.store.dispatch(new ClearAuth()); |
| 37 | + } |
| 38 | + |
| 39 | + getAuthToken(): string | null { |
| 40 | + return localStorage.getItem(this.AUTH_TOKEN_KEY); |
| 41 | + } |
| 42 | + |
| 43 | + private setAuthToken(token: string): void { |
| 44 | + localStorage.setItem(this.AUTH_TOKEN_KEY, token); |
| 45 | + } |
| 46 | + |
| 47 | + private checkInitialAuthState(): void { |
| 48 | + const token: string | null = this.getAuthToken(); |
| 49 | + if (token) { |
| 50 | + this.store.dispatch(new SetAuthToken(token)); |
| 51 | + } |
| 52 | + } |
| 53 | +} |
0 commit comments