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

44 lines
1.4 KiB
TypeScript

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
}
}