initial release
This commit is contained in:
38
bizmatch/src/app/guards/auth.guard.ts
Normal file
38
bizmatch/src/app/guards/auth.guard.ts
Normal file
@@ -0,0 +1,38 @@
|
||||
import { CanMatchFn, Router, RouterStateSnapshot, UrlTree } from '@angular/router';
|
||||
import { inject } from '@angular/core';
|
||||
|
||||
// Services
|
||||
import { UserService } from '../services/user.service';
|
||||
|
||||
export const authGuard: CanMatchFn = async (route, segments): Promise<boolean | UrlTree> => {
|
||||
const router = inject(Router);
|
||||
const userService = inject(UserService);
|
||||
|
||||
const authenticated: boolean = userService.isLoggedIn();
|
||||
if (!authenticated) {
|
||||
console.log(window.location.origin)
|
||||
console.log(window.location.href)
|
||||
await userService.login(`${window.location.origin}${segments['url']}`);
|
||||
}
|
||||
|
||||
// Get the user Keycloak roles and the required from the route
|
||||
const roles: string[] = userService.getUserRoles();//keycloakService.getUserRoles(true);
|
||||
const requiredRoles = route.data?.['roles'];
|
||||
|
||||
// Allow the user to proceed if no additional roles are required to access the route
|
||||
if (!Array.isArray(requiredRoles) || requiredRoles.length === 0) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Allow the user to proceed if ALL of the required roles are present
|
||||
const authorized = requiredRoles.every((role) => roles.includes(role));
|
||||
// Allow the user to proceed if ONE of the required roles is present
|
||||
//const authorized = requiredRoles.some((role) => roles.includes(role));
|
||||
|
||||
if (authorized) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Display my custom HTTP 403 access denied page
|
||||
return router.createUrlTree(['/access']);
|
||||
};
|
||||
Reference in New Issue
Block a user