Select Git revision
-
Christopher Krawietz authoredChristopher Krawietz authored
authentication.service.ts 2.83 KiB
import { Environment, ENVIRONMENT_CONFIG } from '@alfa-client/environment-shared';
import { Inject, Injectable } from '@angular/core';
import { AuthConfig, OAuthService } from 'angular-oauth2-oidc';
import { JwksValidationHandler } from 'angular-oauth2-oidc-jwks';
import { UserProfileResource } from 'libs/user-profile-shared/src/lib/user-profile.model';
import { getUserNameInitials } from 'libs/user-profile-shared/src/lib/user-profile.util';
import { filter, from, map, Observable, startWith, switchMap } from 'rxjs';
import KcAdminClient from '@keycloak/keycloak-admin-client';
@Injectable({ providedIn: 'root' })
export class AuthenticationService {
currentUserResource: UserProfileResource;
constructor(
private kcAdminClient: KcAdminClient,
private oAuthService: OAuthService,
@Inject(ENVIRONMENT_CONFIG) private envConfig: Environment,
) {}
getRefreshToken(): Observable<string> {
return this.oAuthService.events.pipe(
filter((event) => event.type === 'token_received'),
startWith(true),
map(() => this.oAuthService.getRefreshToken()),
);
}
setupKeycloakAdminClientRefresh(): void {
this.authorize().subscribe(() => {});
}
authorize(): Observable<void> {
return this.getRefreshToken().pipe(switchMap((token) => this.useRefreshToken(token)));
}
useRefreshToken(refreshToken: string): Observable<void> {
return from(
this.kcAdminClient.auth({
refreshToken,
grantType: 'refresh_token',
clientId: this.envConfig.clientId,
}),
);
}
public async login(): Promise<void> {
this.oAuthService.configure(this.buildConfiguration());
this.oAuthService.setupAutomaticSilentRefresh();
this.oAuthService.tokenValidationHandler = new JwksValidationHandler();
await this.oAuthService.loadDiscoveryDocumentAndLogin();
this.setCurrentUser();
this.setupKeycloakAdminClientRefresh();
}
buildConfiguration(): AuthConfig {
return {
issuer: this.envConfig.authServer + '/realms/' + this.envConfig.realm,
tokenEndpoint:
this.envConfig.authServer +
'/realms/' +
this.envConfig.realm +
'/protocol/openid-connect/token',
redirectUri: window.location.origin + '/',
clientId: this.envConfig.clientId,
scope: 'openid profile',
requireHttps: false,
responseType: 'code',
showDebugInformation: false,
};
}
setCurrentUser(): void {
const claims: Record<string, any> = this.oAuthService.getIdentityClaims();
const userResource: UserProfileResource = <any>{
firstName: claims['given_name'],
lastName: claims['family_name'],
};
this.currentUserResource = userResource;
}
public getCurrentUserInitials(): string {
return getUserNameInitials(this.currentUserResource);
}
public logout(): void {
this.oAuthService.revokeTokenAndLogout();
}
}