Ajout auth - oublie

This commit is contained in:
2026-05-24 06:50:30 +02:00
parent 2098da0630
commit eeb074f763
3 changed files with 63 additions and 0 deletions
+12
View File
@@ -0,0 +1,12 @@
import { inject } from '@angular/core';
import { CanActivateFn } from '@angular/router';
import { KeycloakService } from './keycloak.service';
export const authGuard: CanActivateFn = () => {
const keycloak = inject(KeycloakService);
if (keycloak.isLoggedIn()) {
return true;
}
keycloak.login();
return false;
};
+43
View File
@@ -0,0 +1,43 @@
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;
}
}
+8
View File
@@ -0,0 +1,8 @@
<!doctype html>
<html>
<body>
<script>
parent.postMessage(location.href, location.origin);
</script>
</body>
</html>