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

43
src/app/auth.guard.ts Normal file
View File

@@ -0,0 +1,43 @@
import { AuthService, User, UserRole } from './auth.service';
import { inject, Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, CanActivate } from '@angular/router';
import { MatDialog } from '@angular/material/dialog';
import { LoginDialog } from './login/login.dialog';
import { firstValueFrom } from 'rxjs';
@Injectable({ providedIn: 'root' })
export class AuthGuard implements CanActivate {
private auth = inject(AuthService);
private dialog = inject(MatDialog);
async canActivate(route: ActivatedRouteSnapshot): Promise<boolean> {
const allowedRoles: UserRole[] = route.data['roles'];
if (!allowedRoles || allowedRoles.length === 0) {
throw new Error('Keine erlaubten Rollen für diese Route definiert.');
}
const currentUser = this.auth.user()
if (currentUser && allowedRoles.includes(currentUser.role)) {
return true;
}
const roleToLogin = allowedRoles[0]; // Standardmäßig erste Rolle auswählen
const user: User | null = this.auth.getUserDataByRole(roleToLogin);
if (!user) {
throw new Error(`Ungültige Rolle: ${roleToLogin}`);
}
const dialogRef = this.dialog.open(LoginDialog, {
disableClose: true,
backdropClass: 'backdropBackground',
data: { user },
});
const result = await firstValueFrom(dialogRef.afterClosed());
return result === true
}
}