57 lines
2.1 KiB
TypeScript
57 lines
2.1 KiB
TypeScript
import { BASE_HREF, IqserAppConfig } 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';
|
|
|
|
function getKeycloakOptions(baseUrl: string, config: IqserAppConfig, tenant: string): KeycloakOptions {
|
|
return {
|
|
config: {
|
|
url: config.OAUTH_URL,
|
|
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,
|
|
};
|
|
}
|
|
|
|
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 baseHref = inject(BASE_HREF);
|
|
const config = getConfig();
|
|
|
|
const keycloakOptions = getKeycloakOptions(baseHref, config, tenant);
|
|
try {
|
|
await keycloakService.init(keycloakOptions);
|
|
} catch (error) {
|
|
logger.error('[KEYCLOAK] Unable to initialize Keycloak', error);
|
|
await router.navigate(['/']);
|
|
return;
|
|
}
|
|
configureAutomaticRedirectToLoginScreen(keycloakService, keycloakStatusService);
|
|
}
|