generated from nhcarrigan/template
56 lines
1.3 KiB
TypeScript
56 lines
1.3 KiB
TypeScript
/**
|
|
* @copyright 2026 NHCarrigan
|
|
* @license Naomi's Public License
|
|
* @author Naomi Carrigan
|
|
*/
|
|
|
|
import { Injectable, signal } from '@angular/core';
|
|
import { Router } from '@angular/router';
|
|
import { Observable, tap } from 'rxjs';
|
|
import { ApiService } from './api.service';
|
|
import { AuthResponse, User } from '@library/shared-types';
|
|
import { environment } from '../../environments/environment';
|
|
|
|
@Injectable({
|
|
providedIn: 'root'
|
|
})
|
|
export class AuthService {
|
|
private currentUser = signal<User | null>(null);
|
|
public readonly user = this.currentUser.asReadonly();
|
|
|
|
constructor(
|
|
private api: ApiService,
|
|
private router: Router
|
|
) {}
|
|
|
|
login(): void {
|
|
// Redirect to API login endpoint
|
|
window.location.href = `${environment.apiUrl}/auth/login`;
|
|
}
|
|
|
|
getCurrentUser(): Observable<AuthResponse> {
|
|
return this.api.get<AuthResponse>('/auth/me').pipe(
|
|
tap(response => {
|
|
this.currentUser.set(response.user);
|
|
})
|
|
);
|
|
}
|
|
|
|
logout(): Observable<{ message: string }> {
|
|
return this.api.post<{ message: string }>('/auth/logout', {}).pipe(
|
|
tap(() => {
|
|
this.currentUser.set(null);
|
|
this.api.clearCsrfToken();
|
|
this.router.navigate(['/']);
|
|
})
|
|
);
|
|
}
|
|
|
|
isAuthenticated(): boolean {
|
|
return this.user() !== null;
|
|
}
|
|
|
|
isAdmin(): boolean {
|
|
return this.user()?.isAdmin === true;
|
|
}
|
|
} |