import { IqserAppConfig, UI_ROOT } from '../utils'; import { KeycloakOptions, KeycloakService } from 'keycloak-angular'; import { KeycloakStatusService } from './services/keycloak-status.service'; import { inject } from '@angular/core'; import { getConfig } from '../services'; import { NGXLogger } from 'ngx-logger'; import { Router } from '@angular/router'; export function getKeycloakOptions(baseUrl: string, config: IqserAppConfig, tenant: string): KeycloakOptions { let oauthUrl = config.OAUTH_URL; if (!oauthUrl.startsWith('http')) { oauthUrl = oauthUrl.startsWith('/') ? oauthUrl : '/' + oauthUrl; oauthUrl = window.location.origin + oauthUrl; } return { config: { url: oauthUrl, realm: tenant, clientId: config.OAUTH_CLIENT_ID, }, initOptions: { checkLoginIframe: false, onLoad: 'check-sso', silentCheckSsoRedirectUri: window.location.origin + baseUrl + '/assets/oauth/silent-refresh.html', flow: 'standard', enableLogging: true, }, enableBearerInterceptor: true, loadUserProfileAtStartUp: true, }; } function configureAutomaticRedirectToLoginScreen(keyCloakService: KeycloakService, keycloakStatusService: KeycloakStatusService) { const keycloakInstance = keyCloakService.getKeycloakInstance(); keycloakInstance.onAuthRefreshError = () => { console.log('onAuthRefreshError'); keycloakStatusService.createLoginUrlAndExecute(); }; keycloakInstance.onAuthError = err => { console.log('onAuthError', err); }; } export async function keycloakInitializer(tenant: string) { const logger = inject(NGXLogger); const router = inject(Router); const keycloakService = inject(KeycloakService); const keycloakStatusService = inject(KeycloakStatusService); const uiRoot = inject(UI_ROOT); const config = getConfig(); const keycloakOptions = getKeycloakOptions(uiRoot, config, tenant); try { await keycloakService.init(keycloakOptions); } catch (error) { logger.error('[KEYCLOAK] Unable to initialize Keycloak', error); await router.navigate(['/']); return; } configureAutomaticRedirectToLoginScreen(keycloakService, keycloakStatusService); }