44 lines
1.2 KiB
TypeScript
44 lines
1.2 KiB
TypeScript
import { Injectable, signal } from '@angular/core';
|
|
import Keycloak from 'keycloak-js';
|
|
|
|
@Injectable({ providedIn: 'root' })
|
|
export class KeycloakService {
|
|
private readonly keycloak = new Keycloak({
|
|
url: 'https://auth.goutailler-olivier.com',
|
|
realm: 'bonsai',
|
|
clientId: 'bonsai-webapp',
|
|
});
|
|
|
|
readonly isAuthenticated = signal(false);
|
|
readonly username = signal<string | undefined>(undefined);
|
|
|
|
async init(): Promise<void> {
|
|
try {
|
|
const authenticated = await this.keycloak.init({
|
|
onLoad: 'check-sso',
|
|
silentCheckSsoRedirectUri: `${window.location.origin}/assets/silent-check-sso.html`,
|
|
pkceMethod: 'S256',
|
|
});
|
|
this.isAuthenticated.set(authenticated);
|
|
if (authenticated) {
|
|
this.username.set(this.keycloak.tokenParsed?.['preferred_username']);
|
|
this.keycloak.onTokenExpired = () => this.keycloak.updateToken(30).catch(() => this.logout());
|
|
}
|
|
} catch {
|
|
console.error('Échec de l\'initialisation Keycloak');
|
|
}
|
|
}
|
|
|
|
login(): Promise<void> {
|
|
return this.keycloak.login();
|
|
}
|
|
|
|
logout(): Promise<void> {
|
|
return this.keycloak.logout({ redirectUri: window.location.origin });
|
|
}
|
|
|
|
isLoggedIn(): boolean {
|
|
return this.keycloak.authenticated ?? false;
|
|
}
|
|
}
|