Ajout auth - oublie
This commit is contained in:
@@ -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;
|
||||
};
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user