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(undefined); async init(): Promise { try { const authenticated = await this.keycloak.init({ 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 { return this.keycloak.login(); } logout(): Promise { return this.keycloak.logout({ redirectUri: window.location.origin }); } isLoggedIn(): boolean { return this.keycloak.authenticated ?? false; } async getToken(): Promise { try { await this.keycloak.updateToken(30); return this.keycloak.token; } catch { return undefined; } } }