Spaces:
Running
Running
import { Injectable, inject } from '@angular/core'; | |
import { HttpClient } from '@angular/common/http'; | |
import { Router } from '@angular/router'; | |
import { BehaviorSubject, Observable, tap } from 'rxjs'; | |
interface LoginResponse { | |
token: string; | |
username: string; | |
} | |
({ | |
providedIn: 'root' | |
}) | |
export class AuthService { | |
private http = inject(HttpClient); | |
private router = inject(Router); | |
private tokenKey = 'flare_token'; | |
private usernameKey = 'flare_username'; | |
private loggedInSubject = new BehaviorSubject<boolean>(this.hasToken()); | |
public loggedIn$ = this.loggedInSubject.asObservable(); | |
login(username: string, password: string): Observable<LoginResponse> { | |
return this.http.post<LoginResponse>('/api/login', { username, password }) | |
.pipe( | |
tap(response => { | |
this.setToken(response.token); | |
this.setUsername(response.username); | |
this.loggedInSubject.next(true); | |
}) | |
); | |
} | |
logout(): void { | |
localStorage.removeItem(this.tokenKey); | |
localStorage.removeItem(this.usernameKey); | |
this.loggedInSubject.next(false); | |
this.router.navigate(['/login']); | |
} | |
getToken(): string | null { | |
return localStorage.getItem(this.tokenKey); | |
} | |
getUsername(): string | null { | |
return localStorage.getItem(this.usernameKey); | |
} | |
setToken(token: string): void { | |
localStorage.setItem(this.tokenKey, token); | |
} | |
setUsername(username: string): void { | |
localStorage.setItem(this.usernameKey, username); | |
} | |
hasToken(): boolean { | |
return !!this.getToken(); | |
} | |
isLoggedIn(): boolean { | |
return this.hasToken(); | |
} | |
} |