61 lines
2.3 KiB
TypeScript
61 lines
2.3 KiB
TypeScript
import { AuthGuardData, createAuthGuard, KeycloakService } from 'keycloak-angular';
|
|
import { ActivatedRouteSnapshot, CanActivateFn, Router, RouterStateSnapshot, UrlTree } from '@angular/router';
|
|
import { inject } from '@angular/core';
|
|
import { appConfig } from '../../app.config';
|
|
import Keycloak from 'keycloak-js';
|
|
|
|
/**
|
|
* The logic below is a simple example, please make it more robust when implementing in your application.
|
|
*
|
|
* Reason: isAccessGranted is not validating the resource, since it is merging all roles. Two resources might
|
|
* have the same role name, and it makes sense to validate it more granular.
|
|
*/
|
|
const isAccessAllowed = async (
|
|
route: ActivatedRouteSnapshot,
|
|
__: RouterStateSnapshot,
|
|
authData: AuthGuardData
|
|
): Promise<boolean | UrlTree> => {
|
|
const marker_start = '======================= auth.guard >>> =======================';
|
|
const marker_end = '\n======================= <<< auth.guard =======================';
|
|
console.debug(marker_start);
|
|
|
|
const { authenticated, grantedRoles } = authData;
|
|
console.debug('authData', authData);
|
|
// console.debug('authenticated', authenticated);
|
|
// console.debug('grantedRoles', grantedRoles);
|
|
// console.debug('grantedRoles - realmRoles', grantedRoles.realmRoles);
|
|
// console.debug('grantedRoles - resourceRoles', grantedRoles.resourceRoles);
|
|
|
|
const requiredRole = route.data['role'];
|
|
// console.debug('requiredRole', requiredRole);
|
|
|
|
if (!requiredRole) {
|
|
// console.debug('No role required for this route.');
|
|
return false;
|
|
}
|
|
|
|
const router = inject(Router);
|
|
const notAllowed = router.parseUrl('/auth/access');
|
|
const keycloak = inject(Keycloak);
|
|
|
|
if (!authenticated) {
|
|
console.debug('you are not authenticated. please authenticate first.' + marker_end);
|
|
// await keycloak.login({ redirectUri: window.location.href });
|
|
return notAllowed;
|
|
}
|
|
|
|
const hasRequiredRealmRole = requiredRole.some((role: string) => {
|
|
return grantedRoles.realmRoles.includes(role);
|
|
});
|
|
if (hasRequiredRealmRole) {
|
|
console.debug('you have the required realm role' + marker_end);
|
|
return true;
|
|
}
|
|
|
|
console.debug('you do not have permission to visit this page.' + marker_end);
|
|
return notAllowed;
|
|
};
|
|
|
|
// @ts-ignore
|
|
export const canActivateAuthRole = createAuthGuard<CanActivateFn>(isAccessAllowed);
|