Implement AuthGuard for route protection, integrate authorization checks into particles route, and simplify HeaderComponent access logic. Remove redundant debug logging in auth.service.ts.
This commit is contained in:
@@ -0,0 +1,41 @@
|
||||
import {Injectable} from '@angular/core';
|
||||
import {ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot, UrlTree} from '@angular/router';
|
||||
import {Observable} from 'rxjs';
|
||||
import {AuthService} from '@services/auth.service';
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class AuthGuard implements CanActivate {
|
||||
|
||||
constructor(
|
||||
private authService: AuthService,
|
||||
private router: Router
|
||||
) {
|
||||
}
|
||||
|
||||
canActivate(
|
||||
route: ActivatedRouteSnapshot,
|
||||
state: RouterStateSnapshot
|
||||
): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
|
||||
|
||||
if (!this.authService.checkAuthStatus()) {
|
||||
return this.router.createUrlTree(['/']);
|
||||
}
|
||||
|
||||
const requiredAuthorizations = route.data['requiredAuthorizations'] as string[];
|
||||
|
||||
if (!requiredAuthorizations || requiredAuthorizations.length === 0) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const userAuthorizations = this.authService.getUserAuthorizations();
|
||||
const hasAccess = requiredAuthorizations.some(auth => userAuthorizations.includes(auth));
|
||||
|
||||
if (!hasAccess) {
|
||||
return this.router.createUrlTree(['/']);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user