45 lines
1.2 KiB
TypeScript
45 lines
1.2 KiB
TypeScript
import {Injectable} from '@angular/core';
|
|
import {ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot, UrlTree} from '@angular/router';
|
|
import {Observable} from 'rxjs';
|
|
import {AuthService} from '@services/auth.service';
|
|
import {environment} from '@environment';
|
|
|
|
@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 (environment.defaultAuthStatus) {
|
|
return true;
|
|
}
|
|
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;
|
|
}
|
|
}
|