-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathkeycloak.service.ts
72 lines (61 loc) · 2.23 KB
/
keycloak.service.ts
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
import { environment } from './../../environments/environment';
import { Injectable } from '@angular/core';
import * as Keycloak from 'keycloak-js';
@Injectable()
export class KeycloakService {
private static auth: any = {};
static init(): Promise<any> {
KeycloakService.auth.loggedIn = false;
KeycloakService.auth.withoutAuth = false;
// need to use plain XMLHttpRequest here, as Http instance is instantiated after this call
const promise = new Promise((resolve, reject) => {
const req = new XMLHttpRequest();
req.open('GET', environment.backendUrl + '/rest/internal/keycloak-config', true);
req.onload = (e) => {
const keycloakConfig = JSON.parse(req.responseText);
const keycloakAuth: any = Keycloak(keycloakConfig);
keycloakAuth.init({ onLoad: 'login-required' })
.success(() => {
KeycloakService.auth.loggedIn = true;
KeycloakService.auth.authz = keycloakAuth;
resolve(null);
})
.error((response) => {
console.error('error on keycloak init');
reject(null);
});
};
req.onerror = (e) => {
console.error(`Error on fetching keycloak configuration: status = ${req.status} ${req.statusText}`);
document.getElementById('rootError').innerHTML = 'Failed to init user authentication. This is probably ' +
'caused by a unsuccessfull communication with the UI backend. Please contact a system administrator.';
reject('Unable to query keycloak config.');
};
req.send(null);
});
return promise;
}
isLoggedIn() {
return KeycloakService.auth.loggedIn;
}
logout() {
console.log('*** LOGOUT');
KeycloakService.auth.loggedIn = false;
const authz = KeycloakService.auth.authz;
KeycloakService.auth.authz = null;
authz.logout();
}
getToken(): Promise<string> {
return new Promise<string>((resolve, reject) => {
if (KeycloakService.auth.authz.token) {
KeycloakService.auth.authz.updateToken(5)
.success(() => {
resolve(<string>KeycloakService.auth.authz.token);
})
.error(() => {
reject('Failed to refresh token');
});
}
});
}
}