forked from Lissy93/dashy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
KeycloakAuth.js
95 lines (80 loc) · 2.47 KB
/
KeycloakAuth.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
import Keycloak from 'keycloak-js';
import ConfigAccumulator from '@/utils/ConfigAccumalator';
import { localStorageKeys } from '@/utils/defaults';
import ErrorHandler from '@/utils/ErrorHandler';
const getAppConfig = () => {
const Accumulator = new ConfigAccumulator();
const config = Accumulator.config();
return config.appConfig || {};
};
class KeycloakAuth {
constructor() {
const { auth } = getAppConfig();
const {
serverUrl, realm, clientId, legacySupport,
} = auth.keycloak;
const url = legacySupport ? `${serverUrl}/auth` : serverUrl;
const initOptions = {
url, realm, clientId, onLoad: 'login-required',
};
this.keycloakClient = Keycloak(initOptions);
}
login() {
return new Promise((resolve, reject) => {
this.keycloakClient.init({ onLoad: 'login-required' })
.then((auth) => {
if (auth) {
this.storeKeycloakInfo();
return resolve();
} else {
return reject(new Error('Not authenticated'));
}
})
.catch((reason) => reject(reason));
});
}
logout() {
localStorage.removeItem(localStorageKeys.USERNAME);
localStorage.removeItem(localStorageKeys.KEYCLOAK_INFO);
this.keycloakClient.logout();
}
storeKeycloakInfo() {
if (this.keycloakClient.tokenParsed && typeof this.keycloakClient.tokenParsed === 'object') {
const {
groups,
realm_access: realmAccess,
resource_access: resourceAccess,
azp: clientId,
preferred_username: preferredUsername,
} = this.keycloakClient.tokenParsed;
const realmRoles = realmAccess.roles || [];
let clientRoles = [];
if (Object.hasOwn(resourceAccess, clientId)) {
clientRoles = resourceAccess[clientId].roles || [];
}
const roles = [...realmRoles, ...clientRoles];
const info = {
groups,
roles,
};
localStorage.setItem(localStorageKeys.KEYCLOAK_INFO, JSON.stringify(info));
localStorage.setItem(localStorageKeys.USERNAME, preferredUsername);
}
}
}
export const isKeycloakEnabled = () => {
const { auth } = getAppConfig();
if (!auth) return false;
return auth.enableKeycloak || false;
};
let keycloak;
export const initKeycloakAuth = () => {
keycloak = new KeycloakAuth();
return keycloak.login();
};
export const getKeycloakAuth = () => {
if (!keycloak) {
ErrorHandler("Keycloak not initialized, can't get instance of class");
}
return keycloak;
};