@ebrains/react 0.9.1-beta → 0.9.2-beta

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (179) hide show
  1. package/.babelrc +12 -0
  2. package/package.json +2 -6
  3. package/project.json +10 -0
  4. package/rollup.config.js +43 -0
  5. package/src/components.ts +49 -0
  6. package/src/generated/components.ts +47 -0
  7. package/src/generated/react-component-lib/attachProps.ts +125 -0
  8. package/src/generated/react-component-lib/case.ts +7 -0
  9. package/src/generated/react-component-lib/createComponent.tsx +106 -0
  10. package/src/generated/react-component-lib/createOverlayComponent.tsx +142 -0
  11. package/src/generated/react-component-lib/dev.ts +14 -0
  12. package/src/generated/react-component-lib/index.tsx +50 -0
  13. package/src/generated/react-component-lib/interfaces.ts +34 -0
  14. package/src/generated/react-component-lib/utils/attachProps.ts +125 -0
  15. package/src/generated/react-component-lib/utils/case.ts +7 -0
  16. package/src/generated/react-component-lib/utils/dev.ts +14 -0
  17. package/src/generated/react-component-lib/utils/index.tsx +50 -0
  18. package/src/react-component-lib/attachProps.ts +125 -0
  19. package/src/react-component-lib/case.ts +7 -0
  20. package/src/react-component-lib/createComponent.tsx +106 -0
  21. package/src/react-component-lib/createOverlayComponent.tsx +142 -0
  22. package/src/react-component-lib/dev.ts +14 -0
  23. package/src/react-component-lib/index.tsx +50 -0
  24. package/src/react-component-lib/interfaces.ts +34 -0
  25. package/src/react-component-lib/utils/attachProps.ts +125 -0
  26. package/src/react-component-lib/utils/case.ts +7 -0
  27. package/src/react-component-lib/utils/index.tsx +50 -0
  28. package/tsconfig.json +17 -0
  29. package/tsconfig.lib.json +23 -0
  30. package/analytics-44b1416b.esm.js +0 -55
  31. package/arrow-diagonal-black-8f0494c3.esm.js +0 -3
  32. package/arrow-right-9322ba8a.esm.js +0 -5
  33. package/bluesky-cc5edd2d.esm.js +0 -14
  34. package/bookmark-c200037c.esm.js +0 -16
  35. package/chevron-down-6144c823.esm.js +0 -12
  36. package/chevron-left-ca6c66e1.esm.js +0 -11
  37. package/chevron-right-b88ed2d4.esm.js +0 -5
  38. package/chevron-up-c66bd477.esm.js +0 -12
  39. package/close-87fc0d63.esm.js +0 -5
  40. package/color-2554aad6.esm.js +0 -122
  41. package/color-primary-palette_6.entry.esm.js +0 -778
  42. package/components-section.entry.esm.js +0 -165
  43. package/copy-03b72cb6.esm.js +0 -5
  44. package/correct-use-of-colors.entry.esm.js +0 -243
  45. package/docs-palettes.entry.esm.js +0 -29
  46. package/docs-tokens.entry.esm.js +0 -45
  47. package/eds-accordion.entry.esm.js +0 -132
  48. package/eds-alert.entry.esm.js +0 -112
  49. package/eds-app-root.entry.esm.js +0 -53
  50. package/eds-avatar_26.entry.esm.js +0 -306
  51. package/eds-card-desc_2.entry.esm.js +0 -86
  52. package/eds-card-generic.entry.esm.js +0 -114
  53. package/eds-card-project.entry.esm.js +0 -93
  54. package/eds-card-section.entry.esm.js +0 -56
  55. package/eds-card-tags.entry.esm.js +0 -27
  56. package/eds-card-tool.entry.esm.js +0 -105
  57. package/eds-card-wrapper.entry.esm.js +0 -39
  58. package/eds-code-block.entry.esm.js +0 -2290
  59. package/eds-cookies-preference.entry.esm.js +0 -47
  60. package/eds-feedback.entry.esm.js +0 -82
  61. package/eds-frame.entry.esm.js +0 -112
  62. package/eds-icon-arrow-diagonal.entry.esm.js +0 -21
  63. package/eds-icon-arrow-right.entry.esm.js +0 -21
  64. package/eds-icon-bluesky.entry.esm.js +0 -21
  65. package/eds-icon-bookmark.entry.esm.js +0 -21
  66. package/eds-icon-chevron-down.entry.esm.js +0 -21
  67. package/eds-icon-chevron-left.entry.esm.js +0 -21
  68. package/eds-icon-chevron-right.entry.esm.js +0 -21
  69. package/eds-icon-chevron-up.entry.esm.js +0 -21
  70. package/eds-icon-close.entry.esm.js +0 -21
  71. package/eds-icon-copy.entry.esm.js +0 -21
  72. package/eds-icon-eu.entry.esm.js +0 -21
  73. package/eds-icon-external.entry.esm.js +0 -21
  74. package/eds-icon-facebook.entry.esm.js +0 -21
  75. package/eds-icon-gitlab.entry.esm.js +0 -21
  76. package/eds-icon-linkedin.entry.esm.js +0 -21
  77. package/eds-icon-loader.entry.esm.js +0 -21
  78. package/eds-icon-mastodon.entry.esm.js +0 -21
  79. package/eds-icon-menu.entry.esm.js +0 -21
  80. package/eds-icon-minus.entry.esm.js +0 -21
  81. package/eds-icon-more.entry.esm.js +0 -21
  82. package/eds-icon-paper.entry.esm.js +0 -21
  83. package/eds-icon-plus.entry.esm.js +0 -21
  84. package/eds-icon-portal.entry.esm.js +0 -21
  85. package/eds-icon-private.entry.esm.js +0 -21
  86. package/eds-icon-public.entry.esm.js +0 -21
  87. package/eds-icon-search.entry.esm.js +0 -21
  88. package/eds-icon-star.entry.esm.js +0 -21
  89. package/eds-icon-success.entry.esm.js +0 -21
  90. package/eds-icon-thumbs-down.entry.esm.js +0 -21
  91. package/eds-icon-thumbs-up.entry.esm.js +0 -21
  92. package/eds-icon-tutorial.entry.esm.js +0 -21
  93. package/eds-icon-twitter.entry.esm.js +0 -21
  94. package/eds-icon-unknown.entry.esm.js +0 -21
  95. package/eds-icon-updown.entry.esm.js +0 -21
  96. package/eds-icon-user.entry.esm.js +0 -21
  97. package/eds-icon-youtube.entry.esm.js +0 -21
  98. package/eds-login_2.entry.esm.js +0 -1828
  99. package/eds-matomo-notice.entry.esm.js +0 -162
  100. package/eds-modal.entry.esm.js +0 -142
  101. package/eds-pagination_2.entry.esm.js +0 -493
  102. package/eds-progress-bar.entry.esm.js +0 -41
  103. package/eds-rating.entry.esm.js +0 -79
  104. package/eds-section-core_2.entry.esm.js +0 -69
  105. package/eds-spinner.entry.esm.js +0 -67
  106. package/eds-switch.entry.esm.js +0 -58
  107. package/eds-tabs.entry.esm.js +0 -143
  108. package/eds-timeline.entry.esm.js +0 -117
  109. package/eds-toast-manager.entry.esm.js +0 -62
  110. package/eds-toast.entry.esm.js +0 -92
  111. package/eds-tooltip.entry.esm.js +0 -125
  112. package/eds-trl.entry.esm.js +0 -68
  113. package/eu-9ddde93a.esm.js +0 -30
  114. package/facebook-9cb5c17f.esm.js +0 -14
  115. package/incorrect-use-of-colors.entry.esm.js +0 -71
  116. package/index-39c58238.esm.js +0 -58
  117. package/index.esm.d.ts +0 -1
  118. package/index.esm.js +0 -4
  119. package/index.esm2.js +0 -4836
  120. package/linkedin-e8650abb.esm.js +0 -28
  121. package/loader-c9628637.esm.js +0 -30
  122. package/logo-color-7f1fd803.esm.js +0 -115
  123. package/logo-color-margins-ff8ce71b.esm.js +0 -118
  124. package/logo-space.entry.esm.js +0 -48
  125. package/logo-variations-horizontal_2.entry.esm.js +0 -123
  126. package/logo-variations-tabs.entry.esm.js +0 -29
  127. package/logo-white-no-bg-f382f86f.esm.js +0 -1021
  128. package/logo-wrong-usage.entry.esm.js +0 -101
  129. package/mastodon-3703ec61.esm.js +0 -14
  130. package/menu-340ea948.esm.js +0 -11
  131. package/minus-b30a7c71.esm.js +0 -11
  132. package/mono-53f70232.esm.js +0 -11
  133. package/more-4449d549.esm.js +0 -13
  134. package/paper-8e74ea31.esm.js +0 -15
  135. package/plus-89c07be2.esm.js +0 -12
  136. package/portal-d6c8ce56.esm.js +0 -18
  137. package/private-1c25ff8e.esm.js +0 -25
  138. package/public-d4d8c585.esm.js +0 -16
  139. package/search-fbcd79c2.esm.js +0 -12
  140. package/sharedUtils-a550989c.esm.js +0 -17
  141. package/src/components.d.ts +0 -40
  142. package/src/generated/components.d.ts +0 -38
  143. package/src/generated/react-component-lib/attachProps.d.ts +0 -16
  144. package/src/generated/react-component-lib/case.d.ts +0 -2
  145. package/src/generated/react-component-lib/createComponent.d.ts +0 -10
  146. package/src/generated/react-component-lib/createOverlayComponent.d.ts +0 -21
  147. package/src/generated/react-component-lib/dev.d.ts +0 -2
  148. package/src/generated/react-component-lib/interfaces.d.ts +0 -29
  149. package/src/generated/react-component-lib/utils/attachProps.d.ts +0 -16
  150. package/src/generated/react-component-lib/utils/case.d.ts +0 -2
  151. package/src/generated/react-component-lib/utils/dev.d.ts +0 -2
  152. package/src/generated/react-component-lib/utils/index.d.ts +0 -10
  153. package/src/react-component-lib/attachProps.d.ts +0 -16
  154. package/src/react-component-lib/case.d.ts +0 -2
  155. package/src/react-component-lib/createComponent.d.ts +0 -10
  156. package/src/react-component-lib/createOverlayComponent.d.ts +0 -21
  157. package/src/react-component-lib/dev.d.ts +0 -2
  158. package/src/react-component-lib/interfaces.d.ts +0 -29
  159. package/src/react-component-lib/utils/attachProps.d.ts +0 -16
  160. package/src/react-component-lib/utils/case.d.ts +0 -2
  161. package/src/react-component-lib/utils/index.d.ts +0 -10
  162. package/star-0da9b5e9.esm.js +0 -5
  163. package/success-443809da.esm.js +0 -18
  164. package/svg-repository.entry.esm.js +0 -337
  165. package/thumbs-down-a18fd049.esm.js +0 -5
  166. package/thumbs-up-c19a71bc.esm.js +0 -6
  167. package/toastManager-d9eee791.esm.js +0 -34
  168. package/token-list_3.entry.esm.js +0 -385
  169. package/token-ratios.entry.esm.js +0 -49
  170. package/token-typography.entry.esm.js +0 -267
  171. package/tutotial-150ee1fd.esm.js +0 -27
  172. package/twitter-ac21b505.esm.js +0 -14
  173. package/unknown-ed01a24c.esm.js +0 -22
  174. package/up-and-down-d747abee.esm.js +0 -12
  175. package/user-71ebdc15.esm.js +0 -16
  176. package/youtube-efbfbdc4.esm.js +0 -14
  177. /package/src/generated/react-component-lib/{index.d.ts → index.ts} +0 -0
  178. /package/src/{index.d.ts → index.ts} +0 -0
  179. /package/src/react-component-lib/{index.d.ts → index.ts} +0 -0
