oidc-spa 8.2.6 → 8.2.7

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.
@@ -10,7 +10,7 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
10
10
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
11
11
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
12
12
  };
13
- var _Keycloak_state;
13
+ var _Keycloak_instances, _Keycloak_state, _Keycloak_init, _Keycloak_login, _Keycloak_logout, _Keycloak_register, _Keycloak_accountManagement, _Keycloak_createAccountUrl, _Keycloak_isTokenExpired, _Keycloak_updateToken, _Keycloak_hasRealmRole, _Keycloak_hasResourceRole, _Keycloak_loadUserProfile, _Keycloak_loadUserInfo;
14
14
  Object.defineProperty(exports, "__esModule", { value: true });
15
15
  exports.Keycloak = void 0;
16
16
  const assert_1 = require("../../tools/tsafe/assert");
@@ -40,7 +40,14 @@ class Keycloak {
40
40
  * I'm not seeing the usecase when ran against keycloak right now so not doing it.
41
41
  */
42
42
  constructor(params) {
43
+ _Keycloak_instances.add(this);
43
44
  _Keycloak_state.set(this, void 0);
45
+ /**
46
+ * Called to initialize the adapter.
47
+ * @param initOptions Initialization options.
48
+ * @returns A promise to set functions to be invoked on success or error.
49
+ */
50
+ this.init = __classPrivateFieldGet(this, _Keycloak_instances, "m", _Keycloak_init).bind(this);
44
51
  /**
45
52
  * Response mode passed in init (default value is `'fragment'`).
46
53
  *
@@ -61,6 +68,109 @@ class Keycloak {
61
68
  * NOTE oidc-spa: Can only be 'standard'
62
69
  */
63
70
  this.flow = "standard";
71
+ /**
72
+ * Redirects to login form.
73
+ * @param options Login options.
74
+ */
75
+ this.login = __classPrivateFieldGet(this, _Keycloak_instances, "m", _Keycloak_login).bind(this);
76
+ /**
77
+ * Redirects to logout.
78
+ * @param options Logout options.
79
+ */
80
+ this.logout = __classPrivateFieldGet(this, _Keycloak_instances, "m", _Keycloak_logout).bind(this);
81
+ /**
82
+ * Redirects to registration form.
83
+ * @param options The options used for the registration.
84
+ */
85
+ this.register = __classPrivateFieldGet(this, _Keycloak_instances, "m", _Keycloak_register).bind(this);
86
+ /**
87
+ * Redirects to the Account Management Console.
88
+ */
89
+ this.accountManagement = __classPrivateFieldGet(this, _Keycloak_instances, "m", _Keycloak_accountManagement).bind(this);
90
+ /**
91
+ * Returns the URL to login form.
92
+ * @param options Supports same options as Keycloak#login.
93
+ *
94
+ * NOTE oidc-spa: Not supported, please use login() method.
95
+ */
96
+ //createLoginUrl(options?: KeycloakLoginOptions): Promise<string>;
97
+ /**
98
+ * Returns the URL to logout the user.
99
+ * @param options Logout options.
100
+ *
101
+ * NOTE oidc-spa: Not supported, please use logout() method.
102
+ */
103
+ //createLogoutUrl(options?: KeycloakLogoutOptions): string;
104
+ /**
105
+ * Returns the URL to registration page.
106
+ * @param options The options used for creating the registration URL.
107
+ *
108
+ * NOTE oidc-spa: Not supported please user login({ action: "register" })
109
+ */
110
+ //createRegisterUrl(options?: KeycloakRegisterOptions): Promise<string>;
111
+ /**
112
+ * Returns the URL to the Account Management Console.
113
+ * @param options The options used for creating the account URL.
114
+ */
115
+ this.createAccountUrl = __classPrivateFieldGet(this, _Keycloak_instances, "m", _Keycloak_createAccountUrl).bind(this);
116
+ /**
117
+ * Returns true if the token has less than `minValidity` seconds left before
118
+ * it expires.
119
+ * @param minValidity If not specified, `0` is used.
120
+ */
121
+ this.isTokenExpired = __classPrivateFieldGet(this, _Keycloak_instances, "m", _Keycloak_isTokenExpired).bind(this);
122
+ /**
123
+ * If the token expires within `minValidity` seconds, the token is refreshed.
124
+ * If the session status iframe is enabled, the session status is also
125
+ * checked.
126
+ * @param minValidity If not specified, `5` is used.
127
+ * @returns A promise to set functions that can be invoked if the token is
128
+ * still valid, or if the token is no longer valid.
129
+ * @example
130
+ * ```js
131
+ * keycloak.updateToken(5).then(function(refreshed) {
132
+ * if (refreshed) {
133
+ * alert('Token was successfully refreshed');
134
+ * } else {
135
+ * alert('Token is still valid');
136
+ * }
137
+ * }).catch(function() {
138
+ * alert('Failed to refresh the token, or the session has expired');
139
+ * });
140
+ */
141
+ this.updateToken = __classPrivateFieldGet(this, _Keycloak_instances, "m", _Keycloak_updateToken).bind(this);
142
+ /**
143
+ * Clears authentication state, including tokens. This can be useful if
144
+ * the application has detected the session was expired, for example if
145
+ * updating token fails. Invoking this results in Keycloak#onAuthLogout
146
+ * callback listener being invoked.
147
+ *
148
+ * NOTE oidc-spa: In this implementation we never end up in the kind of
149
+ * state where calling this makes sense.
150
+ * oidc-spa take more control and exposes less complexity to the user of the
151
+ * adapter.
152
+ */
153
+ //clearToken(): void;
154
+ /**
155
+ * Returns true if the token has the given realm role.
156
+ * @param role A realm role name.
157
+ */
158
+ this.hasRealmRole = __classPrivateFieldGet(this, _Keycloak_instances, "m", _Keycloak_hasRealmRole).bind(this);
159
+ /**
160
+ * Returns true if the token has the given role for the resource.
161
+ * @param role A role name.
162
+ * @param resource If not specified, `clientId` is used.
163
+ */
164
+ this.hasResourceRole = __classPrivateFieldGet(this, _Keycloak_instances, "m", _Keycloak_hasResourceRole).bind(this);
165
+ /**
166
+ * Loads the user's profile.
167
+ * @returns A promise to set functions to be invoked on success or error.
168
+ */
169
+ this.loadUserProfile = __classPrivateFieldGet(this, _Keycloak_instances, "m", _Keycloak_loadUserProfile).bind(this);
170
+ /**
171
+ * @private Undocumented.
172
+ */
173
+ this.loadUserInfo = __classPrivateFieldGet(this, _Keycloak_instances, "m", _Keycloak_loadUserInfo).bind(this);
64
174
  const issuerUri = `${params.url.replace(/\/$/, "")}/realms/${params.realm}`;
65
175
  __classPrivateFieldSet(this, _Keycloak_state, {
66
176
  constructorParams: params,
@@ -75,146 +185,6 @@ class Keycloak {
75
185
  $onTokenExpired: (0, StatefulEvt_1.createStatefulEvt)(() => undefined)
76
186
  }, "f");
77
187
  }
78
- /**
79
- * Called to initialize the adapter.
80
- * @param initOptions Initialization options.
81
- * @returns A promise to set functions to be invoked on success or error.
82
- */
83
- async init(initOptions = {}) {
84
- const { onLoad = "check-sso", redirectUri, enableLogging, scope, locale } = initOptions;
85
- if (__classPrivateFieldGet(this, _Keycloak_state, "f").initOptions !== undefined) {
86
- if (JSON.stringify(__classPrivateFieldGet(this, _Keycloak_state, "f").initOptions) !== JSON.stringify(initOptions)) {
87
- throw new Error("Can't call init() multiple time with different params");
88
- }
89
- await __classPrivateFieldGet(this, _Keycloak_state, "f").dInitialized.pr;
90
- const { oidc } = __classPrivateFieldGet(this, _Keycloak_state, "f");
91
- (0, assert_1.assert)(oidc !== undefined);
92
- return oidc.isUserLoggedIn;
93
- }
94
- __classPrivateFieldGet(this, _Keycloak_state, "f").initOptions = initOptions;
95
- const { constructorParams, issuerUri } = __classPrivateFieldGet(this, _Keycloak_state, "f");
96
- const autoLogin = onLoad === "login-required";
97
- let hasCreateResolved = false;
98
- const oidcOrError = await (0, core_1.createOidc)({
99
- BASE_URL: constructorParams.BASE_URL,
100
- sessionRestorationMethod: constructorParams.sessionRestorationMethod,
101
- issuerUri,
102
- clientId: __classPrivateFieldGet(this, _Keycloak_state, "f").constructorParams.clientId,
103
- autoLogin,
104
- postLoginRedirectUrl: redirectUri,
105
- debugLogs: enableLogging,
106
- scopes: scope?.split(" "),
107
- extraQueryParams: !autoLogin || locale === undefined
108
- ? undefined
109
- : () => {
110
- if (hasCreateResolved) {
111
- return {};
112
- }
113
- return {
114
- ui_locales: locale
115
- };
116
- }
117
- })
118
- // NOTE: This can only happen when autoLogin is true, otherwise the error
119
- // is in oidc.initializationError
120
- .catch((error) => error);
121
- hasCreateResolved = true;
122
- if (oidcOrError instanceof core_1.OidcInitializationError) {
123
- this.onAuthError?.({
124
- error: oidcOrError.name,
125
- error_description: oidcOrError.message
126
- });
127
- await new Promise(() => { });
128
- (0, assert_1.assert)(false);
129
- }
130
- const oidc = oidcOrError;
131
- if (oidc.isUserLoggedIn) {
132
- const tokens = await oidc.getTokens();
133
- const onNewToken = (tokens_new) => {
134
- __classPrivateFieldGet(this, _Keycloak_state, "f").tokens = tokens_new;
135
- this.onAuthRefreshSuccess?.();
136
- };
137
- onNewToken(tokens);
138
- oidc.subscribeToTokensChange(onNewToken);
139
- }
140
- __classPrivateFieldGet(this, _Keycloak_state, "f").oidc = oidc;
141
- __classPrivateFieldGet(this, _Keycloak_state, "f").dInitialized.resolve();
142
- this.onReady?.(oidc.isUserLoggedIn);
143
- onAuthSuccess_call: {
144
- if (!oidc.isUserLoggedIn) {
145
- break onAuthSuccess_call;
146
- }
147
- this.onAuthSuccess?.();
148
- }
149
- onAuthError_call: {
150
- if (oidc.isUserLoggedIn) {
151
- break onAuthError_call;
152
- }
153
- if (oidc.initializationError === undefined) {
154
- break onAuthError_call;
155
- }
156
- this.onAuthError?.({
157
- error: oidc.initializationError.name,
158
- error_description: oidc.initializationError.message
159
- });
160
- }
161
- onActionUpdate_call: {
162
- if (!oidc.isUserLoggedIn) {
163
- break onActionUpdate_call;
164
- }
165
- if (this.onActionUpdate === undefined) {
166
- break onActionUpdate_call;
167
- }
168
- const { backFromAuthServer } = oidc;
169
- if (backFromAuthServer === undefined) {
170
- break onActionUpdate_call;
171
- }
172
- const status = backFromAuthServer.result.kc_action_status;
173
- if (!(0, isAmong_1.isAmong)(["success", "cancelled", "error"], status)) {
174
- break onActionUpdate_call;
175
- }
176
- const action = backFromAuthServer.extraQueryParams.kc_action;
177
- if (action === undefined) {
178
- break onActionUpdate_call;
179
- }
180
- this.onActionUpdate(status, action);
181
- }
182
- schedule_onTokenExpired_call: {
183
- if (!oidc.isUserLoggedIn) {
184
- break schedule_onTokenExpired_call;
185
- }
186
- const { $onTokenExpired } = __classPrivateFieldGet(this, _Keycloak_state, "f");
187
- let clear = undefined;
188
- const next = (onTokenExpired) => {
189
- clear?.();
190
- if (onTokenExpired === undefined) {
191
- return;
192
- }
193
- let timer = undefined;
194
- const onNewToken = () => {
195
- if (timer !== undefined) {
196
- worker_timers_1.workerTimers.clearTimeout(timer);
197
- }
198
- const { tokens } = __classPrivateFieldGet(this, _Keycloak_state, "f");
199
- (0, assert_1.assert)(tokens !== undefined);
200
- timer = worker_timers_1.workerTimers.setTimeout(() => {
201
- onTokenExpired.call(this);
202
- }, Math.max(tokens.accessTokenExpirationTime - tokens.getServerDateNow() - 3000, 0));
203
- };
204
- onNewToken();
205
- const { unsubscribe } = oidc.subscribeToTokensChange(onNewToken);
206
- clear = () => {
207
- if (timer !== undefined) {
208
- worker_timers_1.workerTimers.clearTimeout(timer);
209
- }
210
- unsubscribe();
211
- };
212
- };
213
- next($onTokenExpired.current);
214
- $onTokenExpired.subscribe(next);
215
- }
216
- return oidc.isUserLoggedIn;
217
- }
218
188
  /**
219
189
  * Is true if the user is authenticated, false otherwise.
220
190
  */
@@ -517,264 +487,295 @@ class Keycloak {
517
487
  const { $onTokenExpired } = __classPrivateFieldGet(this, _Keycloak_state, "f");
518
488
  return $onTokenExpired.current;
519
489
  }
520
- /**
521
- * Redirects to login form.
522
- * @param options Login options.
523
- */
524
- async login(options) {
525
- const { redirectUri, action, loginHint, acr, acrValues, idpHint, locale, doesCurrentHrefRequiresAuth } = options ?? {};
526
- if (!this.didInitialize) {
527
- await __classPrivateFieldGet(this, _Keycloak_state, "f").dInitialized.pr;
528
- }
529
- const { oidc, keycloakUtils } = __classPrivateFieldGet(this, _Keycloak_state, "f");
490
+ /** Get the underlying oidc-spa instance */
491
+ get oidc() {
492
+ (0, assert_1.assert)(this.didInitialize, "Cannot get keycloak.oidc before the init() method was called and have resolved.");
493
+ const { oidc } = __classPrivateFieldGet(this, _Keycloak_state, "f");
530
494
  (0, assert_1.assert)(oidc !== undefined);
531
- const extraQueryParams_commons = {
532
- claims: acr === undefined
533
- ? undefined
534
- : JSON.stringify({
535
- id_token: {
536
- acr
537
- }
538
- }),
539
- acr_values: acrValues,
540
- ui_locales: locale
541
- };
542
- if (oidc.isUserLoggedIn) {
543
- (0, assert_1.assert)(action !== "register");
544
- (0, assert_1.assert)(loginHint === undefined);
545
- (0, assert_1.assert)(idpHint === undefined);
546
- (0, assert_1.assert)(doesCurrentHrefRequiresAuth === undefined);
547
- await oidc.goToAuthServer({
548
- redirectUrl: redirectUri,
549
- extraQueryParams: {
550
- ...extraQueryParams_commons,
551
- kc_action: action,
552
- ui_locales: locale
553
- }
554
- });
555
- (0, assert_1.assert)(false);
556
- }
557
- (0, assert_1.assert)(action === undefined || action === "register");
558
- await oidc.login({
559
- redirectUrl: redirectUri,
560
- doesCurrentHrefRequiresAuth: doesCurrentHrefRequiresAuth ?? false,
561
- extraQueryParams: {
562
- ...extraQueryParams_commons,
563
- login_hint: loginHint,
564
- kc_idp_hint: idpHint
565
- },
566
- transformUrlBeforeRedirect: action !== "register" ? undefined : keycloakUtils.transformUrlBeforeRedirectForRegister
567
- });
568
- (0, assert_1.assert)(false);
495
+ return oidc;
569
496
  }
570
- /**
571
- * Redirects to logout.
572
- * @param options Logout options.
573
- */
574
- async logout(options) {
575
- if (!this.didInitialize) {
576
- await __classPrivateFieldGet(this, _Keycloak_state, "f").dInitialized.pr;
497
+ }
498
+ exports.Keycloak = Keycloak;
499
+ _Keycloak_state = new WeakMap(), _Keycloak_instances = new WeakSet(), _Keycloak_init = async function _Keycloak_init(initOptions = {}) {
500
+ const { onLoad = "check-sso", redirectUri, enableLogging, scope, locale } = initOptions;
501
+ if (__classPrivateFieldGet(this, _Keycloak_state, "f").initOptions !== undefined) {
502
+ if (JSON.stringify(__classPrivateFieldGet(this, _Keycloak_state, "f").initOptions) !== JSON.stringify(initOptions)) {
503
+ throw new Error("Can't call init() multiple time with different params");
577
504
  }
578
- const { oidc, initOptions } = __classPrivateFieldGet(this, _Keycloak_state, "f");
505
+ await __classPrivateFieldGet(this, _Keycloak_state, "f").dInitialized.pr;
506
+ const { oidc } = __classPrivateFieldGet(this, _Keycloak_state, "f");
579
507
  (0, assert_1.assert)(oidc !== undefined);
580
- (0, assert_1.assert)(initOptions !== undefined);
581
- (0, assert_1.assert)(oidc.isUserLoggedIn, "The user is not currently logged in");
582
- const redirectUri = options?.redirectUri ?? initOptions.redirectUri;
583
- await oidc.logout({
584
- ...(redirectUri === undefined
585
- ? { redirectTo: "current page" }
586
- : { redirectTo: "specific url", url: redirectUri })
587
- });
588
- (0, assert_1.assert)(false);
589
- }
590
- /**
591
- * Redirects to registration form.
592
- * @param options The options used for the registration.
593
- */
594
- async register(options) {
595
- return this.login({
596
- ...options,
597
- action: "register"
598
- });
599
- }
600
- /**
601
- * Redirects to the Account Management Console.
602
- */
603
- async accountManagement(options) {
604
- const { redirectUri, locale } = options ?? {};
605
- window.location.href = this.createAccountUrl({
606
- redirectUri,
607
- locale
608
- });
609
- return new Promise(() => { });
508
+ return oidc.isUserLoggedIn;
610
509
  }
611
- /**
612
- * Returns the URL to login form.
613
- * @param options Supports same options as Keycloak#login.
614
- *
615
- * NOTE oidc-spa: Not supported, please use login() method.
616
- */
617
- //createLoginUrl(options?: KeycloakLoginOptions): Promise<string>;
618
- /**
619
- * Returns the URL to logout the user.
620
- * @param options Logout options.
621
- *
622
- * NOTE oidc-spa: Not supported, please use logout() method.
623
- */
624
- //createLogoutUrl(options?: KeycloakLogoutOptions): string;
625
- /**
626
- * Returns the URL to registration page.
627
- * @param options The options used for creating the registration URL.
628
- *
629
- * NOTE oidc-spa: Not supported please user login({ action: "register" })
630
- */
631
- //createRegisterUrl(options?: KeycloakRegisterOptions): Promise<string>;
632
- /**
633
- * Returns the URL to the Account Management Console.
634
- * @param options The options used for creating the account URL.
635
- */
636
- createAccountUrl(options) {
637
- const { locale, redirectUri } = options ?? {};
638
- const { keycloakUtils, constructorParams } = __classPrivateFieldGet(this, _Keycloak_state, "f");
639
- return keycloakUtils.getAccountUrl({
640
- clientId: this.clientId,
641
- validRedirectUri: (() => {
642
- if (redirectUri !== undefined) {
643
- return redirectUri;
510
+ __classPrivateFieldGet(this, _Keycloak_state, "f").initOptions = initOptions;
511
+ const { constructorParams, issuerUri } = __classPrivateFieldGet(this, _Keycloak_state, "f");
512
+ const autoLogin = onLoad === "login-required";
513
+ let hasCreateResolved = false;
514
+ const oidcOrError = await (0, core_1.createOidc)({
515
+ BASE_URL: constructorParams.BASE_URL,
516
+ sessionRestorationMethod: constructorParams.sessionRestorationMethod,
517
+ issuerUri,
518
+ clientId: __classPrivateFieldGet(this, _Keycloak_state, "f").constructorParams.clientId,
519
+ autoLogin,
520
+ postLoginRedirectUrl: redirectUri,
521
+ debugLogs: enableLogging,
522
+ scopes: scope?.split(" "),
523
+ extraQueryParams: !autoLogin || locale === undefined
524
+ ? undefined
525
+ : () => {
526
+ if (hasCreateResolved) {
527
+ return {};
644
528
  }
645
- const { homeUrlAndRedirectUri } = (0, homeAndRedirectUri_1.getHomeAndRedirectUri)({
646
- BASE_URL_params: constructorParams.BASE_URL
647
- });
648
- return homeUrlAndRedirectUri;
649
- })(),
650
- locale
529
+ return {
530
+ ui_locales: locale
531
+ };
532
+ }
533
+ })
534
+ // NOTE: This can only happen when autoLogin is true, otherwise the error
535
+ // is in oidc.initializationError
536
+ .catch((error) => error);
537
+ hasCreateResolved = true;
538
+ if (oidcOrError instanceof core_1.OidcInitializationError) {
539
+ this.onAuthError?.({
540
+ error: oidcOrError.name,
541
+ error_description: oidcOrError.message
651
542
  });
543
+ await new Promise(() => { });
544
+ (0, assert_1.assert)(false);
652
545
  }
653
- /**
654
- * Returns true if the token has less than `minValidity` seconds left before
655
- * it expires.
656
- * @param minValidity If not specified, `0` is used.
657
- */
658
- isTokenExpired(minValidity = 0) {
659
- let accessTokenExpirationTime;
660
- if (!this.didInitialize) {
661
- const fakeAccessToken = this.token;
662
- if (fakeAccessToken === undefined) {
663
- throw new Error("isTokenExpired was called too early");
664
- }
665
- const time = (0, readExpirationTimeInJwt_1.readExpirationTimeInJwt)(fakeAccessToken);
666
- (0, assert_1.assert)(time !== undefined, "The initial token is not a JWT");
667
- accessTokenExpirationTime = time;
546
+ const oidc = oidcOrError;
547
+ if (oidc.isUserLoggedIn) {
548
+ const tokens = await oidc.getTokens();
549
+ const onNewToken = (tokens_new) => {
550
+ __classPrivateFieldGet(this, _Keycloak_state, "f").tokens = tokens_new;
551
+ this.onAuthRefreshSuccess?.();
552
+ };
553
+ onNewToken(tokens);
554
+ oidc.subscribeToTokensChange(onNewToken);
555
+ }
556
+ __classPrivateFieldGet(this, _Keycloak_state, "f").oidc = oidc;
557
+ __classPrivateFieldGet(this, _Keycloak_state, "f").dInitialized.resolve();
558
+ this.onReady?.(oidc.isUserLoggedIn);
559
+ onAuthSuccess_call: {
560
+ if (!oidc.isUserLoggedIn) {
561
+ break onAuthSuccess_call;
668
562
  }
669
- else {
670
- const { tokens } = __classPrivateFieldGet(this, _Keycloak_state, "f");
671
- (0, assert_1.assert)(tokens !== undefined);
672
- accessTokenExpirationTime = tokens.accessTokenExpirationTime;
563
+ this.onAuthSuccess?.();
564
+ }
565
+ onAuthError_call: {
566
+ if (oidc.isUserLoggedIn) {
567
+ break onAuthError_call;
673
568
  }
674
- if (accessTokenExpirationTime > Date.now() + minValidity * 1000) {
675
- return false;
569
+ if (oidc.initializationError === undefined) {
570
+ break onAuthError_call;
676
571
  }
677
- return true;
572
+ this.onAuthError?.({
573
+ error: oidc.initializationError.name,
574
+ error_description: oidc.initializationError.message
575
+ });
678
576
  }
679
- /**
680
- * If the token expires within `minValidity` seconds, the token is refreshed.
681
- * If the session status iframe is enabled, the session status is also
682
- * checked.
683
- * @param minValidity If not specified, `5` is used.
684
- * @returns A promise to set functions that can be invoked if the token is
685
- * still valid, or if the token is no longer valid.
686
- * @example
687
- * ```js
688
- * keycloak.updateToken(5).then(function(refreshed) {
689
- * if (refreshed) {
690
- * alert('Token was successfully refreshed');
691
- * } else {
692
- * alert('Token is still valid');
693
- * }
694
- * }).catch(function() {
695
- * alert('Failed to refresh the token, or the session has expired');
696
- * });
697
- */
698
- async updateToken(minValidity = 5) {
699
- if (!this.didInitialize) {
700
- await __classPrivateFieldGet(this, _Keycloak_state, "f").dInitialized.pr;
577
+ onActionUpdate_call: {
578
+ if (!oidc.isUserLoggedIn) {
579
+ break onActionUpdate_call;
701
580
  }
702
- const { oidc } = __classPrivateFieldGet(this, _Keycloak_state, "f");
703
- (0, assert_1.assert)(oidc !== undefined);
704
- (0, assert_1.assert)(oidc.isUserLoggedIn, "updateToken called too early");
705
- if (!this.isTokenExpired(minValidity)) {
706
- return false;
581
+ if (this.onActionUpdate === undefined) {
582
+ break onActionUpdate_call;
707
583
  }
708
- await oidc.renewTokens();
709
- return true;
710
- }
711
- /**
712
- * Clears authentication state, including tokens. This can be useful if
713
- * the application has detected the session was expired, for example if
714
- * updating token fails. Invoking this results in Keycloak#onAuthLogout
715
- * callback listener being invoked.
716
- *
717
- * NOTE oidc-spa: In this implementation we never end up in the kind of
718
- * state where calling this makes sense.
719
- * oidc-spa take more control and exposes less complexity to the user of the
720
- * adapter.
721
- */
722
- //clearToken(): void;
723
- /**
724
- * Returns true if the token has the given realm role.
725
- * @param role A realm role name.
726
- */
727
- hasRealmRole(role) {
728
- const access = this.realmAccess;
729
- return access !== undefined && access.roles.indexOf(role) >= 0;
730
- }
731
- /**
732
- * Returns true if the token has the given role for the resource.
733
- * @param role A role name.
734
- * @param resource If not specified, `clientId` is used.
735
- */
736
- hasResourceRole(role, resource) {
737
- if (this.resourceAccess === undefined) {
738
- return false;
584
+ const { backFromAuthServer } = oidc;
585
+ if (backFromAuthServer === undefined) {
586
+ break onActionUpdate_call;
739
587
  }
740
- const access = this.resourceAccess[resource || this.clientId];
741
- return access !== undefined && access.roles.indexOf(role) >= 0;
742
- }
743
- /**
744
- * Loads the user's profile.
745
- * @returns A promise to set functions to be invoked on success or error.
746
- */
747
- async loadUserProfile() {
748
- if (!this.didInitialize) {
749
- await __classPrivateFieldGet(this, _Keycloak_state, "f").dInitialized.pr;
588
+ const status = backFromAuthServer.result.kc_action_status;
589
+ if (!(0, isAmong_1.isAmong)(["success", "cancelled", "error"], status)) {
590
+ break onActionUpdate_call;
750
591
  }
751
- const { oidc, keycloakUtils } = __classPrivateFieldGet(this, _Keycloak_state, "f");
752
- (0, assert_1.assert)(oidc !== undefined);
753
- (0, assert_1.assert)(oidc.isUserLoggedIn, "Can't load userProfile if user not authenticated");
754
- const { accessToken } = await oidc.getTokens();
755
- return (__classPrivateFieldGet(this, _Keycloak_state, "f").profile = await keycloakUtils.fetchUserProfile({ accessToken }));
756
- }
757
- /**
758
- * @private Undocumented.
759
- */
760
- async loadUserInfo() {
761
- if (!this.didInitialize) {
762
- await __classPrivateFieldGet(this, _Keycloak_state, "f").dInitialized.pr;
592
+ const action = backFromAuthServer.extraQueryParams.kc_action;
593
+ if (action === undefined) {
594
+ break onActionUpdate_call;
763
595
  }
764
- const { oidc, keycloakUtils } = __classPrivateFieldGet(this, _Keycloak_state, "f");
765
- (0, assert_1.assert)(oidc !== undefined);
766
- (0, assert_1.assert)(oidc.isUserLoggedIn, "Can't load userInfo if user not authenticated");
767
- const { accessToken } = await oidc.getTokens();
768
- return (__classPrivateFieldGet(this, _Keycloak_state, "f").userInfo = await keycloakUtils.fetchUserInfo({ accessToken }));
596
+ this.onActionUpdate(status, action);
769
597
  }
770
- /** Get the underlying oidc-spa instance */
771
- get oidc() {
772
- (0, assert_1.assert)(this.didInitialize, "Cannot get keycloak.oidc before the init() method was called and have resolved.");
773
- const { oidc } = __classPrivateFieldGet(this, _Keycloak_state, "f");
774
- (0, assert_1.assert)(oidc !== undefined);
775
- return oidc;
598
+ schedule_onTokenExpired_call: {
599
+ if (!oidc.isUserLoggedIn) {
600
+ break schedule_onTokenExpired_call;
601
+ }
602
+ const { $onTokenExpired } = __classPrivateFieldGet(this, _Keycloak_state, "f");
603
+ let clear = undefined;
604
+ const next = (onTokenExpired) => {
605
+ clear?.();
606
+ if (onTokenExpired === undefined) {
607
+ return;
608
+ }
609
+ let timer = undefined;
610
+ const onNewToken = () => {
611
+ if (timer !== undefined) {
612
+ worker_timers_1.workerTimers.clearTimeout(timer);
613
+ }
614
+ const { tokens } = __classPrivateFieldGet(this, _Keycloak_state, "f");
615
+ (0, assert_1.assert)(tokens !== undefined);
616
+ timer = worker_timers_1.workerTimers.setTimeout(() => {
617
+ onTokenExpired.call(this);
618
+ }, Math.max(tokens.accessTokenExpirationTime - tokens.getServerDateNow() - 3000, 0));
619
+ };
620
+ onNewToken();
621
+ const { unsubscribe } = oidc.subscribeToTokensChange(onNewToken);
622
+ clear = () => {
623
+ if (timer !== undefined) {
624
+ worker_timers_1.workerTimers.clearTimeout(timer);
625
+ }
626
+ unsubscribe();
627
+ };
628
+ };
629
+ next($onTokenExpired.current);
630
+ $onTokenExpired.subscribe(next);
631
+ }
632
+ return oidc.isUserLoggedIn;
633
+ }, _Keycloak_login = async function _Keycloak_login(options) {
634
+ const { redirectUri, action, loginHint, acr, acrValues, idpHint, locale, doesCurrentHrefRequiresAuth } = options ?? {};
635
+ if (!this.didInitialize) {
636
+ await __classPrivateFieldGet(this, _Keycloak_state, "f").dInitialized.pr;
637
+ }
638
+ const { oidc, keycloakUtils } = __classPrivateFieldGet(this, _Keycloak_state, "f");
639
+ (0, assert_1.assert)(oidc !== undefined);
640
+ const extraQueryParams_commons = {
641
+ claims: acr === undefined
642
+ ? undefined
643
+ : JSON.stringify({
644
+ id_token: {
645
+ acr
646
+ }
647
+ }),
648
+ acr_values: acrValues,
649
+ ui_locales: locale
650
+ };
651
+ if (oidc.isUserLoggedIn) {
652
+ (0, assert_1.assert)(action !== "register");
653
+ (0, assert_1.assert)(loginHint === undefined);
654
+ (0, assert_1.assert)(idpHint === undefined);
655
+ (0, assert_1.assert)(doesCurrentHrefRequiresAuth === undefined);
656
+ await oidc.goToAuthServer({
657
+ redirectUrl: redirectUri,
658
+ extraQueryParams: {
659
+ ...extraQueryParams_commons,
660
+ kc_action: action,
661
+ ui_locales: locale
662
+ }
663
+ });
664
+ (0, assert_1.assert)(false);
776
665
  }
777
- }
778
- exports.Keycloak = Keycloak;
779
- _Keycloak_state = new WeakMap();
666
+ (0, assert_1.assert)(action === undefined || action === "register");
667
+ await oidc.login({
668
+ redirectUrl: redirectUri,
669
+ doesCurrentHrefRequiresAuth: doesCurrentHrefRequiresAuth ?? false,
670
+ extraQueryParams: {
671
+ ...extraQueryParams_commons,
672
+ login_hint: loginHint,
673
+ kc_idp_hint: idpHint
674
+ },
675
+ transformUrlBeforeRedirect: action !== "register" ? undefined : keycloakUtils.transformUrlBeforeRedirectForRegister
676
+ });
677
+ (0, assert_1.assert)(false);
678
+ }, _Keycloak_logout = async function _Keycloak_logout(options) {
679
+ if (!this.didInitialize) {
680
+ await __classPrivateFieldGet(this, _Keycloak_state, "f").dInitialized.pr;
681
+ }
682
+ const { oidc, initOptions } = __classPrivateFieldGet(this, _Keycloak_state, "f");
683
+ (0, assert_1.assert)(oidc !== undefined);
684
+ (0, assert_1.assert)(initOptions !== undefined);
685
+ (0, assert_1.assert)(oidc.isUserLoggedIn, "The user is not currently logged in");
686
+ const redirectUri = options?.redirectUri ?? initOptions.redirectUri;
687
+ await oidc.logout({
688
+ ...(redirectUri === undefined
689
+ ? { redirectTo: "current page" }
690
+ : { redirectTo: "specific url", url: redirectUri })
691
+ });
692
+ (0, assert_1.assert)(false);
693
+ }, _Keycloak_register = async function _Keycloak_register(options) {
694
+ return this.login({
695
+ ...options,
696
+ action: "register"
697
+ });
698
+ }, _Keycloak_accountManagement = async function _Keycloak_accountManagement(options) {
699
+ const { redirectUri, locale } = options ?? {};
700
+ window.location.href = this.createAccountUrl({
701
+ redirectUri,
702
+ locale
703
+ });
704
+ return new Promise(() => { });
705
+ }, _Keycloak_createAccountUrl = function _Keycloak_createAccountUrl(options) {
706
+ const { locale, redirectUri } = options ?? {};
707
+ const { keycloakUtils, constructorParams } = __classPrivateFieldGet(this, _Keycloak_state, "f");
708
+ return keycloakUtils.getAccountUrl({
709
+ clientId: this.clientId,
710
+ validRedirectUri: (() => {
711
+ if (redirectUri !== undefined) {
712
+ return redirectUri;
713
+ }
714
+ const { homeUrlAndRedirectUri } = (0, homeAndRedirectUri_1.getHomeAndRedirectUri)({
715
+ BASE_URL_params: constructorParams.BASE_URL
716
+ });
717
+ return homeUrlAndRedirectUri;
718
+ })(),
719
+ locale
720
+ });
721
+ }, _Keycloak_isTokenExpired = function _Keycloak_isTokenExpired(minValidity = 0) {
722
+ let accessTokenExpirationTime;
723
+ if (!this.didInitialize) {
724
+ const fakeAccessToken = this.token;
725
+ if (fakeAccessToken === undefined) {
726
+ throw new Error("isTokenExpired was called too early");
727
+ }
728
+ const time = (0, readExpirationTimeInJwt_1.readExpirationTimeInJwt)(fakeAccessToken);
729
+ (0, assert_1.assert)(time !== undefined, "The initial token is not a JWT");
730
+ accessTokenExpirationTime = time;
731
+ }
732
+ else {
733
+ const { tokens } = __classPrivateFieldGet(this, _Keycloak_state, "f");
734
+ (0, assert_1.assert)(tokens !== undefined);
735
+ accessTokenExpirationTime = tokens.accessTokenExpirationTime;
736
+ }
737
+ if (accessTokenExpirationTime > Date.now() + minValidity * 1000) {
738
+ return false;
739
+ }
740
+ return true;
741
+ }, _Keycloak_updateToken = async function _Keycloak_updateToken(minValidity = 5) {
742
+ if (!this.didInitialize) {
743
+ await __classPrivateFieldGet(this, _Keycloak_state, "f").dInitialized.pr;
744
+ }
745
+ const { oidc } = __classPrivateFieldGet(this, _Keycloak_state, "f");
746
+ (0, assert_1.assert)(oidc !== undefined);
747
+ (0, assert_1.assert)(oidc.isUserLoggedIn, "updateToken called too early");
748
+ if (!this.isTokenExpired(minValidity)) {
749
+ return false;
750
+ }
751
+ await oidc.renewTokens();
752
+ return true;
753
+ }, _Keycloak_hasRealmRole = function _Keycloak_hasRealmRole(role) {
754
+ const access = this.realmAccess;
755
+ return access !== undefined && access.roles.indexOf(role) >= 0;
756
+ }, _Keycloak_hasResourceRole = function _Keycloak_hasResourceRole(role, resource) {
757
+ if (this.resourceAccess === undefined) {
758
+ return false;
759
+ }
760
+ const access = this.resourceAccess[resource || this.clientId];
761
+ return access !== undefined && access.roles.indexOf(role) >= 0;
762
+ }, _Keycloak_loadUserProfile = async function _Keycloak_loadUserProfile() {
763
+ if (!this.didInitialize) {
764
+ await __classPrivateFieldGet(this, _Keycloak_state, "f").dInitialized.pr;
765
+ }
766
+ const { oidc, keycloakUtils } = __classPrivateFieldGet(this, _Keycloak_state, "f");
767
+ (0, assert_1.assert)(oidc !== undefined);
768
+ (0, assert_1.assert)(oidc.isUserLoggedIn, "Can't load userProfile if user not authenticated");
769
+ const { accessToken } = await oidc.getTokens();
770
+ return (__classPrivateFieldGet(this, _Keycloak_state, "f").profile = await keycloakUtils.fetchUserProfile({ accessToken }));
771
+ }, _Keycloak_loadUserInfo = async function _Keycloak_loadUserInfo() {
772
+ if (!this.didInitialize) {
773
+ await __classPrivateFieldGet(this, _Keycloak_state, "f").dInitialized.pr;
774
+ }
775
+ const { oidc, keycloakUtils } = __classPrivateFieldGet(this, _Keycloak_state, "f");
776
+ (0, assert_1.assert)(oidc !== undefined);
777
+ (0, assert_1.assert)(oidc.isUserLoggedIn, "Can't load userInfo if user not authenticated");
778
+ const { accessToken } = await oidc.getTokens();
779
+ return (__classPrivateFieldGet(this, _Keycloak_state, "f").userInfo = await keycloakUtils.fetchUserInfo({ accessToken }));
780
+ };
780
781
  //# sourceMappingURL=Keycloak.js.map