Guest User

Untitled

a guest
Mar 13th, 2023
53
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import { Injectable } from '@angular/core';
  2. import {ActivatedRouteSnapshot, Router,  RouterStateSnapshot} from '@angular/router';
  3. import { KeycloakAuthGuard, KeycloakService } from 'keycloak-angular';
  4.  
  5. @Injectable({
  6.   providedIn: 'root'
  7. })
  8. export class AuthGuard extends KeycloakAuthGuard {
  9.   constructor(
  10.     protected override readonly router: Router,
  11.     protected readonly keycloak: KeycloakService
  12.   ) {
  13.     super(router, keycloak);
  14.   }
  15.  
  16.   public async isAccessAllowed(
  17.     route: ActivatedRouteSnapshot,
  18.     state: RouterStateSnapshot
  19.   ) : Promise <boolean>{
  20.     // Force the user to log in if currently unauthenticated.
  21.     if (!this.authenticated) {
  22.       await this.keycloak.login({
  23.         redirectUri: window.location.origin
  24.       });
  25.     }
  26.  
  27.     // Get the roles required from the route.
  28.     const requiredRoles = route.data['roles'] ;
  29.  
  30.     // Allow the user to proceed if no additional roles are required to access the route.
  31.     if (!(requiredRoles instanceof Array) || requiredRoles.length === 0) {
  32.       return true;
  33.     }
  34.  
  35.     // Allow the user to proceed if all the required roles are present.
  36.     return requiredRoles.every((role) => this.roles.includes(role));
  37.   }
  38. }
  39.  
Add Comment
Please, Sign In to add comment