@@ -1,1828 +0,0 @@
1
- import { r as registerInstance, c as createEvent, h, H as Host } from './index.esm2.js';
2
- import { t as toast } from './toastManager-d9eee791.esm.js';
3
- import 'react';
4
- import 'react/jsx-runtime';
5
- import 'react-dom';
6
-
7
- /*
8
- * Copyright 2016 Red Hat, Inc. and/or its affiliates
9
- * and other contributors as indicated by the @author tags.
10
- *
11
- * Licensed under the Apache License, Version 2.0 (the "License");
12
- * you may not use this file except in compliance with the License.
13
- * You may obtain a copy of the License at
14
- *
15
- * http://www.apache.org/licenses/LICENSE-2.0
16
- *
17
- * Unless required by applicable law or agreed to in writing, software
18
- * distributed under the License is distributed on an "AS IS" BASIS,
19
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20
- * See the License for the specific language governing permissions and
21
- * limitations under the License.
22
- */
23
- function Keycloak(config) {
24
- if (!(this instanceof Keycloak)) {
25
- throw new Error("The 'Keycloak' constructor must be invoked with 'new'.");
26
- }
27
- if (typeof config !== 'string' && !isObject(config)) {
28
- throw new Error("The 'Keycloak' constructor must be provided with a configuration object, or a URL to a JSON configuration file.");
29
- }
30
- if (isObject(config)) {
31
- const requiredProperties = 'oidcProvider' in config ? ['clientId'] : ['url', 'realm', 'clientId'];
32
- for (const property of requiredProperties) {
33
- if (!config[property]) {
34
- throw new Error(`The configuration object is missing the required '${property}' property.`);
35
- }
36
- }
37
- }
38
- var kc = this;
39
- var adapter;
40
- var refreshQueue = [];
41
- var callbackStorage;
42
- var loginIframe = {
43
- enable: true,
44
- callbackList: [],
45
- interval: 5
46
- };
47
- kc.didInitialize = false;
48
- var useNonce = true;
49
- var logInfo = createLogger(console.info);
50
- var logWarn = createLogger(console.warn);
51
- if (!globalThis.isSecureContext) {
52
- logWarn("[KEYCLOAK] Keycloak JS must be used in a 'secure context' to function properly as it relies on browser APIs that are otherwise not available.\n" + "Continuing to run your application insecurely will lead to unexpected behavior and breakage.\n\n" + "For more information see: https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts");
53
- }
54
- kc.init = function (initOptions = {}) {
55
- if (kc.didInitialize) {
56
- throw new Error("A 'Keycloak' instance can only be initialized once.");
57
- }
58
- kc.didInitialize = true;
59
- kc.authenticated = false;
60
- callbackStorage = createCallbackStorage();
61
- var adapters = ['default', 'cordova', 'cordova-native'];
62
- if (adapters.indexOf(initOptions.adapter) > -1) {
63
- adapter = loadAdapter(initOptions.adapter);
64
- } else if (typeof initOptions.adapter === "object") {
65
- adapter = initOptions.adapter;
66
- } else {
67
- if (window.Cordova || window.cordova) {
68
- adapter = loadAdapter('cordova');
69
- } else {
70
- adapter = loadAdapter();
71
- }
72
- }
73
- if (typeof initOptions.useNonce !== 'undefined') {
74
- useNonce = initOptions.useNonce;
75
- }
76
- if (typeof initOptions.checkLoginIframe !== 'undefined') {
77
- loginIframe.enable = initOptions.checkLoginIframe;
78
- }
79
- if (initOptions.checkLoginIframeInterval) {
80
- loginIframe.interval = initOptions.checkLoginIframeInterval;
81
- }
82
- if (initOptions.onLoad === 'login-required') {
83
- kc.loginRequired = true;
84
- }
85
- if (initOptions.responseMode) {
86
- if (initOptions.responseMode === 'query' || initOptions.responseMode === 'fragment') {
87
- kc.responseMode = initOptions.responseMode;
88
- } else {
89
- throw 'Invalid value for responseMode';
90
- }
91
- }
92
- if (initOptions.flow) {
93
- switch (initOptions.flow) {
94
- case 'standard':
95
- kc.responseType = 'code';
96
- break;
97
- case 'implicit':
98
- kc.responseType = 'id_token token';
99
- break;
100
- case 'hybrid':
101
- kc.responseType = 'code id_token token';
102
- break;
103
- default:
104
- throw 'Invalid value for flow';
105
- }
106
- kc.flow = initOptions.flow;
107
- }
108
- if (initOptions.timeSkew != null) {
109
- kc.timeSkew = initOptions.timeSkew;
110
- }
111
- if (initOptions.redirectUri) {
112
- kc.redirectUri = initOptions.redirectUri;
113
- }
114
- if (initOptions.silentCheckSsoRedirectUri) {
115
- kc.silentCheckSsoRedirectUri = initOptions.silentCheckSsoRedirectUri;
116
- }
117
- if (typeof initOptions.silentCheckSsoFallback === 'boolean') {
118
- kc.silentCheckSsoFallback = initOptions.silentCheckSsoFallback;
119
- } else {
120
- kc.silentCheckSsoFallback = true;
121
- }
122
- if (typeof initOptions.pkceMethod !== "undefined") {
123
- if (initOptions.pkceMethod !== "S256" && initOptions.pkceMethod !== false) {
124
- throw new TypeError(`Invalid value for pkceMethod', expected 'S256' or false but got ${initOptions.pkceMethod}.`);
125
- }
126
- kc.pkceMethod = initOptions.pkceMethod;
127
- } else {
128
- kc.pkceMethod = "S256";
129
- }
130
- if (typeof initOptions.enableLogging === 'boolean') {
131
- kc.enableLogging = initOptions.enableLogging;
132
- } else {
133
- kc.enableLogging = false;
134
- }
135
- if (initOptions.logoutMethod === 'POST') {
136
- kc.logoutMethod = 'POST';
137
- } else {
138
- kc.logoutMethod = 'GET';
139
- }
140
- if (typeof initOptions.scope === 'string') {
141
- kc.scope = initOptions.scope;
142
- }
143
- if (typeof initOptions.acrValues === 'string') {
144
- kc.acrValues = initOptions.acrValues;
145
- }
146
- if (typeof initOptions.messageReceiveTimeout === 'number' && initOptions.messageReceiveTimeout > 0) {
147
- kc.messageReceiveTimeout = initOptions.messageReceiveTimeout;
148
- } else {
149
- kc.messageReceiveTimeout = 10000;
150
- }
151
- if (!kc.responseMode) {
152
- kc.responseMode = 'fragment';
153
- }
154
- if (!kc.responseType) {
155
- kc.responseType = 'code';
156
- kc.flow = 'standard';
157
- }
158
- var promise = createPromise();
159
- var initPromise = createPromise();
160
- initPromise.promise.then(function () {
161
- kc.onReady && kc.onReady(kc.authenticated);
162
- promise.setSuccess(kc.authenticated);
163
- }).catch(function (error) {
164
- promise.setError(error);
165
- });
166
- var configPromise = loadConfig();
167
- function onLoad() {
168
- var doLogin = function (prompt) {
169
- if (!prompt) {
170
- options.prompt = 'none';
171
- }
172
- if (initOptions.locale) {
173
- options.locale = initOptions.locale;
174
- }
175
- kc.login(options).then(function () {
176
- initPromise.setSuccess();
177
- }).catch(function (error) {
178
- initPromise.setError(error);
179
- });
180
- };
181
- var checkSsoSilently = async function () {
182
- var ifrm = document.createElement("iframe");
183
- var src = await kc.createLoginUrl({
184
- prompt: 'none',
185
- redirectUri: kc.silentCheckSsoRedirectUri
186
- });
187
- ifrm.setAttribute("src", src);
188
- ifrm.setAttribute("sandbox", "allow-storage-access-by-user-activation allow-scripts allow-same-origin");
189
- ifrm.setAttribute("title", "keycloak-silent-check-sso");
190
- ifrm.style.display = "none";
191
- document.body.appendChild(ifrm);
192
- var messageCallback = function (event) {
193
- if (event.origin !== window.location.origin || ifrm.contentWindow !== event.source) {
194
- return;
195
- }
196
- var oauth = parseCallback(event.data);
197
- processCallback(oauth, initPromise);
198
- document.body.removeChild(ifrm);
199
- window.removeEventListener("message", messageCallback);
200
- };
201
- window.addEventListener("message", messageCallback);
202
- };
203
- var options = {};
204
- switch (initOptions.onLoad) {
205
- case 'check-sso':
206
- if (loginIframe.enable) {
207
- setupCheckLoginIframe().then(function () {
208
- checkLoginIframe().then(function (unchanged) {
209
- if (!unchanged) {
210
- kc.silentCheckSsoRedirectUri ? checkSsoSilently() : doLogin(false);
211
- } else {
212
- initPromise.setSuccess();
213
- }
214
- }).catch(function (error) {
215
- initPromise.setError(error);
216
- });
217
- });
218
- } else {
219
- kc.silentCheckSsoRedirectUri ? checkSsoSilently() : doLogin(false);
220
- }
221
- break;
222
- case 'login-required':
223
- doLogin(true);
224
- break;
225
- default:
226
- throw 'Invalid value for onLoad';
227
- }
228
- }
229
- function processInit() {
230
- var callback = parseCallback(window.location.href);
231
- if (callback) {
232
- window.history.replaceState(window.history.state, null, callback.newUrl);
233
- }
234
- if (callback && callback.valid) {
235
- return setupCheckLoginIframe().then(function () {
236
- processCallback(callback, initPromise);
237
- }).catch(function (error) {
238
- initPromise.setError(error);
239
- });
240
- }
241
- if (initOptions.token && initOptions.refreshToken) {
242
- setToken(initOptions.token, initOptions.refreshToken, initOptions.idToken);
243
- if (loginIframe.enable) {
244
- setupCheckLoginIframe().then(function () {
245
- checkLoginIframe().then(function (unchanged) {
246
- if (unchanged) {
247
- kc.onAuthSuccess && kc.onAuthSuccess();
248
- initPromise.setSuccess();
249
- scheduleCheckIframe();
250
- } else {
251
- initPromise.setSuccess();
252
- }
253
- }).catch(function (error) {
254
- initPromise.setError(error);
255
- });
256
- });
257
- } else {
258
- kc.updateToken(-1).then(function () {
259
- kc.onAuthSuccess && kc.onAuthSuccess();
260
- initPromise.setSuccess();
261
- }).catch(function (error) {
262
- kc.onAuthError && kc.onAuthError();
263
- if (initOptions.onLoad) {
264
- onLoad();
265
- } else {
266
- initPromise.setError(error);
267
- }
268
- });
269
- }
270
- } else if (initOptions.onLoad) {
271
- onLoad();
272
- } else {
273
- initPromise.setSuccess();
274
- }
275
- }
276
- configPromise.then(function () {
277
- check3pCookiesSupported().then(processInit).catch(function (error) {
278
- promise.setError(error);
279
- });
280
- });
281
- configPromise.catch(function (error) {
282
- promise.setError(error);
283
- });
284
- return promise.promise;
285
- };
286
- kc.login = function (options) {
287
- return adapter.login(options);
288
- };
289
- function generateRandomData(len) {
290
- if (typeof crypto === "undefined" || typeof crypto.getRandomValues === "undefined") {
291
- throw new Error("Web Crypto API is not available.");
292
- }
293
- return crypto.getRandomValues(new Uint8Array(len));
294
- }
295
- function generateCodeVerifier(len) {
296
- return generateRandomString(len, 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789');
297
- }
298
- function generateRandomString(len, alphabet) {
299
- var randomData = generateRandomData(len);
300
- var chars = new Array(len);
301
- for (var i = 0; i < len; i++) {
302
- chars[i] = alphabet.charCodeAt(randomData[i] % alphabet.length);
303
- }
304
- return String.fromCharCode.apply(null, chars);
305
- }
306
- async function generatePkceChallenge(pkceMethod, codeVerifier) {
307
- if (pkceMethod !== "S256") {
308
- throw new TypeError(`Invalid value for 'pkceMethod', expected 'S256' but got '${pkceMethod}'.`);
309
- }
310
-
311
- // hash codeVerifier, then encode as url-safe base64 without padding
312
- const hashBytes = new Uint8Array(await sha256Digest(codeVerifier));
313
- const encodedHash = bytesToBase64(hashBytes).replace(/\+/g, '-').replace(/\//g, '_').replace(/\=/g, '');
314
- return encodedHash;
315
- }
316
- function buildClaimsParameter(requestedAcr) {
317
- var claims = {
318
- id_token: {
319
- acr: requestedAcr
320
- }
321
- };
322
- return JSON.stringify(claims);
323
- }
324
- kc.createLoginUrl = async function (options) {
325
- var state = createUUID();
326
- var nonce = createUUID();
327
- var redirectUri = adapter.redirectUri(options);
328
- var callbackState = {
329
- state: state,
330
- nonce: nonce,
331
- redirectUri: encodeURIComponent(redirectUri),
332
- loginOptions: options
333
- };
334
- if (options && options.prompt) {
335
- callbackState.prompt = options.prompt;
336
- }
337
- var baseUrl;
338
- if (options && options.action == 'register') {
339
- baseUrl = kc.endpoints.register();
340
- } else {
341
- baseUrl = kc.endpoints.authorize();
342
- }
343
- var scope = options && options.scope || kc.scope;
344
- if (!scope) {
345
- // if scope is not set, default to "openid"
346
- scope = "openid";
347
- } else if (scope.indexOf("openid") === -1) {
348
- // if openid scope is missing, prefix the given scopes with it
349
- scope = "openid " + scope;
350
- }
351
- var url = baseUrl + '?client_id=' + encodeURIComponent(kc.clientId) + '&redirect_uri=' + encodeURIComponent(redirectUri) + '&state=' + encodeURIComponent(state) + '&response_mode=' + encodeURIComponent(kc.responseMode) + '&response_type=' + encodeURIComponent(kc.responseType) + '&scope=' + encodeURIComponent(scope);
352
- if (useNonce) {
353
- url = url + '&nonce=' + encodeURIComponent(nonce);
354
- }
355
- if (options && options.prompt) {
356
- url += '&prompt=' + encodeURIComponent(options.prompt);
357
- }
358
- if (options && typeof options.maxAge === 'number') {
359
- url += '&max_age=' + encodeURIComponent(options.maxAge);
360
- }
361
- if (options && options.loginHint) {
362
- url += '&login_hint=' + encodeURIComponent(options.loginHint);
363
- }
364
- if (options && options.idpHint) {
365
- url += '&kc_idp_hint=' + encodeURIComponent(options.idpHint);
366
- }
367
- if (options && options.action && options.action != 'register') {
368
- url += '&kc_action=' + encodeURIComponent(options.action);
369
- }
370
- if (options && options.locale) {
371
- url += '&ui_locales=' + encodeURIComponent(options.locale);
372
- }
373
- if (options && options.acr) {
374
- var claimsParameter = buildClaimsParameter(options.acr);
375
- url += '&claims=' + encodeURIComponent(claimsParameter);
376
- }
377
- if (options && options.acrValues || kc.acrValues) {
378
- url += '&acr_values=' + encodeURIComponent(options.acrValues || kc.acrValues);
379
- }
380
- if (kc.pkceMethod) {
381
- try {
382
- const codeVerifier = generateCodeVerifier(96);
383
- const pkceChallenge = await generatePkceChallenge(kc.pkceMethod, codeVerifier);
384
- callbackState.pkceCodeVerifier = codeVerifier;
385
- url += '&code_challenge=' + pkceChallenge;
386
- url += '&code_challenge_method=' + kc.pkceMethod;
387
- } catch (error) {
388
- throw new Error("Failed to generate PKCE challenge.", {
389
- cause: error
390
- });
391
- }
392
- }
393
- callbackStorage.add(callbackState);
394
- return url;
395
- };
396
- kc.logout = function (options) {
397
- return adapter.logout(options);
398
- };
399
- kc.createLogoutUrl = function (options) {
400
- const logoutMethod = options?.logoutMethod ?? kc.logoutMethod;
401
- if (logoutMethod === 'POST') {
402
- return kc.endpoints.logout();
403
- }
404
- var url = kc.endpoints.logout() + '?client_id=' + encodeURIComponent(kc.clientId) + '&post_logout_redirect_uri=' + encodeURIComponent(adapter.redirectUri(options, false));
405
- if (kc.idToken) {
406
- url += '&id_token_hint=' + encodeURIComponent(kc.idToken);
407
- }
408
- return url;
409
- };
410
- kc.register = function (options) {
411
- return adapter.register(options);
412
- };
413
- kc.createRegisterUrl = async function (options) {
414
- if (!options) {
415
- options = {};
416
- }
417
- options.action = 'register';
418
- return await kc.createLoginUrl(options);
419
- };
420
- kc.createAccountUrl = function (options) {
421
- var realm = getRealmUrl();
422
- var url = undefined;
423
- if (typeof realm !== 'undefined') {
424
- url = realm + '/account' + '?referrer=' + encodeURIComponent(kc.clientId) + '&referrer_uri=' + encodeURIComponent(adapter.redirectUri(options));
425
- }
426
- return url;
427
- };
428
- kc.accountManagement = function () {
429
- return adapter.accountManagement();
430
- };
431
- kc.hasRealmRole = function (role) {
432
- var access = kc.realmAccess;
433
- return !!access && access.roles.indexOf(role) >= 0;
434
- };
435
- kc.hasResourceRole = function (role, resource) {
436
- if (!kc.resourceAccess) {
437
- return false;
438
- }
439
- var access = kc.resourceAccess[resource || kc.clientId];
440
- return !!access && access.roles.indexOf(role) >= 0;
441
- };
442
- kc.loadUserProfile = function () {
443
- var url = getRealmUrl() + '/account';
444
- var req = new XMLHttpRequest();
445
- req.open('GET', url, true);
446
- req.setRequestHeader('Accept', 'application/json');
447
- req.setRequestHeader('Authorization', 'bearer ' + kc.token);
448
- var promise = createPromise();
449
- req.onreadystatechange = function () {
450
- if (req.readyState == 4) {
451
- if (req.status == 200) {
452
- kc.profile = JSON.parse(req.responseText);
453
- promise.setSuccess(kc.profile);
454
- } else {
455
- promise.setError();
456
- }
457
- }
458
- };
459
- req.send();
460
- return promise.promise;
461
- };
462
- kc.loadUserInfo = function () {
463
- var url = kc.endpoints.userinfo();
464
- var req = new XMLHttpRequest();
465
- req.open('GET', url, true);
466
- req.setRequestHeader('Accept', 'application/json');
467
- req.setRequestHeader('Authorization', 'bearer ' + kc.token);
468
- var promise = createPromise();
469
- req.onreadystatechange = function () {
470
- if (req.readyState == 4) {
471
- if (req.status == 200) {
472
- kc.userInfo = JSON.parse(req.responseText);
473
- promise.setSuccess(kc.userInfo);
474
- } else {
475
- promise.setError();
476
- }
477
- }
478
- };
479
- req.send();
480
- return promise.promise;
481
- };
482
- kc.isTokenExpired = function (minValidity) {
483
- if (!kc.tokenParsed || !kc.refreshToken && kc.flow != 'implicit') {
484
- throw 'Not authenticated';
485
- }
486
- if (kc.timeSkew == null) {
487
- logInfo('[KEYCLOAK] Unable to determine if token is expired as timeskew is not set');
488
- return true;
489
- }
490
- var expiresIn = kc.tokenParsed['exp'] - Math.ceil(new Date().getTime() / 1000) + kc.timeSkew;
491
- if (minValidity) {
492
- if (isNaN(minValidity)) {
493
- throw 'Invalid minValidity';
494
- }
495
- expiresIn -= minValidity;
496
- }
497
- return expiresIn < 0;
498
- };
499
- kc.updateToken = function (minValidity) {
500
- var promise = createPromise();
501
- if (!kc.refreshToken) {
502
- promise.setError();
503
- return promise.promise;
504
- }
505
- minValidity = minValidity || 5;
506
- var exec = function () {
507
- var refreshToken = false;
508
- if (minValidity == -1) {
509
- refreshToken = true;
510
- logInfo('[KEYCLOAK] Refreshing token: forced refresh');
511
- } else if (!kc.tokenParsed || kc.isTokenExpired(minValidity)) {
512
- refreshToken = true;
513
- logInfo('[KEYCLOAK] Refreshing token: token expired');
514
- }
515
- if (!refreshToken) {
516
- promise.setSuccess(false);
517
- } else {
518
- var params = 'grant_type=refresh_token&' + 'refresh_token=' + kc.refreshToken;
519
- var url = kc.endpoints.token();
520
- refreshQueue.push(promise);
521
- if (refreshQueue.length == 1) {
522
- var req = new XMLHttpRequest();
523
- req.open('POST', url, true);
524
- req.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
525
- req.withCredentials = true;
526
- params += '&client_id=' + encodeURIComponent(kc.clientId);
527
- var timeLocal = new Date().getTime();
528
- req.onreadystatechange = function () {
529
- if (req.readyState == 4) {
530
- if (req.status == 200) {
531
- logInfo('[KEYCLOAK] Token refreshed');
532
- timeLocal = (timeLocal + new Date().getTime()) / 2;
533
- var tokenResponse = JSON.parse(req.responseText);
534
- setToken(tokenResponse['access_token'], tokenResponse['refresh_token'], tokenResponse['id_token'], timeLocal);
535
- kc.onAuthRefreshSuccess && kc.onAuthRefreshSuccess();
536
- for (var p = refreshQueue.pop(); p != null; p = refreshQueue.pop()) {
537
- p.setSuccess(true);
538
- }
539
- } else {
540
- logWarn('[KEYCLOAK] Failed to refresh token');
541
- if (req.status == 400) {
542
- kc.clearToken();
543
- }
544
- kc.onAuthRefreshError && kc.onAuthRefreshError();
545
- for (var p = refreshQueue.pop(); p != null; p = refreshQueue.pop()) {
546
- p.setError("Failed to refresh token: An unexpected HTTP error occurred while attempting to refresh the token.");
547
- }
548
- }
549
- }
550
- };
551
- req.send(params);
552
- }
553
- }
554
- };
555
- if (loginIframe.enable) {
556
- var iframePromise = checkLoginIframe();
557
- iframePromise.then(function () {
558
- exec();
559
- }).catch(function (error) {
560
- promise.setError(error);
561
- });
562
- } else {
563
- exec();
564
- }
565
- return promise.promise;
566
- };
567
- kc.clearToken = function () {
568
- if (kc.token) {
569
- setToken(null, null, null);
570
- kc.onAuthLogout && kc.onAuthLogout();
571
- if (kc.loginRequired) {
572
- kc.login();
573
- }
574
- }
575
- };
576
- function getRealmUrl() {
577
- if (typeof kc.authServerUrl !== 'undefined') {
578
- if (kc.authServerUrl.charAt(kc.authServerUrl.length - 1) == '/') {
579
- return kc.authServerUrl + 'realms/' + encodeURIComponent(kc.realm);
580
- } else {
581
- return kc.authServerUrl + '/realms/' + encodeURIComponent(kc.realm);
582
- }
583
- } else {
584
- return undefined;
585
- }
586
- }
587
- function getOrigin() {
588
- if (!window.location.origin) {
589
- return window.location.protocol + "//" + window.location.hostname + (window.location.port ? ':' + window.location.port : '');
590
- } else {
591
- return window.location.origin;
592
- }
593
- }
594
- function processCallback(oauth, promise) {
595
- var code = oauth.code;
596
- var error = oauth.error;
597
- var prompt = oauth.prompt;
598
- var timeLocal = new Date().getTime();
599
- if (oauth['kc_action_status']) {
600
- kc.onActionUpdate && kc.onActionUpdate(oauth['kc_action_status'], oauth['kc_action']);
601
- }
602
- if (error) {
603
- if (prompt != 'none') {
604
- if (oauth.error_description && oauth.error_description === "authentication_expired") {
605
- kc.login(oauth.loginOptions);
606
- } else {
607
- var errorData = {
608
- error: error,
609
- error_description: oauth.error_description
610
- };
611
- kc.onAuthError && kc.onAuthError(errorData);
612
- promise && promise.setError(errorData);
613
- }
614
- } else {
615
- promise && promise.setSuccess();
616
- }
617
- return;
618
- } else if (kc.flow != 'standard' && (oauth.access_token || oauth.id_token)) {
619
- authSuccess(oauth.access_token, null, oauth.id_token, true);
620
- }
621
- if (kc.flow != 'implicit' && code) {
622
- var params = 'code=' + code + '&grant_type=authorization_code';
623
- var url = kc.endpoints.token();
624
- var req = new XMLHttpRequest();
625
- req.open('POST', url, true);
626
- req.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
627
- params += '&client_id=' + encodeURIComponent(kc.clientId);
628
- params += '&redirect_uri=' + oauth.redirectUri;
629
- if (oauth.pkceCodeVerifier) {
630
- params += '&code_verifier=' + oauth.pkceCodeVerifier;
631
- }
632
- req.withCredentials = true;
633
- req.onreadystatechange = function () {
634
- if (req.readyState == 4) {
635
- if (req.status == 200) {
636
- var tokenResponse = JSON.parse(req.responseText);
637
- authSuccess(tokenResponse['access_token'], tokenResponse['refresh_token'], tokenResponse['id_token'], kc.flow === 'standard');
638
- scheduleCheckIframe();
639
- } else {
640
- kc.onAuthError && kc.onAuthError();
641
- promise && promise.setError();
642
- }
643
- }
644
- };
645
- req.send(params);
646
- }
647
- function authSuccess(accessToken, refreshToken, idToken, fulfillPromise) {
648
- timeLocal = (timeLocal + new Date().getTime()) / 2;
649
- setToken(accessToken, refreshToken, idToken, timeLocal);
650
- if (useNonce && kc.idTokenParsed && kc.idTokenParsed.nonce != oauth.storedNonce) {
651
- logInfo('[KEYCLOAK] Invalid nonce, clearing token');
652
- kc.clearToken();
653
- promise && promise.setError();
654
- } else {
655
- if (fulfillPromise) {
656
- kc.onAuthSuccess && kc.onAuthSuccess();
657
- promise && promise.setSuccess();
658
- }
659
- }
660
- }
661
- }
662
- function loadConfig() {
663
- var promise = createPromise();
664
- var configUrl;
665
- if (typeof config === 'string') {
666
- configUrl = config;
667
- }
668
- function setupOidcEndoints(oidcConfiguration) {
669
- if (!oidcConfiguration) {
670
- kc.endpoints = {
671
- authorize: function () {
672
- return getRealmUrl() + '/protocol/openid-connect/auth';
673
- },
674
- token: function () {
675
- return getRealmUrl() + '/protocol/openid-connect/token';
676
- },
677
- logout: function () {
678
- return getRealmUrl() + '/protocol/openid-connect/logout';
679
- },
680
- checkSessionIframe: function () {
681
- return getRealmUrl() + '/protocol/openid-connect/login-status-iframe.html';
682
- },
683
- thirdPartyCookiesIframe: function () {
684
- return getRealmUrl() + '/protocol/openid-connect/3p-cookies/step1.html';
685
- },
686
- register: function () {
687
- return getRealmUrl() + '/protocol/openid-connect/registrations';
688
- },
689
- userinfo: function () {
690
- return getRealmUrl() + '/protocol/openid-connect/userinfo';
691
- }
692
- };
693
- } else {
694
- kc.endpoints = {
695
- authorize: function () {
696
- return oidcConfiguration.authorization_endpoint;
697
- },
698
- token: function () {
699
- return oidcConfiguration.token_endpoint;
700
- },
701
- logout: function () {
702
- if (!oidcConfiguration.end_session_endpoint) {
703
- throw "Not supported by the OIDC server";
704
- }
705
- return oidcConfiguration.end_session_endpoint;
706
- },
707
- checkSessionIframe: function () {
708
- if (!oidcConfiguration.check_session_iframe) {
709
- throw "Not supported by the OIDC server";
710
- }
711
- return oidcConfiguration.check_session_iframe;
712
- },
713
- register: function () {
714
- throw 'Redirection to "Register user" page not supported in standard OIDC mode';
715
- },
716
- userinfo: function () {
717
- if (!oidcConfiguration.userinfo_endpoint) {
718
- throw "Not supported by the OIDC server";
719
- }
720
- return oidcConfiguration.userinfo_endpoint;
721
- }
722
- };
723
- }
724
- }
725
- if (configUrl) {
726
- var req = new XMLHttpRequest();
727
- req.open('GET', configUrl, true);
728
- req.setRequestHeader('Accept', 'application/json');
729
- req.onreadystatechange = function () {
730
- if (req.readyState == 4) {
731
- if (req.status == 200 || fileLoaded(req)) {
732
- var config = JSON.parse(req.responseText);
733
- kc.authServerUrl = config['auth-server-url'];
734
- kc.realm = config['realm'];
735
- kc.clientId = config['resource'];
736
- setupOidcEndoints(null);
737
- promise.setSuccess();
738
- } else {
739
- promise.setError();
740
- }
741
- }
742
- };
743
- req.send();
744
- } else {
745
- kc.clientId = config.clientId;
746
- var oidcProvider = config['oidcProvider'];
747
- if (!oidcProvider) {
748
- kc.authServerUrl = config.url;
749
- kc.realm = config.realm;
750
- setupOidcEndoints(null);
751
- promise.setSuccess();
752
- } else {
753
- if (typeof oidcProvider === 'string') {
754
- var oidcProviderConfigUrl;
755
- if (oidcProvider.charAt(oidcProvider.length - 1) == '/') {
756
- oidcProviderConfigUrl = oidcProvider + '.well-known/openid-configuration';
757
- } else {
758
- oidcProviderConfigUrl = oidcProvider + '/.well-known/openid-configuration';
759
- }
760
- var req = new XMLHttpRequest();
761
- req.open('GET', oidcProviderConfigUrl, true);
762
- req.setRequestHeader('Accept', 'application/json');
763
- req.onreadystatechange = function () {
764
- if (req.readyState == 4) {
765
- if (req.status == 200 || fileLoaded(req)) {
766
- var oidcProviderConfig = JSON.parse(req.responseText);
767
- setupOidcEndoints(oidcProviderConfig);
768
- promise.setSuccess();
769
- } else {
770
- promise.setError();
771
- }
772
- }
773
- };
774
- req.send();
775
- } else {
776
- setupOidcEndoints(oidcProvider);
777
- promise.setSuccess();
778
- }
779
- }
780
- }
781
- return promise.promise;
782
- }
783
- function fileLoaded(xhr) {
784
- return xhr.status == 0 && xhr.responseText && xhr.responseURL.startsWith('file:');
785
- }
786
- function setToken(token, refreshToken, idToken, timeLocal) {
787
- if (kc.tokenTimeoutHandle) {
788
- clearTimeout(kc.tokenTimeoutHandle);
789
- kc.tokenTimeoutHandle = null;
790
- }
791
- if (refreshToken) {
792
- kc.refreshToken = refreshToken;
793
- kc.refreshTokenParsed = decodeToken(refreshToken);
794
- } else {
795
- delete kc.refreshToken;
796
- delete kc.refreshTokenParsed;
797
- }
798
- if (idToken) {
799
- kc.idToken = idToken;
800
- kc.idTokenParsed = decodeToken(idToken);
801
- } else {
802
- delete kc.idToken;
803
- delete kc.idTokenParsed;
804
- }
805
- if (token) {
806
- kc.token = token;
807
- kc.tokenParsed = decodeToken(token);
808
- kc.sessionId = kc.tokenParsed.sid;
809
- kc.authenticated = true;
810
- kc.subject = kc.tokenParsed.sub;
811
- kc.realmAccess = kc.tokenParsed.realm_access;
812
- kc.resourceAccess = kc.tokenParsed.resource_access;
813
- if (timeLocal) {
814
- kc.timeSkew = Math.floor(timeLocal / 1000) - kc.tokenParsed.iat;
815
- }
816
- if (kc.timeSkew != null) {
817
- logInfo('[KEYCLOAK] Estimated time difference between browser and server is ' + kc.timeSkew + ' seconds');
818
- if (kc.onTokenExpired) {
819
- var expiresIn = (kc.tokenParsed['exp'] - new Date().getTime() / 1000 + kc.timeSkew) * 1000;
820
- logInfo('[KEYCLOAK] Token expires in ' + Math.round(expiresIn / 1000) + ' s');
821
- if (expiresIn <= 0) {
822
- kc.onTokenExpired();
823
- } else {
824
- kc.tokenTimeoutHandle = setTimeout(kc.onTokenExpired, expiresIn);
825
- }
826
- }
827
- }
828
- } else {
829
- delete kc.token;
830
- delete kc.tokenParsed;
831
- delete kc.subject;
832
- delete kc.realmAccess;
833
- delete kc.resourceAccess;
834
- kc.authenticated = false;
835
- }
836
- }
837
- function createUUID() {
838
- if (typeof crypto === "undefined" || typeof crypto.randomUUID === "undefined") {
839
- throw new Error("Web Crypto API is not available.");
840
- }
841
- return crypto.randomUUID();
842
- }
843
- function parseCallback(url) {
844
- var oauth = parseCallbackUrl(url);
845
- if (!oauth) {
846
- return;
847
- }
848
- var oauthState = callbackStorage.get(oauth.state);
849
- if (oauthState) {
850
- oauth.valid = true;
851
- oauth.redirectUri = oauthState.redirectUri;
852
- oauth.storedNonce = oauthState.nonce;
853
- oauth.prompt = oauthState.prompt;
854
- oauth.pkceCodeVerifier = oauthState.pkceCodeVerifier;
855
- oauth.loginOptions = oauthState.loginOptions;
856
- }
857
- return oauth;
858
- }
859
- function parseCallbackUrl(url) {
860
- var supportedParams;
861
- switch (kc.flow) {
862
- case 'standard':
863
- supportedParams = ['code', 'state', 'session_state', 'kc_action_status', 'kc_action', 'iss'];
864
- break;
865
- case 'implicit':
866
- supportedParams = ['access_token', 'token_type', 'id_token', 'state', 'session_state', 'expires_in', 'kc_action_status', 'kc_action', 'iss'];
867
- break;
868
- case 'hybrid':
869
- supportedParams = ['access_token', 'token_type', 'id_token', 'code', 'state', 'session_state', 'expires_in', 'kc_action_status', 'kc_action', 'iss'];
870
- break;
871
- }
872
- supportedParams.push('error');
873
- supportedParams.push('error_description');
874
- supportedParams.push('error_uri');
875
- var queryIndex = url.indexOf('?');
876
- var fragmentIndex = url.indexOf('#');
877
- var newUrl;
878
- var parsed;
879
- if (kc.responseMode === 'query' && queryIndex !== -1) {
880
- newUrl = url.substring(0, queryIndex);
881
- parsed = parseCallbackParams(url.substring(queryIndex + 1, fragmentIndex !== -1 ? fragmentIndex : url.length), supportedParams);
882
- if (parsed.paramsString !== '') {
883
- newUrl += '?' + parsed.paramsString;
884
- }
885
- if (fragmentIndex !== -1) {
886
- newUrl += url.substring(fragmentIndex);
887
- }
888
- } else if (kc.responseMode === 'fragment' && fragmentIndex !== -1) {
889
- newUrl = url.substring(0, fragmentIndex);
890
- parsed = parseCallbackParams(url.substring(fragmentIndex + 1), supportedParams);
891
- if (parsed.paramsString !== '') {
892
- newUrl += '#' + parsed.paramsString;
893
- }
894
- }
895
- if (parsed && parsed.oauthParams) {
896
- if (kc.flow === 'standard' || kc.flow === 'hybrid') {
897
- if ((parsed.oauthParams.code || parsed.oauthParams.error) && parsed.oauthParams.state) {
898
- parsed.oauthParams.newUrl = newUrl;
899
- return parsed.oauthParams;
900
- }
901
- } else if (kc.flow === 'implicit') {
902
- if ((parsed.oauthParams.access_token || parsed.oauthParams.error) && parsed.oauthParams.state) {
903
- parsed.oauthParams.newUrl = newUrl;
904
- return parsed.oauthParams;
905
- }
906
- }
907
- }
908
- }
909
- function parseCallbackParams(paramsString, supportedParams) {
910
- var p = paramsString.split('&');
911
- var result = {
912
- paramsString: '',
913
- oauthParams: {}
914
- };
915
- for (var i = 0; i < p.length; i++) {
916
- var split = p[i].indexOf("=");
917
- var key = p[i].slice(0, split);
918
- if (supportedParams.indexOf(key) !== -1) {
919
- result.oauthParams[key] = p[i].slice(split + 1);
920
- } else {
921
- if (result.paramsString !== '') {
922
- result.paramsString += '&';
923
- }
924
- result.paramsString += p[i];
925
- }
926
- }
927
- return result;
928
- }
929
- function createPromise() {
930
- // Need to create a native Promise which also preserves the
931
- // interface of the custom promise type previously used by the API
932
- var p = {
933
- setSuccess: function (result) {
934
- p.resolve(result);
935
- },
936
- setError: function (result) {
937
- p.reject(result);
938
- }
939
- };
940
- p.promise = new Promise(function (resolve, reject) {
941
- p.resolve = resolve;
942
- p.reject = reject;
943
- });
944
- return p;
945
- }
946
-
947
- // Function to extend existing native Promise with timeout
948
- function applyTimeoutToPromise(promise, timeout, errorMessage) {
949
- var timeoutHandle = null;
950
- var timeoutPromise = new Promise(function (resolve, reject) {
951
- timeoutHandle = setTimeout(function () {
952
- reject({
953
- "error": errorMessage
954
- });
955
- }, timeout);
956
- });
957
- return Promise.race([promise, timeoutPromise]).finally(function () {
958
- clearTimeout(timeoutHandle);
959
- });
960
- }
961
- function setupCheckLoginIframe() {
962
- var promise = createPromise();
963
- if (!loginIframe.enable) {
964
- promise.setSuccess();
965
- return promise.promise;
966
- }
967
- if (loginIframe.iframe) {
968
- promise.setSuccess();
969
- return promise.promise;
970
- }
971
- var iframe = document.createElement('iframe');
972
- loginIframe.iframe = iframe;
973
- iframe.onload = function () {
974
- var authUrl = kc.endpoints.authorize();
975
- if (authUrl.charAt(0) === '/') {
976
- loginIframe.iframeOrigin = getOrigin();
977
- } else {
978
- loginIframe.iframeOrigin = authUrl.substring(0, authUrl.indexOf('/', 8));
979
- }
980
- promise.setSuccess();
981
- };
982
- var src = kc.endpoints.checkSessionIframe();
983
- iframe.setAttribute('src', src);
984
- iframe.setAttribute('sandbox', 'allow-storage-access-by-user-activation allow-scripts allow-same-origin');
985
- iframe.setAttribute('title', 'keycloak-session-iframe');
986
- iframe.style.display = 'none';
987
- document.body.appendChild(iframe);
988
- var messageCallback = function (event) {
989
- if (event.origin !== loginIframe.iframeOrigin || loginIframe.iframe.contentWindow !== event.source) {
990
- return;
991
- }
992
- if (!(event.data == 'unchanged' || event.data == 'changed' || event.data == 'error')) {
993
- return;
994
- }
995
- if (event.data != 'unchanged') {
996
- kc.clearToken();
997
- }
998
- var callbacks = loginIframe.callbackList.splice(0, loginIframe.callbackList.length);
999
- for (var i = callbacks.length - 1; i >= 0; --i) {
1000
- var promise = callbacks[i];
1001
- if (event.data == 'error') {
1002
- promise.setError();
1003
- } else {
1004
- promise.setSuccess(event.data == 'unchanged');
1005
- }
1006
- }
1007
- };
1008
- window.addEventListener('message', messageCallback, false);
1009
- return promise.promise;
1010
- }
1011
- function scheduleCheckIframe() {
1012
- if (loginIframe.enable) {
1013
- if (kc.token) {
1014
- setTimeout(function () {
1015
- checkLoginIframe().then(function (unchanged) {
1016
- if (unchanged) {
1017
- scheduleCheckIframe();
1018
- }
1019
- });
1020
- }, loginIframe.interval * 1000);
1021
- }
1022
- }
1023
- }
1024
- function checkLoginIframe() {
1025
- var promise = createPromise();
1026
- if (loginIframe.iframe && loginIframe.iframeOrigin) {
1027
- var msg = kc.clientId + ' ' + (kc.sessionId ? kc.sessionId : '');
1028
- loginIframe.callbackList.push(promise);
1029
- var origin = loginIframe.iframeOrigin;
1030
- if (loginIframe.callbackList.length == 1) {
1031
- loginIframe.iframe.contentWindow.postMessage(msg, origin);
1032
- }
1033
- } else {
1034
- promise.setSuccess();
1035
- }
1036
- return promise.promise;
1037
- }
1038
- function check3pCookiesSupported() {
1039
- var promise = createPromise();
1040
- if ((loginIframe.enable || kc.silentCheckSsoRedirectUri) && typeof kc.endpoints.thirdPartyCookiesIframe === 'function') {
1041
- var iframe = document.createElement('iframe');
1042
- iframe.setAttribute('src', kc.endpoints.thirdPartyCookiesIframe());
1043
- iframe.setAttribute('sandbox', 'allow-storage-access-by-user-activation allow-scripts allow-same-origin');
1044
- iframe.setAttribute('title', 'keycloak-3p-check-iframe');
1045
- iframe.style.display = 'none';
1046
- document.body.appendChild(iframe);
1047
- var messageCallback = function (event) {
1048
- if (iframe.contentWindow !== event.source) {
1049
- return;
1050
- }
1051
- if (event.data !== "supported" && event.data !== "unsupported") {
1052
- return;
1053
- } else if (event.data === "unsupported") {
1054
- logWarn("[KEYCLOAK] Your browser is blocking access to 3rd-party cookies, this means:\n\n" + " - It is not possible to retrieve tokens without redirecting to the Keycloak server (a.k.a. no support for silent authentication).\n" + " - It is not possible to automatically detect changes to the session status (such as the user logging out in another tab).\n\n" + "For more information see: https://www.keycloak.org/securing-apps/javascript-adapter#_modern_browsers");
1055
- loginIframe.enable = false;
1056
- if (kc.silentCheckSsoFallback) {
1057
- kc.silentCheckSsoRedirectUri = false;
1058
- }
1059
- }
1060
- document.body.removeChild(iframe);
1061
- window.removeEventListener("message", messageCallback);
1062
- promise.setSuccess();
1063
- };
1064
- window.addEventListener('message', messageCallback, false);
1065
- } else {
1066
- promise.setSuccess();
1067
- }
1068
- return applyTimeoutToPromise(promise.promise, kc.messageReceiveTimeout, "Timeout when waiting for 3rd party check iframe message.");
1069
- }
1070
- function loadAdapter(type) {
1071
- if (!type || type == 'default') {
1072
- return {
1073
- login: async function (options) {
1074
- window.location.assign(await kc.createLoginUrl(options));
1075
- return createPromise().promise;
1076
- },
1077
- logout: async function (options) {
1078
- const logoutMethod = options?.logoutMethod ?? kc.logoutMethod;
1079
- if (logoutMethod === "GET") {
1080
- window.location.replace(kc.createLogoutUrl(options));
1081
- return;
1082
- }
1083
-
1084
- // Create form to send POST request.
1085
- const form = document.createElement("form");
1086
- form.setAttribute("method", "POST");
1087
- form.setAttribute("action", kc.createLogoutUrl(options));
1088
- form.style.display = "none";
1089
-
1090
- // Add data to form as hidden input fields.
1091
- const data = {
1092
- id_token_hint: kc.idToken,
1093
- client_id: kc.clientId,
1094
- post_logout_redirect_uri: adapter.redirectUri(options, false)
1095
- };
1096
- for (const [name, value] of Object.entries(data)) {
1097
- const input = document.createElement("input");
1098
- input.setAttribute("type", "hidden");
1099
- input.setAttribute("name", name);
1100
- input.setAttribute("value", value);
1101
- form.appendChild(input);
1102
- }
1103
-
1104
- // Append form to page and submit it to perform logout and redirect.
1105
- document.body.appendChild(form);
1106
- form.submit();
1107
- },
1108
- register: async function (options) {
1109
- window.location.assign(await kc.createRegisterUrl(options));
1110
- return createPromise().promise;
1111
- },
1112
- accountManagement: function () {
1113
- var accountUrl = kc.createAccountUrl();
1114
- if (typeof accountUrl !== 'undefined') {
1115
- window.location.href = accountUrl;
1116
- } else {
1117
- throw "Not supported by the OIDC server";
1118
- }
1119
- return createPromise().promise;
1120
- },
1121
- redirectUri: function (options, encodeHash) {
1122
- if (options && options.redirectUri) {
1123
- return options.redirectUri;
1124
- } else if (kc.redirectUri) {
1125
- return kc.redirectUri;
1126
- } else {
1127
- return location.href;
1128
- }
1129
- }
1130
- };
1131
- }
1132
- if (type == 'cordova') {
1133
- loginIframe.enable = false;
1134
- var cordovaOpenWindowWrapper = function (loginUrl, target, options) {
1135
- if (window.cordova && window.cordova.InAppBrowser) {
1136
- // Use inappbrowser for IOS and Android if available
1137
- return window.cordova.InAppBrowser.open(loginUrl, target, options);
1138
- } else {
1139
- return window.open(loginUrl, target, options);
1140
- }
1141
- };
1142
- var shallowCloneCordovaOptions = function (userOptions) {
1143
- if (userOptions && userOptions.cordovaOptions) {
1144
- return Object.keys(userOptions.cordovaOptions).reduce(function (options, optionName) {
1145
- options[optionName] = userOptions.cordovaOptions[optionName];
1146
- return options;
1147
- }, {});
1148
- } else {
1149
- return {};
1150
- }
1151
- };
1152
- var formatCordovaOptions = function (cordovaOptions) {
1153
- return Object.keys(cordovaOptions).reduce(function (options, optionName) {
1154
- options.push(optionName + "=" + cordovaOptions[optionName]);
1155
- return options;
1156
- }, []).join(",");
1157
- };
1158
- var createCordovaOptions = function (userOptions) {
1159
- var cordovaOptions = shallowCloneCordovaOptions(userOptions);
1160
- cordovaOptions.location = 'no';
1161
- if (userOptions && userOptions.prompt == 'none') {
1162
- cordovaOptions.hidden = 'yes';
1163
- }
1164
- return formatCordovaOptions(cordovaOptions);
1165
- };
1166
- var getCordovaRedirectUri = function () {
1167
- return kc.redirectUri || 'http://localhost';
1168
- };
1169
- return {
1170
- login: async function (options) {
1171
- var promise = createPromise();
1172
- var cordovaOptions = createCordovaOptions(options);
1173
- var loginUrl = await kc.createLoginUrl(options);
1174
- var ref = cordovaOpenWindowWrapper(loginUrl, '_blank', cordovaOptions);
1175
- var completed = false;
1176
- var closed = false;
1177
- var closeBrowser = function () {
1178
- closed = true;
1179
- ref.close();
1180
- };
1181
- ref.addEventListener('loadstart', function (event) {
1182
- if (event.url.indexOf(getCordovaRedirectUri()) == 0) {
1183
- var callback = parseCallback(event.url);
1184
- processCallback(callback, promise);
1185
- closeBrowser();
1186
- completed = true;
1187
- }
1188
- });
1189
- ref.addEventListener('loaderror', function (event) {
1190
- if (!completed) {
1191
- if (event.url.indexOf(getCordovaRedirectUri()) == 0) {
1192
- var callback = parseCallback(event.url);
1193
- processCallback(callback, promise);
1194
- closeBrowser();
1195
- completed = true;
1196
- } else {
1197
- promise.setError();
1198
- closeBrowser();
1199
- }
1200
- }
1201
- });
1202
- ref.addEventListener('exit', function (event) {
1203
- if (!closed) {
1204
- promise.setError({
1205
- reason: "closed_by_user"
1206
- });
1207
- }
1208
- });
1209
- return promise.promise;
1210
- },
1211
- logout: function (options) {
1212
- var promise = createPromise();
1213
- var logoutUrl = kc.createLogoutUrl(options);
1214
- var ref = cordovaOpenWindowWrapper(logoutUrl, '_blank', 'location=no,hidden=yes,clearcache=yes');
1215
- var error;
1216
- ref.addEventListener('loadstart', function (event) {
1217
- if (event.url.indexOf(getCordovaRedirectUri()) == 0) {
1218
- ref.close();
1219
- }
1220
- });
1221
- ref.addEventListener('loaderror', function (event) {
1222
- if (event.url.indexOf(getCordovaRedirectUri()) == 0) {
1223
- ref.close();
1224
- } else {
1225
- error = true;
1226
- ref.close();
1227
- }
1228
- });
1229
- ref.addEventListener('exit', function (event) {
1230
- if (error) {
1231
- promise.setError();
1232
- } else {
1233
- kc.clearToken();
1234
- promise.setSuccess();
1235
- }
1236
- });
1237
- return promise.promise;
1238
- },
1239
- register: async function (options) {
1240
- var promise = createPromise();
1241
- var registerUrl = await kc.createRegisterUrl();
1242
- var cordovaOptions = createCordovaOptions(options);
1243
- var ref = cordovaOpenWindowWrapper(registerUrl, '_blank', cordovaOptions);
1244
- ref.addEventListener('loadstart', function (event) {
1245
- if (event.url.indexOf(getCordovaRedirectUri()) == 0) {
1246
- ref.close();
1247
- var oauth = parseCallback(event.url);
1248
- processCallback(oauth, promise);
1249
- }
1250
- });
1251
- return promise.promise;
1252
- },
1253
- accountManagement: function () {
1254
- var accountUrl = kc.createAccountUrl();
1255
- if (typeof accountUrl !== 'undefined') {
1256
- var ref = cordovaOpenWindowWrapper(accountUrl, '_blank', 'location=no');
1257
- ref.addEventListener('loadstart', function (event) {
1258
- if (event.url.indexOf(getCordovaRedirectUri()) == 0) {
1259
- ref.close();
1260
- }
1261
- });
1262
- } else {
1263
- throw "Not supported by the OIDC server";
1264
- }
1265
- },
1266
- redirectUri: function (options) {
1267
- return getCordovaRedirectUri();
1268
- }
1269
- };
1270
- }
1271
- if (type == 'cordova-native') {
1272
- loginIframe.enable = false;
1273
- return {
1274
- login: async function (options) {
1275
- var promise = createPromise();
1276
- var loginUrl = await kc.createLoginUrl(options);
1277
- universalLinks.subscribe('keycloak', function (event) {
1278
- universalLinks.unsubscribe('keycloak');
1279
- window.cordova.plugins.browsertab.close();
1280
- var oauth = parseCallback(event.url);
1281
- processCallback(oauth, promise);
1282
- });
1283
- window.cordova.plugins.browsertab.openUrl(loginUrl);
1284
- return promise.promise;
1285
- },
1286
- logout: function (options) {
1287
- var promise = createPromise();
1288
- var logoutUrl = kc.createLogoutUrl(options);
1289
- universalLinks.subscribe('keycloak', function (event) {
1290
- universalLinks.unsubscribe('keycloak');
1291
- window.cordova.plugins.browsertab.close();
1292
- kc.clearToken();
1293
- promise.setSuccess();
1294
- });
1295
- window.cordova.plugins.browsertab.openUrl(logoutUrl);
1296
- return promise.promise;
1297
- },
1298
- register: async function (options) {
1299
- var promise = createPromise();
1300
- var registerUrl = await kc.createRegisterUrl(options);
1301
- universalLinks.subscribe('keycloak', function (event) {
1302
- universalLinks.unsubscribe('keycloak');
1303
- window.cordova.plugins.browsertab.close();
1304
- var oauth = parseCallback(event.url);
1305
- processCallback(oauth, promise);
1306
- });
1307
- window.cordova.plugins.browsertab.openUrl(registerUrl);
1308
- return promise.promise;
1309
- },
1310
- accountManagement: function () {
1311
- var accountUrl = kc.createAccountUrl();
1312
- if (typeof accountUrl !== 'undefined') {
1313
- window.cordova.plugins.browsertab.openUrl(accountUrl);
1314
- } else {
1315
- throw "Not supported by the OIDC server";
1316
- }
1317
- },
1318
- redirectUri: function (options) {
1319
- if (options && options.redirectUri) {
1320
- return options.redirectUri;
1321
- } else if (kc.redirectUri) {
1322
- return kc.redirectUri;
1323
- } else {
1324
- return "http://localhost";
1325
- }
1326
- }
1327
- };
1328
- }
1329
- throw 'invalid adapter type: ' + type;
1330
- }
1331
- const STORAGE_KEY_PREFIX = 'kc-callback-';
1332
- var LocalStorage = function () {
1333
- if (!(this instanceof LocalStorage)) {
1334
- return new LocalStorage();
1335
- }
1336
- localStorage.setItem('kc-test', 'test');
1337
- localStorage.removeItem('kc-test');
1338
- var cs = this;
1339
-
1340
- /**
1341
- * Clears all values from local storage that are no longer valid.
1342
- */
1343
- function clearInvalidValues() {
1344
- const currentTime = Date.now();
1345
- for (const [key, value] of getStoredEntries()) {
1346
- // Attempt to parse the expiry time from the value.
1347
- const expiry = parseExpiry(value);
1348
-
1349
- // Discard the value if it is malformed or expired.
1350
- if (expiry === null || expiry < currentTime) {
1351
- localStorage.removeItem(key);
1352
- }
1353
- }
1354
- }
1355
-
1356
- /**
1357
- * Clears all known values from local storage.
1358
- */
1359
- function clearAllValues() {
1360
- for (const [key] of getStoredEntries()) {
1361
- localStorage.removeItem(key);
1362
- }
1363
- }
1364
-
1365
- /**
1366
- * Gets all entries stored in local storage that are known to be managed by this class.
1367
- * @returns {Array<[string, unknown]>} An array of key-value pairs.
1368
- */
1369
- function getStoredEntries() {
1370
- return Object.entries(localStorage).filter(([key]) => key.startsWith(STORAGE_KEY_PREFIX));
1371
- }
1372
-
1373
- /**
1374
- * Parses the expiry time from a value stored in local storage.
1375
- * @param {unknown} value
1376
- * @returns {number | null} The expiry time in milliseconds, or `null` if the value is malformed.
1377
- */
1378
- function parseExpiry(value) {
1379
- let parsedValue;
1380
-
1381
- // Attempt to parse the value as JSON.
1382
- try {
1383
- parsedValue = JSON.parse(value);
1384
- } catch (error) {
1385
- return null;
1386
- }
1387
-
1388
- // Attempt to extract the 'expires' property.
1389
- if (isObject(parsedValue) && 'expires' in parsedValue && typeof parsedValue.expires === 'number') {
1390
- return parsedValue.expires;
1391
- }
1392
- return null;
1393
- }
1394
- cs.get = function (state) {
1395
- if (!state) {
1396
- return;
1397
- }
1398
- var key = STORAGE_KEY_PREFIX + state;
1399
- var value = localStorage.getItem(key);
1400
- if (value) {
1401
- localStorage.removeItem(key);
1402
- value = JSON.parse(value);
1403
- }
1404
- clearInvalidValues();
1405
- return value;
1406
- };
1407
- cs.add = function (state) {
1408
- clearInvalidValues();
1409
- const key = STORAGE_KEY_PREFIX + state.state;
1410
- const value = JSON.stringify({
1411
- ...state,
1412
- // Set the expiry time to 1 hour from now.
1413
- expires: Date.now() + 60 * 60 * 1000
1414
- });
1415
- try {
1416
- localStorage.setItem(key, value);
1417
- } catch (error) {
1418
- // If the storage is full, clear all known values and try again.
1419
- clearAllValues();
1420
- localStorage.setItem(key, value);
1421
- }
1422
- };
1423
- };
1424
- var CookieStorage = function () {
1425
- if (!(this instanceof CookieStorage)) {
1426
- return new CookieStorage();
1427
- }
1428
- var cs = this;
1429
- cs.get = function (state) {
1430
- if (!state) {
1431
- return;
1432
- }
1433
- var value = getCookie(STORAGE_KEY_PREFIX + state);
1434
- setCookie(STORAGE_KEY_PREFIX + state, '', cookieExpiration(-100));
1435
- if (value) {
1436
- return JSON.parse(value);
1437
- }
1438
- };
1439
- cs.add = function (state) {
1440
- setCookie(STORAGE_KEY_PREFIX + state.state, JSON.stringify(state), cookieExpiration(60));
1441
- };
1442
- cs.removeItem = function (key) {
1443
- setCookie(key, '', cookieExpiration(-100));
1444
- };
1445
- var cookieExpiration = function (minutes) {
1446
- var exp = new Date();
1447
- exp.setTime(exp.getTime() + minutes * 60 * 1000);
1448
- return exp;
1449
- };
1450
- var getCookie = function (key) {
1451
- var name = key + '=';
1452
- var ca = document.cookie.split(';');
1453
- for (var i = 0; i < ca.length; i++) {
1454
- var c = ca[i];
1455
- while (c.charAt(0) == ' ') {
1456
- c = c.substring(1);
1457
- }
1458
- if (c.indexOf(name) == 0) {
1459
- return c.substring(name.length, c.length);
1460
- }
1461
- }
1462
- return '';
1463
- };
1464
- var setCookie = function (key, value, expirationDate) {
1465
- var cookie = key + '=' + value + '; ' + 'expires=' + expirationDate.toUTCString() + '; ';
1466
- document.cookie = cookie;
1467
- };
1468
- };
1469
- function createCallbackStorage() {
1470
- try {
1471
- return new LocalStorage();
1472
- } catch (err) {}
1473
- return new CookieStorage();
1474
- }
1475
- function createLogger(fn) {
1476
- return function () {
1477
- if (kc.enableLogging) {
1478
- fn.apply(console, Array.prototype.slice.call(arguments));
1479
- }
1480
- };
1481
- }
1482
- }
1483
-
1484
- /**
1485
- * @param {ArrayBuffer} bytes
1486
- * @see https://developer.mozilla.org/en-US/docs/Glossary/Base64#the_unicode_problem
1487
- */
1488
- function bytesToBase64(bytes) {
1489
- const binString = String.fromCodePoint(...bytes);
1490
- return btoa(binString);
1491
- }
1492
-
1493
- /**
1494
- * @param {string} message
1495
- * @see https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest#basic_example
1496
- */
1497
- async function sha256Digest(message) {
1498
- const encoder = new TextEncoder();
1499
- const data = encoder.encode(message);
1500
- if (typeof crypto === "undefined" || typeof crypto.subtle === "undefined") {
1501
- throw new Error("Web Crypto API is not available.");
1502
- }
1503
- return await crypto.subtle.digest("SHA-256", data);
1504
- }
1505
-
1506
- /**
1507
- * @param {string} token
1508
- */
1509
- function decodeToken(token) {
1510
- const [header, payload] = token.split(".");
1511
- if (typeof payload !== "string") {
1512
- throw new Error("Unable to decode token, payload not found.");
1513
- }
1514
- let decoded;
1515
- try {
1516
- decoded = base64UrlDecode(payload);
1517
- } catch (error) {
1518
- throw new Error("Unable to decode token, payload is not a valid Base64URL value.", {
1519
- cause: error
1520
- });
1521
- }
1522
- try {
1523
- return JSON.parse(decoded);
1524
- } catch (error) {
1525
- throw new Error("Unable to decode token, payload is not a valid JSON value.", {
1526
- cause: error
1527
- });
1528
- }
1529
- }
1530
-
1531
- /**
1532
- * @param {string} input
1533
- */
1534
- function base64UrlDecode(input) {
1535
- let output = input.replaceAll("-", "+").replaceAll("_", "/");
1536
- switch (output.length % 4) {
1537
- case 0:
1538
- break;
1539
- case 2:
1540
- output += "==";
1541
- break;
1542
- case 3:
1543
- output += "=";
1544
- break;
1545
- default:
1546
- throw new Error("Input is not of the correct length.");
1547
- }
1548
- try {
1549
- return b64DecodeUnicode(output);
1550
- } catch (error) {
1551
- return atob(output);
1552
- }
1553
- }
1554
-
1555
- /**
1556
- * @param {string} input
1557
- */
1558
- function b64DecodeUnicode(input) {
1559
- return decodeURIComponent(atob(input).replace(/(.)/g, (m, p) => {
1560
- let code = p.charCodeAt(0).toString(16).toUpperCase();
1561
- if (code.length < 2) {
1562
- code = "0" + code;
1563
- }
1564
- return "%" + code;
1565
- }));
1566
- }
1567
-
1568
- /**
1569
- * Check if the input is an object that can be operated on.
1570
- * @param {unknown} input
1571
- */
1572
- function isObject(input) {
1573
- return typeof input === 'object' && input !== null;
1574
- }
1575
- let keycloak = null;
1576
- let keycloakInitPromise = null;
1577
- // Initialize Keycloak with an optional silent check
1578
- function initKeycloak(config, silentCheck = true) {
1579
- // If already initializing or initialized, return the cached promise
1580
- if (keycloakInitPromise) {
1581
- // eslint-disable-next-line
1582
- console.log('Keycloak already initialized, returning from cache');
1583
- return keycloakInitPromise;
1584
- }
1585
- if (!keycloak) {
1586
- keycloak = new Keycloak({
1587
- url: config.url,
1588
- realm: config.realm,
1589
- clientId: config.clientId
1590
- });
1591
- }
1592
- keycloakInitPromise = keycloak.init({
1593
- onLoad: silentCheck ? 'check-sso' : 'login-required',
1594
- checkLoginIframe: false
1595
- //silentCheckSsoRedirectUri: `${window.location.origin}/silent-check-sso.html`, // Ensure this file is set up
1596
- }).then(authenticated => authenticated).catch(error => {
1597
- // eslint-disable-next-line
1598
- console.error('Failed to initialize Keycloak:', error);
1599
- return false;
1600
- });
1601
- return keycloakInitPromise;
1602
- }
1603
- function getUser() {
1604
- if ((keycloak === null || keycloak === void 0 ? void 0 : keycloak.authenticated) && (keycloak === null || keycloak === void 0 ? void 0 : keycloak.idTokenParsed)) {
1605
- return {
1606
- fullname: keycloak.idTokenParsed.name,
1607
- email: keycloak.idTokenParsed.email,
1608
- lastname: keycloak.idTokenParsed.family_name,
1609
- firstname: keycloak.idTokenParsed.given_name,
1610
- username: keycloak.idTokenParsed.preferred_username,
1611
- background: 'grey',
1612
- // Optional custom value
1613
- token: keycloak.token,
1614
- sub: keycloak.idTokenParsed.sub
1615
- };
1616
- }
1617
- return {};
1618
- }
1619
- // Log in the user
1620
- function login() {
1621
- if (keycloak) {
1622
- keycloak.login();
1623
- } else {
1624
- throw new Error('Keycloak is not initialized.');
1625
- }
1626
- }
1627
- // Log out the user
1628
- function logout() {
1629
- if (keycloak) {
1630
- keycloak.logout();
1631
- } else {
1632
- throw new Error('Keycloak is not initialized.');
1633
- }
1634
- }
1635
- // Check if the user is authenticated
1636
- function isAuthenticated() {
1637
- return !!(keycloak === null || keycloak === void 0 ? void 0 : keycloak.authenticated);
1638
- }
1639
- async function checkServerAvailability(url) {
1640
- try {
1641
- const response = await fetch(url, {
1642
- method: 'HEAD',
1643
- mode: 'no-cors'
1644
- });
1645
- return response.ok || response.type === 'opaque';
1646
- } catch (_a) {
1647
- return false;
1648
- }
1649
- }
1650
- const EdsLogin = class {
1651
- constructor(hostRef) {
1652
- registerInstance(this, hostRef);
1653
- this.keycloak = createEvent(this, "keycloak", 7);
1654
- this.auth = createEvent(this, "auth", 7);
1655
- /**
1656
- * Handles user login by invoking the Keycloak `login` function.
1657
- * Only triggers login if the user is not already authenticated.
1658
- */
1659
- this.handleLogin = async () => {
1660
- if (!this.authenticated) {
1661
- try {
1662
- await login();
1663
- } catch (error) {
1664
- toast.show(error.message, 'error');
1665
- }
1666
- }
1667
- };
1668
- /**
1669
- * Handles user logout by invoking the Keycloak `logout` function.
1670
- * Resets the `authenticated` state to `false` after logout.
1671
- */
1672
- this.handleLogout = async () => {
1673
- try {
1674
- await logout();
1675
- } catch (error) {
1676
- toast.show(error.message, 'error');
1677
- }
1678
- this.authenticated = false;
1679
- this.user = null;
1680
- };
1681
- this.keycloakUrl = undefined;
1682
- this.keycloakRealm = undefined;
1683
- this.keycloakClientId = undefined;
1684
- this.authenticated = false;
1685
- this.user = null;
1686
- this.serverAvailable = false;
1687
- }
1688
- /**
1689
- * Lifecycle method that runs when the component is about to load.
1690
- * It initializes authentication by calling the `initAuth` method.
1691
- */
1692
- async componentWillLoad() {
1693
- // Check if required props are provided (optional check)
1694
- if (!this.keycloakUrl || !this.keycloakRealm || !this.keycloakClientId) {
1695
- // eslint-disable-next-line
1696
- console.error('Keycloak configuration props are missing.');
1697
- return;
1698
- }
1699
- this.serverAvailable = await checkServerAvailability(`${this.keycloakUrl}/realms/${this.keycloakRealm}`);
1700
- if (!this.serverAvailable) {
1701
- toast.show('Keycloak server is unavailable.', 'error');
1702
- return; // Do not proceed further
1703
- }
1704
- await this.initAuth();
1705
- }
1706
- /**
1707
- * Initializes the Keycloak authentication by configuring Keycloak with the provided props.
1708
- * Sets the `authenticated` state and `user` data if the user is authenticated.
1709
- * Emits `authStatusChanged` event with the authentication status.
1710
- */
1711
- async initAuth() {
1712
- try {
1713
- const res = await initKeycloak({
1714
- url: this.keycloakUrl,
1715
- realm: this.keycloakRealm,
1716
- clientId: this.keycloakClientId
1717
- }, true);
1718
- this.keycloak.emit({
1719
- init: res
1720
- });
1721
- if (isAuthenticated()) {
1722
- this.user = getUser();
1723
- this.authenticated = true;
1724
- this.auth.emit({
1725
- authenticated: this.authenticated,
1726
- user: this.user
1727
- }); // Emit auth status change
1728
- }
1729
- } catch (error) {
1730
- toast.show(error.message, 'error');
1731
- }
1732
- }
1733
- render() {
1734
- return h("div", {
1735
- key: 'ac10895096f36f2fb3a79622972d5a8c519685eb',
1736
- class: "block"
1737
- }, !this.authenticated && h("eds-button", {
1738
- key: '55aab5ee63214d6a1ccdefc303273df99aa309cf',
1739
- label: "Login",
1740
- intent: "primary",
1741
- "extra-class": "text-default",
1742
- "aria-label": "Login",
1743
- triggerClick: this.handleLogin.bind(this)
1744
- }));
1745
- }
1746
- };
1747
- const edsSplashScreenCss = ".splash-overlay{position:fixed;top:0;left:0;width:100vw;height:100vh;z-index:9999999;background-color:var(--grey-200);display:flex;flex-direction:column;align-items:center;justify-content:center}.logo-container{width:200px;height:200px;margin-bottom:1rem}.content-container{position:relative;width:5rem;height:5rem;display:flex;align-items:center;justify-content:center}";
1748
- const EdsSplashScreenStyle0 = edsSplashScreenCss;
1749
- const EdsSplashScreen = class {
1750
- constructor(hostRef) {
1751
- registerInstance(this, hostRef);
1752
- this.splash = createEvent(this, "splash", 7);
1753
- this.inverse = false;
1754
- this.initPromise = undefined;
1755
- this.isVisible = true;
1756
- }
1757
- // When the component loads, check if there is a promise.
1758
- componentWillLoad() {
1759
- if (this.initPromise) {
1760
- this.handleInitPromise(this.initPromise);
1761
- }
1762
- }
1763
- // Watch for changes on initPromise.
1764
- async watchInitPromise(newPromise) {
1765
- if (newPromise) {
1766
- this.handleInitPromise(newPromise);
1767
- }
1768
- }
1769
- async handleInitPromise(promise) {
1770
- try {
1771
- await promise;
1772
- //console.log('Promises resolved');
1773
- this.hideSplash();
1774
- } catch (error) {
1775
- //console.error('Initialization error:', error);
1776
- this.splash.emit({
1777
- type: 'error',
1778
- message: error.message || 'Unknown error'
1779
- });
1780
- }
1781
- }
1782
- handleHideSplash() {
1783
- this.hideSplash();
1784
- }
1785
- hideSplash() {
1786
- this.isVisible = false;
1787
- this.splash.emit({
1788
- type: 'hidden',
1789
- message: 'Splash screen hidden successfully'
1790
- });
1791
- }
1792
- render() {
1793
- if (!this.isVisible) {
1794
- return null;
1795
- }
1796
- return h(Host, null, h("div", {
1797
- class: "splash-overlay",
1798
- style: {
1799
- background: this.inverse ? 'black' : 'var(--grey-200)'
1800
- }
1801
- }, h("div", {
1802
- class: "logo-container"
1803
- }, this.inverse ? h("eds-logo", {
1804
- orientation: "vertical",
1805
- type: "color-white"
1806
- }) : h("eds-logo", {
1807
- orientation: "vertical",
1808
- type: "color"
1809
- })), h("div", {
1810
- class: "content-container"
1811
- }, h("eds-spinner", {
1812
- size: "1rem",
1813
- thickness: "3px",
1814
- "border-color": "var(--grey-400)",
1815
- "bottom-color": "var(--grey-900)",
1816
- background: "none",
1817
- fullscreen: false
1818
- }))));
1819
- }
1820
- static get watchers() {
1821
- return {
1822
- "initPromise": ["watchInitPromise"]
1823
- };
1824
- }
1825
- };
1826
- EdsSplashScreen.style = EdsSplashScreenStyle0;
1827
-
1828
- export { EdsLogin as eds_login, EdsSplashScreen as eds_splash_screen };