Files
frontend/src/app/auth.service.ts

64 lines
1.6 KiB
TypeScript

import { Injectable, signal } from '@angular/core';
import { Router } from '@angular/router';
export type UserRole = 'admin' | 'employee';
export interface User {
role: UserRole;
displayName: string;
}
@Injectable({
providedIn: 'root',
})
export class AuthService {
private readonly SESSION_KEY = 'userRole';
private readonly USERS: Record<UserRole, { password: string; displayName: string }> = {
admin: { password: 'admin123', displayName: 'Admin' },
employee: { password: 'employee123', displayName: 'Mitarbeiter' },
};
user = signal<User | null>(this.loadUserFromSession());
constructor(private router: Router) {}
private loadUserFromSession(): User | null {
const stored = sessionStorage.getItem(this.SESSION_KEY);
return stored ? JSON.parse(stored) as User : null;
}
login(role: UserRole, password: string): boolean {
const user = this.USERS[role];
if (!user) {
return false
};
if (password === user.password) {
const userObj: User = { role, displayName: user.displayName };
sessionStorage.setItem(this.SESSION_KEY, JSON.stringify(userObj));
this.user.set(userObj);
return true;
}
return false;
}
logout() {
sessionStorage.removeItem(this.SESSION_KEY);
this.user.set(null);
this.router.navigate(['/']);
}
getUserDataByRole(role: UserRole): User | null {
const userDef = this.USERS[role];
return userDef ? { role, displayName: userDef.displayName } : null;
}
isLoggedIn(role?: UserRole): boolean {
const current = this.user();
if (!current) return false;
return role ? current.role === role : true;
}
}