Implement authentication feature with role-based access control and login dialog

This commit is contained in:
2025-11-07 17:53:11 +01:00
parent 87a1ab06d9
commit b4f0b7256a
11 changed files with 224 additions and 7 deletions

63
src/app/auth.service.ts Normal file
View File

@@ -0,0 +1,63 @@
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;
}
}