64 lines
2.5 KiB
TypeScript
64 lines
2.5 KiB
TypeScript
import { ChangeDetectionStrategy, Component, inject, Input } from '@angular/core';
|
|
import { FormBuilder, Validators } from '@angular/forms';
|
|
import { TenantsService } from '../services';
|
|
import { LoadingService } from '../../loading';
|
|
import { Title } from '@angular/platform-browser';
|
|
import { getConfig } from '../../services';
|
|
import { KeycloakService } from 'keycloak-angular';
|
|
import { BASE_HREF } from '../../utils';
|
|
import { getKeycloakOptions } from '../keycloak-initializer';
|
|
import { KeycloakStatusService } from '../services/keycloak-status.service';
|
|
|
|
@Component({
|
|
templateUrl: './tenant-select.component.html',
|
|
styleUrls: ['./tenant-select.component.scss'],
|
|
changeDetection: ChangeDetectionStrategy.OnPush,
|
|
})
|
|
export class TenantSelectComponent {
|
|
protected readonly baseHref = inject(BASE_HREF);
|
|
protected readonly storedTenants = inject(TenantsService)
|
|
.getStoredTenants()
|
|
.sort((a, b) => a.tenantId.localeCompare(b.tenantId));
|
|
protected readonly titleService = inject(Title);
|
|
protected readonly config = getConfig();
|
|
protected readonly loadingService = inject(LoadingService);
|
|
protected readonly keycloakService = inject(KeycloakService);
|
|
protected readonly keycloakStatusService = inject(KeycloakStatusService);
|
|
protected readonly form = inject(FormBuilder).group({
|
|
// eslint-disable-next-line @typescript-eslint/unbound-method
|
|
tenantId: ['', Validators.required],
|
|
});
|
|
@Input() isLoggedOut = false;
|
|
|
|
updateTenantSelection() {
|
|
const tenantId = this.form.controls.tenantId.value;
|
|
if (!tenantId) {
|
|
throw new Error('No tenant selected!');
|
|
}
|
|
|
|
this.loadingService.start();
|
|
|
|
const email = this.#getEmail(tenantId);
|
|
return this.select(tenantId, email);
|
|
}
|
|
|
|
async select(tenantId: string, email?: string) {
|
|
try {
|
|
await this.keycloakService.init(getKeycloakOptions(this.baseHref, this.config, tenantId));
|
|
} catch (e) {
|
|
return this.keycloakService.logout();
|
|
}
|
|
const url = this.keycloakService.getKeycloakInstance().createLoginUrl({
|
|
redirectUri: this.keycloakStatusService.createLoginUrl(tenantId),
|
|
idpHint: this.config.OAUTH_IDP_HINT,
|
|
loginHint: email ?? undefined,
|
|
});
|
|
return this.keycloakService.logout(url);
|
|
}
|
|
|
|
#getEmail(tenantId: string) {
|
|
const existingStored = this.storedTenants.filter(s => s.tenantId === tenantId);
|
|
return existingStored.length === 1 ? existingStored[0].email : undefined;
|
|
}
|
|
}
|