waiting for initialization

This commit is contained in:
2024-05-22 13:32:17 -05:00
parent 7fdc87fb0b
commit d6768b3da9
4 changed files with 190 additions and 39 deletions

View File

@@ -1,8 +1,9 @@
import { Injectable } from '@angular/core';
import { Router, UrlTree } from '@angular/router';
import { ActivatedRouteSnapshot, Router, RouterStateSnapshot, UrlTree } from '@angular/router';
import { KeycloakAuthGuard, KeycloakService } from 'keycloak-angular';
import { KeycloakInitializerService } from '../services/keycloak-initializer.service';
import { createLogger } from '../utils/utils';
const logger = createLogger('AuthGuard');
@Injectable({
providedIn: 'root',
})
@@ -11,14 +12,30 @@ export class AuthGuard extends KeycloakAuthGuard {
super(router, keycloak);
}
async isAccessAllowed(): Promise<boolean | UrlTree> {
if (!this.keycloakInitializer.isInitialized()) {
await this.keycloakInitializer.initialize();
async isAccessAllowed(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<boolean | UrlTree> {
logger.info(`--->AuthGuard`);
while (!this.keycloakInitializer.initialized) {
logger.info(`Waiting 100 msec`);
await new Promise(resolve => setTimeout(resolve, 100));
}
// Force the user to log in if currently unauthenticated.
const authenticated = this.keycloak.isLoggedIn();
if (!authenticated) {
await this.router.navigate(['/home']);
if (!this.authenticated && !authenticated) {
await this.keycloak.login({
redirectUri: window.location.origin + state.url,
});
// return false;
}
return authenticated;
// Get the roles required from the route.
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 the required roles are present.
return requiredRoles.every(role => this.roles.includes(role));
}
}