55 lines
1.3 KiB
TypeScript
55 lines
1.3 KiB
TypeScript
import { Injectable, signal, computed } from '@angular/core';
|
|
|
|
const USER_ID_KEY = 'scn_user_id';
|
|
const ADMIN_KEY_KEY = 'scn_admin_key';
|
|
|
|
@Injectable({
|
|
providedIn: 'root'
|
|
})
|
|
export class AuthService {
|
|
private userId = signal<string | null>(null);
|
|
private adminKey = signal<string | null>(null);
|
|
|
|
isAuthenticated = computed(() => !!this.userId() && !!this.adminKey());
|
|
|
|
constructor() {
|
|
this.loadFromStorage();
|
|
}
|
|
|
|
private loadFromStorage(): void {
|
|
const userId = localStorage.getItem(USER_ID_KEY);
|
|
const adminKey = localStorage.getItem(ADMIN_KEY_KEY);
|
|
if (userId && adminKey) {
|
|
this.userId.set(userId);
|
|
this.adminKey.set(adminKey);
|
|
}
|
|
}
|
|
|
|
login(userId: string, adminKey: string): void {
|
|
localStorage.setItem(USER_ID_KEY, userId);
|
|
localStorage.setItem(ADMIN_KEY_KEY, adminKey);
|
|
this.userId.set(userId);
|
|
this.adminKey.set(adminKey);
|
|
}
|
|
|
|
logout(): void {
|
|
localStorage.removeItem(USER_ID_KEY);
|
|
localStorage.removeItem(ADMIN_KEY_KEY);
|
|
this.userId.set(null);
|
|
this.adminKey.set(null);
|
|
}
|
|
|
|
getUserId(): string | null {
|
|
return this.userId();
|
|
}
|
|
|
|
getAdminKey(): string | null {
|
|
return this.adminKey();
|
|
}
|
|
|
|
getAuthHeader(): string | null {
|
|
const key = this.adminKey();
|
|
return key ? `SCN ${key}` : null;
|
|
}
|
|
}
|