69 lines
2.6 KiB
TypeScript
69 lines
2.6 KiB
TypeScript
import { Injectable } from '@angular/core';
|
|
import {
|
|
CanActivate, Router, CanLoad, Route, CanActivateChild ,
|
|
ActivatedRouteSnapshot,
|
|
RouterStateSnapshot
|
|
} from '@angular/router';
|
|
|
|
|
|
import { Store } from '@ngrx/store';
|
|
import { OAuthService } from 'angular-oauth2-oidc';
|
|
|
|
|
|
import * as appCommonReducer from '../reducers/app-common.reducer'
|
|
import * as appCommonActions from '../actions/app-common.actions';
|
|
|
|
|
|
@Injectable({
|
|
providedIn: 'root',
|
|
})
|
|
export class AuthGuard implements CanActivate, CanLoad, CanActivateChild {
|
|
|
|
constructor(private oauthService: OAuthService, private router: Router, private store: Store<appCommonReducer.State> ) { }
|
|
|
|
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<boolean> {
|
|
console.debug("AuthGuard->canActivate", route, state);
|
|
const url: string = state.url;
|
|
|
|
return this.checkLogin(url, route);
|
|
}
|
|
|
|
canActivateChild(childRoute: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<boolean> {
|
|
console.debug("AuthGuard->canActivateChild", childRoute, state);
|
|
const url: string = state.url;
|
|
|
|
return this.checkLogin(url, childRoute);
|
|
}
|
|
|
|
canLoad(route: Route): Promise<boolean> {
|
|
console.debug("AuthGuard->canLoad", route);
|
|
return this.checkLogin(route.path, null);
|
|
}
|
|
|
|
checkLogin(url: string, route: ActivatedRouteSnapshot): Promise<boolean> {
|
|
console.debug("AuthGuard->checkLogin", url, route);
|
|
return new Promise<boolean>((resolve) => {
|
|
if (!this.oauthService.hasValidAccessToken()) {
|
|
console.debug("No valid token");
|
|
this.oauthService.initCodeFlow(url);
|
|
resolve(false);
|
|
} else {
|
|
const requiredRoleClaim = route.data.role;
|
|
if (!requiredRoleClaim) { resolve(true); }
|
|
const ownedClaims = this.oauthService.getIdentityClaims();
|
|
if (!ownedClaims) { console.debug("No owned claims"); resolve(false); }
|
|
const ownedRoleClaims: string[] = ownedClaims['role'];
|
|
if (!ownedRoleClaims) { console.debug("No owned role claims"); resolve(false); }
|
|
if (Array.isArray(ownedRoleClaims)) {
|
|
if (ownedRoleClaims.findIndex(r => r === requiredRoleClaim) <= -1) { console.debug("No required role claim", ownedRoleClaims, requiredRoleClaim); resolve(false); }
|
|
}
|
|
else {
|
|
if (ownedRoleClaims !== requiredRoleClaim) { console.debug("No required role claim", ownedRoleClaims, requiredRoleClaim); resolve(false); }
|
|
}
|
|
console.debug("Has required role claim", requiredRoleClaim);
|
|
resolve(true);
|
|
}
|
|
});
|
|
}
|
|
}
|