asab_webui_shell 27.8.5 → 28.0.0-alpha.3

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 (82) hide show
  1. package/dist/actions.js +15 -15
  2. package/dist/components/branding/BrandImage.js +3 -5
  3. package/dist/components/locationReplace.js +5 -11
  4. package/dist/config/ConfigReducer.js +2 -4
  5. package/dist/config/ConfigService.js +7 -10
  6. package/dist/containers/Alerts/index.js +34 -45
  7. package/dist/containers/Alerts/reducer.js +19 -20
  8. package/dist/containers/Application.js +200 -207
  9. package/dist/containers/FullscreenMode/reducer.js +5 -10
  10. package/dist/containers/Header/ApplicationScreenTitle/ApplicationScreenTitle.js +27 -32
  11. package/dist/containers/Header/ApplicationScreenTitle/index.js +8 -10
  12. package/dist/containers/Header/Help/HelpButton.js +58 -55
  13. package/dist/containers/Header/Help/HelpService.js +3 -4
  14. package/dist/containers/Header/index.js +23 -23
  15. package/dist/containers/Header/reducer.js +13 -15
  16. package/dist/containers/Navigation/index.js +4 -6
  17. package/dist/containers/Navigation/reducer.js +7 -11
  18. package/dist/containers/RouteErrorHandler/ErrorContainer.js +47 -31
  19. package/dist/containers/RouteErrorHandler/index.js +26 -27
  20. package/dist/containers/Router/ApplicationHashRouter.js +7 -8
  21. package/dist/containers/Router/ApplicationRouter.js +38 -38
  22. package/dist/containers/Router/index.js +2 -4
  23. package/dist/containers/Router/reducer.js +7 -11
  24. package/dist/containers/Sidebar/NavbarBrand.js +30 -38
  25. package/dist/containers/Sidebar/SidebarBottomItem.js +42 -36
  26. package/dist/containers/Sidebar/SidebarIcon.js +12 -9
  27. package/dist/containers/Sidebar/SidebarItem.js +135 -132
  28. package/dist/containers/Sidebar/SidebarItemRenderer.js +25 -26
  29. package/dist/containers/Sidebar/index.js +55 -70
  30. package/dist/containers/Sidebar/reducer.js +7 -11
  31. package/dist/containers/Sidebar/utils/sidebarRouteMatch.js +12 -15
  32. package/dist/containers/Sidepanel/Sidepanel.js +35 -40
  33. package/dist/containers/Toast/ToastComponent.js +21 -15
  34. package/dist/containers/Toast/ToastContainer.js +23 -32
  35. package/dist/containers/Toast/reducer.js +14 -16
  36. package/dist/index.js +10 -10
  37. package/dist/modules/about/AboutScreen.js +80 -65
  38. package/dist/modules/about/index.js +3 -3
  39. package/dist/modules/attentionrequired/attentionRequiredReducer.js +5 -10
  40. package/dist/modules/attentionrequired/components/OfflineIndication.js +9 -7
  41. package/dist/modules/attentionrequired/connectivityReducer.js +5 -10
  42. package/dist/modules/attentionrequired/index.js +2 -3
  43. package/dist/modules/attentionrequired/service.js +21 -24
  44. package/dist/modules/auth/actions.js +1 -1
  45. package/dist/modules/auth/api.js +53 -61
  46. package/dist/modules/auth/components/LoginLoopCard.js +24 -15
  47. package/dist/modules/auth/components/SessionExpirationAlert.js +26 -18
  48. package/dist/modules/auth/header.js +69 -62
  49. package/dist/modules/auth/index.js +418 -458
  50. package/dist/modules/auth/reducer.js +11 -14
  51. package/dist/modules/auth/screens/AccessControlScreen.js +71 -50
  52. package/dist/modules/i18n/actions.js +1 -1
  53. package/dist/modules/i18n/dropdown.js +52 -46
  54. package/dist/modules/i18n/escapeHtmlMinimal.js +2 -2
  55. package/dist/modules/i18n/index.js +2 -2
  56. package/dist/modules/i18n/reducer.js +5 -10
  57. package/dist/modules/i18n/service.js +52 -73
  58. package/dist/modules/invite/InvitationScreen.js +162 -138
  59. package/dist/modules/invite/index.js +5 -4
  60. package/dist/modules/tenant/TenantDropdown.js +52 -58
  61. package/dist/modules/tenant/access/AccessDeniedCard.js +52 -52
  62. package/dist/modules/tenant/actions.js +1 -1
  63. package/dist/modules/tenant/index.js +2 -2
  64. package/dist/modules/tenant/reducer.js +2 -4
  65. package/dist/modules/tenant/service.js +74 -91
  66. package/dist/screens/InvalidRouteScreen.js +30 -20
  67. package/dist/screens/SuspenseScreen.js +26 -24
  68. package/dist/screens/UnauthorizedAccessScreen.js +44 -33
  69. package/dist/screens/UnsupportedBrowserScreen.js +44 -38
  70. package/dist/services/BrandingService.js +16 -24
  71. package/dist/services/HeaderService.js +4 -7
  72. package/dist/services/TitleService.js +19 -20
  73. package/dist/theme/ThemeButton.js +18 -14
  74. package/dist/theme/ThemeReducer.js +3 -5
  75. package/dist/theme/ThemeService.js +6 -8
  76. package/dist/theme/actions.js +1 -1
  77. package/dist/utils/browserSupport.js +18 -23
  78. package/dist/utils/extractTenantFromUrl.js +3 -3
  79. package/dist/utils/jsonParseWithBigInt.js +10 -9
  80. package/dist/utils/pageLifecycle.js +5 -5
  81. package/dist/utils/statusAlerts.js +1 -1
  82. package/package.json +13 -13
@@ -1,12 +1,13 @@
1
1
  "use strict";
2
2
 
3
- var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
3
+ var _interopRequireWildcard3 = require("@babel/runtime/helpers/interopRequireWildcard").default;
4
+ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
4
5
  Object.defineProperty(exports, "__esModule", {
5
6
  value: true
6
7
  });
7
8
  exports.default = void 0;
8
- var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));
9
- var _react = _interopRequireWildcard(require("react"));
9
+ var _interopRequireWildcard2 = _interopRequireDefault(require("@babel/runtime/helpers/interopRequireWildcard"));
10
+ var _react = _interopRequireWildcard3(require("react"));
10
11
  var _asab_webui_components = require("asab_webui_components");
11
12
  var _header = require("./header");
12
13
  var _reducer = _interopRequireDefault(require("./reducer"));
@@ -16,9 +17,10 @@ var _api = require("./api");
16
17
  var _locationReplace = require("../../components/locationReplace");
17
18
  var _extractTenantFromUrl = require("../../utils/extractTenantFromUrl");
18
19
  var _SessionExpirationAlert = require("./components/SessionExpirationAlert");
19
- var cache;
20
- function _interopRequireWildcard(e, t) { if (!t && e && e.__esModule) return e; var r, c, a = Object.defineProperty, n = { __proto__: null, default: e }; if (Object(e) !== e) return n; if (cache || "function" != typeof WeakMap || (cache = new WeakMap()), cache) { if (cache.has(e)) return cache.get(e); cache.set(e, n); } for (c in e) "default" !== c && {}.hasOwnProperty.call(e, c) && ((r = a && Object.getOwnPropertyDescriptor(e, c)) && (r.get || r.set) ? a(n, c, r) : n[c] = e[c]); return n; } // TODO: Use SessionExpirationAlert only after proper fix of the component
21
- var AccessControlScreen = /*#__PURE__*/(0, _react.lazy)(() => Promise.resolve().then(() => _interopRequireWildcard(require("./screens/AccessControlScreen"))));
20
+ var _jsxRuntime = require("react/jsx-runtime");
21
+ // TODO: Use SessionExpirationAlert only after proper fix of the component
22
+
23
+ const AccessControlScreen = /*#__PURE__*/(0, _react.lazy)(() => Promise.resolve().then(() => (0, _interopRequireWildcard2.default)(require("./screens/AccessControlScreen"))));
22
24
  class AuthModule extends _asab_webui_components.Module {
23
25
  constructor(app, name) {
24
26
  super(app, "AuthModule");
@@ -52,7 +54,7 @@ class AuthModule extends _asab_webui_components.Module {
52
54
  this._unsubscribeLifecycle = null; // Unsubscribe function for the Application.lifecycle! subscription (set by _markAuthPageActive)
53
55
 
54
56
  // Login-loop protection counts consecutive login redirects and resets on auth success
55
- var _n = parseInt(sessionStorage.getItem('SeaCatLoginAttempts') || '0', 10);
57
+ const _n = parseInt(sessionStorage.getItem('SeaCatLoginAttempts') || '0', 10);
56
58
  this._loginAttempts = Number.isFinite(_n) ? _n : 0;
57
59
 
58
60
  // Access control screen
@@ -64,161 +66,157 @@ class AuthModule extends _asab_webui_components.Module {
64
66
  resource: "*"
65
67
  });
66
68
  }
67
- initialize() {
68
- var _this = this;
69
- return (0, _asyncToGenerator2.default)(function* () {
70
- var headerService = _this.App.locateService("HeaderService");
71
- headerService.addComponent({
72
- component: _header.AuthHeaderDropdown,
73
- componentProps: {
74
- AuthModule: _this
75
- },
76
- order: 700
77
- });
78
- if (typeof MOCK_USERINFO !== 'undefined') {
79
- /* This section is only for DEV purposes! */
80
- yield _this.simulateUserinfo(MOCK_USERINFO);
81
- /* End of DEV section */
82
- } else {
83
- // Check the query string for 'code'
84
- var qs = new URLSearchParams(window.location.search);
85
- var authorization_code = qs.get('code');
86
-
87
- // Checking error type in params
88
- var errorType = qs.get('error');
89
- if (errorType != undefined && errorType != 'tenant_access_denied') {
90
- /*
91
- If error appears in the URL search params and is NOT
92
- tenant_access_denied, user will stay in splashscreen
93
- with Access denied card
94
- */
95
- return;
96
- }
69
+ async initialize() {
70
+ const headerService = this.App.locateService("HeaderService");
71
+ headerService.addComponent({
72
+ component: _header.AuthHeaderDropdown,
73
+ componentProps: {
74
+ AuthModule: this
75
+ },
76
+ order: 700
77
+ });
78
+ if (typeof MOCK_USERINFO !== 'undefined') {
79
+ /* This section is only for DEV purposes! */
80
+ await this.simulateUserinfo(MOCK_USERINFO);
81
+ /* End of DEV section */
82
+ } else {
83
+ // Check the query string for 'code'
84
+ var qs = new URLSearchParams(window.location.search);
85
+ const authorization_code = qs.get('code');
97
86
 
87
+ // Checking error type in params
88
+ const errorType = qs.get('error');
89
+ if (errorType != undefined && errorType != 'tenant_access_denied') {
98
90
  /*
99
- Duplicated tabs clone sessionStorage and SeaCatAuthTabActive is set
100
- while the tab is live and cleared on pagehide (refresh/close).
101
- If the flag (SeaCatAuthTabActive) is still present at startup,
102
- then its evaluated as a clone and it drops tokens and re-authenticate.
103
- Skipping the evaluation during the OAuth `code` redirect
91
+ If error appears in the URL search params and is NOT
92
+ tenant_access_denied, user will stay in splashscreen
93
+ with Access denied card
104
94
  */
105
- if (authorization_code === null && _this.OAuthTokens != null && sessionStorage.getItem('SeaCatAuthTabActive')) {
106
- _this.OAuthTokens = null;
95
+ return;
96
+ }
97
+
98
+ /*
99
+ Duplicated tabs clone sessionStorage and SeaCatAuthTabActive is set
100
+ while the tab is live and cleared on pagehide (refresh/close).
101
+ If the flag (SeaCatAuthTabActive) is still present at startup,
102
+ then its evaluated as a clone and it drops tokens and re-authenticate.
103
+ Skipping the evaluation during the OAuth `code` redirect
104
+ */
105
+ if (authorization_code === null && this.OAuthTokens != null && sessionStorage.getItem('SeaCatAuthTabActive')) {
106
+ this.OAuthTokens = null;
107
+ sessionStorage.removeItem('SeaCatOAuth2Tokens');
108
+ sessionStorage.removeItem('SeaCatAuthTabActive');
109
+ await this._attemptLogin(this.RedirectURL, false);
110
+ return;
111
+ }
112
+ if (authorization_code !== null) {
113
+ await this._exchangeCodeForTokens(authorization_code);
114
+ // Remove 'code' from a query string
115
+ qs.delete('code');
116
+ const stateIndex = qs.get("state");
117
+ let state = "";
118
+ // Check if stateIndex is present, eventually return empty state string
119
+ if (stateIndex != undefined) {
120
+ // Check if oauth2_state_ is present, eventually return empty string
121
+ if (localStorage.getItem(`oauth2_state_${stateIndex}`) != undefined) {
122
+ state = localStorage.getItem(`oauth2_state_${stateIndex}`);
123
+ }
124
+ }
125
+ localStorage.removeItem(`oauth2_state_${stateIndex}`);
126
+
127
+ // Remove 'state' from a query string
128
+ qs.delete("state");
129
+
130
+ // Construct the new URL without `code` in the query string
131
+ // For this case, condition on empty qs string is sufficient and tested
132
+ let reloadUrl;
133
+ if (qs.toString() == '') {
134
+ // Remove `?` part from URL completely, if empty
135
+ reloadUrl = window.location.pathname + state; // part form localstorage instead of hash
136
+ } else {
137
+ reloadUrl = window.location.pathname + '?' + qs.toString() + state; // part form localstorage instead of hash
138
+ }
139
+
140
+ // Reload the app with `code` removed
141
+ await (0, _locationReplace.locationReplace)(reloadUrl);
142
+ }
143
+
144
+ // Do we have an oauth token (we are authorized to use the app)
145
+ if (this.OAuthTokens != null) {
146
+ // Update the user info
147
+ let result = await this.updateUserInfo();
148
+ if (!result) {
149
+ // User info not found - go to login
107
150
  sessionStorage.removeItem('SeaCatOAuth2Tokens');
108
151
  sessionStorage.removeItem('SeaCatAuthTabActive');
109
- yield _this._attemptLogin(_this.RedirectURL, false);
152
+ let force_login_prompt = false;
153
+ await this._attemptLogin(this.RedirectURL, force_login_prompt);
110
154
  return;
111
155
  }
112
- if (authorization_code !== null) {
113
- yield _this._exchangeCodeForTokens(authorization_code);
114
- // Remove 'code' from a query string
115
- qs.delete('code');
116
- var stateIndex = qs.get("state");
117
- var state = "";
118
- // Check if stateIndex is present, eventually return empty state string
119
- if (stateIndex != undefined) {
120
- // Check if oauth2_state_ is present, eventually return empty string
121
- if (localStorage.getItem("oauth2_state_".concat(stateIndex)) != undefined) {
122
- state = localStorage.getItem("oauth2_state_".concat(stateIndex));
123
- }
124
- }
125
- localStorage.removeItem("oauth2_state_".concat(stateIndex));
126
-
127
- // Remove 'state' from a query string
128
- qs.delete("state");
129
-
130
- // Construct the new URL without `code` in the query string
131
- // For this case, condition on empty qs string is sufficient and tested
132
- var reloadUrl;
133
- if (qs.toString() == '') {
134
- // Remove `?` part from URL completely, if empty
135
- reloadUrl = window.location.pathname + state; // part form localstorage instead of hash
136
- } else {
137
- reloadUrl = window.location.pathname + '?' + qs.toString() + state; // part form localstorage instead of hash
138
- }
139
-
140
- // Reload the app with `code` removed
141
- yield (0, _locationReplace.locationReplace)(reloadUrl);
142
- }
143
156
 
144
- // Do we have an oauth token (we are authorized to use the app)
145
- if (_this.OAuthTokens != null) {
146
- // Update the user info
147
- var result = yield _this.updateUserInfo();
148
- if (!result) {
149
- // User info not found - go to login
150
- sessionStorage.removeItem('SeaCatOAuth2Tokens');
151
- sessionStorage.removeItem('SeaCatAuthTabActive');
152
- var force_login_prompt = false;
153
- yield _this._attemptLogin(_this.RedirectURL, force_login_prompt);
157
+ // Mark current tab as holding an active auth session
158
+ this._markAuthPageActive();
159
+
160
+ // Add interceptor with Bearer token in the Header into axios calls
161
+ this.App.addAxiosInterceptor(this.authInterceptor());
162
+ // Add response error interceptor to handle 401 Unauthorized globally
163
+ this.App.addAxiosResponseErrorInterceptor(this.unauthorizedInterceptor());
164
+ // Add webSocket interceptor with Bearer token into websocket calls
165
+ this.App.addWebSocketInterceptor(this.webSocketAuthInterceptor());
166
+
167
+ // Authorization of the user based on tenant access
168
+ if (this.App.Config.get("authorization") !== "disabled" && this.App.Services.TenantService) {
169
+ // Tenant access validation
170
+ let tenantAuthorized = this.validateTenant();
171
+ if (!tenantAuthorized) {
172
+ // If tenant not authorized, redirect to Access denied card
173
+ let force_login_prompt = false;
174
+ await this._attemptLogin(this.RedirectURL, force_login_prompt);
154
175
  return;
155
176
  }
177
+ }
156
178
 
157
- // Mark current tab as holding an active auth session
158
- _this._markAuthPageActive();
159
-
160
- // Add interceptor with Bearer token in the Header into axios calls
161
- _this.App.addAxiosInterceptor(_this.authInterceptor());
162
- // Add response error interceptor to handle 401 Unauthorized globally
163
- _this.App.addAxiosResponseErrorInterceptor(_this.unauthorizedInterceptor());
164
- // Add webSocket interceptor with Bearer token into websocket calls
165
- _this.App.addWebSocketInterceptor(_this.webSocketAuthInterceptor());
166
-
167
- // Authorization of the user based on tenant access
168
- if (_this.App.Config.get("authorization") !== "disabled" && _this.App.Services.TenantService) {
169
- // Tenant access validation
170
- var tenantAuthorized = _this.validateTenant();
171
- if (!tenantAuthorized) {
172
- // If tenant not authorized, redirect to Access denied card
173
- var _force_login_prompt = false;
174
- yield _this._attemptLogin(_this.RedirectURL, _force_login_prompt);
175
- return;
176
- }
177
- }
178
-
179
- // Validate resources of items and children in navigation (resource validation depends on tenant)
180
- if (_this.App.AppStore && _this.App.Services.TenantService && _this.UserInfo !== null) {
181
- var _this$App, _this$App$dispatch;
182
- var currentTenant = _this.App.Services.TenantService.getCurrentTenant();
183
- var resources = _this.UserInfo.resources ? _this.UserInfo.resources[currentTenant] : [];
184
- /*
185
- When switching between tenants,
186
- we need to force authorization to obtain
187
- correct data (resources) for particular
188
- tenant (this is unavailable until auth token is updated)
189
- */
190
- if (resources == undefined) {
191
- var _force_login_prompt2 = false;
192
- yield _this._attemptLogin(_this.RedirectURL, _force_login_prompt2);
193
- return;
194
- }
195
- (_this$App = _this.App) === null || _this$App === void 0 || (_this$App = _this$App.AppStore) === null || _this$App === void 0 || (_this$App$dispatch = _this$App.dispatch) === null || _this$App$dispatch === void 0 || _this$App$dispatch.call(_this$App, {
196
- type: _actions.types.AUTH_RESOURCES,
197
- resources: resources
198
- });
199
- _this.validateNavigation({
200
- resources
201
- });
202
- }
203
- if (_this.UserInfo != null) {
204
- yield _this._startSessionExpirationValidation(); // Start session validation
179
+ // Validate resources of items and children in navigation (resource validation depends on tenant)
180
+ if (this.App.AppStore && this.App.Services.TenantService && this.UserInfo !== null) {
181
+ let currentTenant = this.App.Services.TenantService.getCurrentTenant();
182
+ let resources = this.UserInfo.resources ? this.UserInfo.resources[currentTenant] : [];
183
+ /*
184
+ When switching between tenants,
185
+ we need to force authorization to obtain
186
+ correct data (resources) for particular
187
+ tenant (this is unavailable until auth token is updated)
188
+ */
189
+ if (resources == undefined) {
190
+ let force_login_prompt = false;
191
+ await this._attemptLogin(this.RedirectURL, force_login_prompt);
192
+ return;
205
193
  }
194
+ this.App?.AppStore?.dispatch?.({
195
+ type: _actions.types.AUTH_RESOURCES,
196
+ resources: resources
197
+ });
198
+ this.validateNavigation({
199
+ resources
200
+ });
206
201
  }
207
- if (_this.UserInfo == null && _this.MustAuthenticate) {
208
- var _force_login_prompt3 = false;
209
- yield _this._attemptLogin(_this.RedirectURL, _force_login_prompt3);
210
- return;
202
+ if (this.UserInfo != null) {
203
+ await this._startSessionExpirationValidation(); // Start session validation
211
204
  }
212
205
  }
206
+ if (this.UserInfo == null && this.MustAuthenticate) {
207
+ let force_login_prompt = false;
208
+ await this._attemptLogin(this.RedirectURL, force_login_prompt);
209
+ return;
210
+ }
211
+ }
213
212
 
214
- // Authorization completed successfully so reset the login-loop counter
215
- _this._loginAttempts = 0;
216
- sessionStorage.removeItem('SeaCatLoginAttempts');
217
- _this.App.removeSplashScreenRequestor(_this);
218
- })();
213
+ // Authorization completed successfully so reset the login-loop counter
214
+ this._loginAttempts = 0;
215
+ sessionStorage.removeItem('SeaCatLoginAttempts');
216
+ this.App.removeSplashScreenRequestor(this);
219
217
  }
220
218
  authInterceptor() {
221
- var interceptor = config => {
219
+ const interceptor = config => {
222
220
  config.headers['Authorization'] = 'Bearer ' + this.OAuthTokens['access_token'];
223
221
  return config;
224
222
  };
@@ -227,97 +225,87 @@ class AuthModule extends _asab_webui_components.Module {
227
225
 
228
226
  // Handle 401 Unauthorized responses from the server
229
227
  unauthorizedInterceptor() {
230
- var _this2 = this;
231
- return /*#__PURE__*/function () {
232
- var _ref = (0, _asyncToGenerator2.default)(function* (error) {
233
- var _error$response, _error$config, _error$config2, _error$config3, _error$config3$get, _this2$OAuthTokens;
234
- if ((error === null || error === void 0 || (_error$response = error.response) === null || _error$response === void 0 ? void 0 : _error$response.status) !== 401) return;
235
-
236
- // If session expired, do not continue
237
- if (_this2._sessionExpired) return;
238
-
239
- // Ignore 401s from auth endpoints themselves to avoid loops
240
- var requestBaseURL = error === null || error === void 0 || (_error$config = error.config) === null || _error$config === void 0 ? void 0 : _error$config.baseURL;
241
- var requestPath = error === null || error === void 0 || (_error$config2 = error.config) === null || _error$config2 === void 0 ? void 0 : _error$config2.url;
242
- var oidcURL = _this2.App.getServiceURL('openidconnect');
243
- var seacatAuthURL = _this2.App.getServiceURL('seacat-auth');
244
- // Ignore 401 requests from the oidc service (token/userinfo endpoints) to avoid refresh loops
245
- // For seacat-auth, only ignore the internal /openidconnect/* sub-path (used by the internal userinfo call)
246
- if (requestBaseURL && (requestBaseURL === oidcURL || requestBaseURL === seacatAuthURL && (requestPath === '/openidconnect' || requestPath !== null && requestPath !== void 0 && requestPath.startsWith('/openidconnect/')))) {
247
- return;
248
- }
228
+ return async error => {
229
+ if (error?.response?.status !== 401) return;
230
+
231
+ // If session expired, do not continue
232
+ if (this._sessionExpired) return;
233
+
234
+ // Ignore 401s from auth endpoints themselves to avoid loops
235
+ const requestBaseURL = error?.config?.baseURL;
236
+ const requestPath = error?.config?.url;
237
+ const oidcURL = this.App.getServiceURL('openidconnect');
238
+ const seacatAuthURL = this.App.getServiceURL('seacat-auth');
239
+ // Ignore 401 requests from the oidc service (token/userinfo endpoints) to avoid refresh loops
240
+ // For seacat-auth, only ignore the internal /openidconnect/* sub-path (used by the internal userinfo call)
241
+ if (requestBaseURL && (requestBaseURL === oidcURL || requestBaseURL === seacatAuthURL && (requestPath === '/openidconnect' || requestPath?.startsWith('/openidconnect/')))) {
242
+ return;
243
+ }
249
244
 
250
- // Each refresh invalidates the previous access token server-side, so only a 401 for the current token can mean an invalid session
251
- if ((error === null || error === void 0 || (_error$config3 = error.config) === null || _error$config3 === void 0 || (_error$config3 = _error$config3.headers) === null || _error$config3 === void 0 || (_error$config3$get = _error$config3.get) === null || _error$config3$get === void 0 ? void 0 : _error$config3$get.call(_error$config3, 'Authorization')) !== "Bearer ".concat((_this2$OAuthTokens = _this2.OAuthTokens) === null || _this2$OAuthTokens === void 0 ? void 0 : _this2$OAuthTokens.access_token)) {
252
- return;
253
- }
245
+ // Each refresh invalidates the previous access token server-side, so only a 401 for the current token can mean an invalid session
246
+ if (error?.config?.headers?.get?.('Authorization') !== `Bearer ${this.OAuthTokens?.access_token}`) {
247
+ return;
248
+ }
254
249
 
255
- // Await so sessionExpired is set before callers reach addAlertFromException
256
- var _yield$_this2$_renewS = yield _this2._renewSession(),
257
- userInfoUpdated = _yield$_this2$_renewS.userInfoUpdated;
258
- if (userInfoUpdated === false) {
259
- _this2._triggerSessionExpired();
260
- }
261
- });
262
- return function (_x) {
263
- return _ref.apply(this, arguments);
264
- };
265
- }();
250
+ // Await so sessionExpired is set before callers reach addAlertFromException
251
+ const {
252
+ userInfoUpdated
253
+ } = await this._renewSession();
254
+ if (userInfoUpdated === false) {
255
+ this._triggerSessionExpired();
256
+ }
257
+ };
266
258
  }
267
259
  webSocketAuthInterceptor() {
268
260
  // Return a function to ensure that the token is always current and not static
269
- return () => "access_token_".concat(this.OAuthTokens['access_token']);
261
+ return () => `access_token_${this.OAuthTokens['access_token']}`;
270
262
  }
271
- simulateUserinfo(mock_userinfo) {
272
- var _this3 = this;
273
- return (0, _asyncToGenerator2.default)(function* () {
274
- /*
275
- This method takes parameters from wepack.dev.js settings
276
- plugins: [
277
- ...
278
- new webpack.DefinePlugin({
279
- 'MOCK_USERINFO': JSON.stringify({ // Inject mocked UserInfo object, this means the application will NOT require user authorization
280
- "username": "johndev",
281
- "email": "dev@dev.de",
282
- "phone": "123456789",
283
- "resources": ["authz:superuser"],
284
- "roles": ["default/Admin"],
285
- "sub": "devdb:dev:1abc2def3456",
286
- "tenants": ["default"]
287
- })
288
- }),
289
- ...
290
- ],
291
- */
292
- _this3.App.addAlert("warning", "ASABAuthModule|You are using MOCK_USERINFO!", 1, true);
293
- var mockParams = mock_userinfo;
294
- if (mockParams.resources) {
295
- mockParams["resources"] = Object.values(mockParams.resources);
296
- }
297
- if (mockParams.roles) {
298
- mockParams["roles"] = Object.values(mockParams.roles);
299
- }
300
- if (mockParams.tenants) {
301
- mockParams["tenants"] = Object.values(mockParams.tenants);
302
- }
303
- if (_this3.App.AppStore) {
304
- var _this3$App$AppStore$d, _this3$App$AppStore, _this3$App$AppStore$d2, _this3$App$AppStore2;
305
- (_this3$App$AppStore$d = (_this3$App$AppStore = _this3.App.AppStore).dispatch) === null || _this3$App$AppStore$d === void 0 || _this3$App$AppStore$d.call(_this3$App$AppStore, {
306
- type: _actions.types.AUTH_USERINFO,
307
- payload: mockParams
308
- });
309
- (_this3$App$AppStore$d2 = (_this3$App$AppStore2 = _this3.App.AppStore).dispatch) === null || _this3$App$AppStore$d2 === void 0 || _this3$App$AppStore$d2.call(_this3$App$AppStore2, {
310
- type: _actions.types.AUTH_RESOURCES,
311
- resources: mockParams["resources"]
312
- });
313
- }
263
+ async simulateUserinfo(mock_userinfo) {
264
+ /*
265
+ This method takes parameters from wepack.dev.js settings
266
+ plugins: [
267
+ ...
268
+ new webpack.DefinePlugin({
269
+ 'MOCK_USERINFO': JSON.stringify({ // Inject mocked UserInfo object, this means the application will NOT require user authorization
270
+ "username": "johndev",
271
+ "email": "dev@dev.de",
272
+ "phone": "123456789",
273
+ "resources": ["authz:superuser"],
274
+ "roles": ["default/Admin"],
275
+ "sub": "devdb:dev:1abc2def3456",
276
+ "tenants": ["default"]
277
+ })
278
+ }),
279
+ ...
280
+ ],
281
+ */
282
+ this.App.addAlert("warning", "ASABAuthModule|You are using MOCK_USERINFO!", 1, true);
283
+ let mockParams = mock_userinfo;
284
+ if (mockParams.resources) {
285
+ mockParams["resources"] = Object.values(mockParams.resources);
286
+ }
287
+ if (mockParams.roles) {
288
+ mockParams["roles"] = Object.values(mockParams.roles);
289
+ }
290
+ if (mockParams.tenants) {
291
+ mockParams["tenants"] = Object.values(mockParams.tenants);
292
+ }
293
+ if (this.App.AppStore) {
294
+ this.App.AppStore.dispatch?.({
295
+ type: _actions.types.AUTH_USERINFO,
296
+ payload: mockParams
297
+ });
298
+ this.App.AppStore.dispatch?.({
299
+ type: _actions.types.AUTH_RESOURCES,
300
+ resources: mockParams["resources"]
301
+ });
302
+ }
314
303
 
315
- /** Check for TenantService and pass tenants list obtained from userinfo */
316
- var availableTenants = mockParams.tenants;
317
- if (_this3.App.Services.TenantService) {
318
- yield _this3.App.Services.TenantService.setTenants(availableTenants, _this3._getAuthorizedTenant(mockParams));
319
- }
320
- })();
304
+ /** Check for TenantService and pass tenants list obtained from userinfo */
305
+ let availableTenants = mockParams.tenants;
306
+ if (this.App.Services.TenantService) {
307
+ await this.App.Services.TenantService.setTenants(availableTenants, this._getAuthorizedTenant(mockParams));
308
+ }
321
309
  }
322
310
  logout() {
323
311
  this.App.addSplashScreenRequestor(this);
@@ -328,7 +316,7 @@ class AuthModule extends _asab_webui_components.Module {
328
316
  sessionStorage.removeItem('SeaCatLoginAttempts');
329
317
  sessionStorage.removeItem('SeaCatOAuth2Tokens');
330
318
  sessionStorage.removeItem('SeaCatAuthTabActive');
331
- var promise = this.Api.logout(this.OAuthTokens['access_token']);
319
+ const promise = this.Api.logout(this.OAuthTokens['access_token']);
332
320
  if (promise == null) {
333
321
  window.location.reload();
334
322
  }
@@ -338,12 +326,12 @@ class AuthModule extends _asab_webui_components.Module {
338
326
  window.location.reload();
339
327
  });
340
328
  }
341
- validateNavigation(_ref2) {
342
- var _state$navigation, _this$App$AppStore$di, _this$App$AppStore;
343
- var resources = _ref2.resources;
344
- var state = this.App.AppStore.getState();
345
- var navItems = (_state$navigation = state.navigation) === null || _state$navigation === void 0 ? void 0 : _state$navigation.navItems;
346
- var authorizedNavItems = [];
329
+ validateNavigation({
330
+ resources
331
+ }) {
332
+ const state = this.App.AppStore.getState();
333
+ let navItems = state.navigation?.navItems;
334
+ let authorizedNavItems = [];
347
335
  navItems && navItems.map((itm, idx) => {
348
336
  if (resources.indexOf('authz:superuser') !== -1) {
349
337
  // If user is superuser, validate every navigation item
@@ -354,7 +342,7 @@ class AuthModule extends _asab_webui_components.Module {
354
342
  itm.children = this._validateChildrenNav(itm, resources);
355
343
  }
356
344
  // Item validation
357
- var access_auth = this._validateItemNav(itm.resource, resources);
345
+ let access_auth = this._validateItemNav(itm.resource, resources);
358
346
  if (access_auth == true) {
359
347
  authorizedNavItems.push(itm);
360
348
  }
@@ -368,7 +356,7 @@ class AuthModule extends _asab_webui_components.Module {
368
356
  }
369
357
  }
370
358
  });
371
- (_this$App$AppStore$di = (_this$App$AppStore = this.App.AppStore).dispatch) === null || _this$App$AppStore$di === void 0 || _this$App$AppStore$di.call(_this$App$AppStore, {
359
+ this.App.AppStore.dispatch?.({
372
360
  type: _actions2.SET_NAVIGATION_ITEMS,
373
361
  navItems: authorizedNavItems
374
362
  });
@@ -377,10 +365,10 @@ class AuthModule extends _asab_webui_components.Module {
377
365
  // Validate sidebar's item children
378
366
  _validateChildrenNav(itm, resources) {
379
367
  // Item's children validation
380
- var authorizedNavChildren = [];
368
+ let authorizedNavChildren = [];
381
369
  itm.children.map((child, id) => {
382
370
  if (child.resource) {
383
- var access_auth = this._validateItemNav(child.resource, resources);
371
+ let access_auth = this._validateItemNav(child.resource, resources);
384
372
  if (access_auth == true) {
385
373
  authorizedNavChildren.push(child);
386
374
  }
@@ -391,7 +379,7 @@ class AuthModule extends _asab_webui_components.Module {
391
379
 
392
380
  // Validate sidebar items
393
381
  _validateItemNav(resource, resources) {
394
- var valid = resources ? resources.indexOf(resource) !== -1 : false;
382
+ let valid = resources ? resources.indexOf(resource) !== -1 : false;
395
383
  // If user is superuser, then item is enabled
396
384
  if (resources.indexOf('authz:superuser') !== -1) {
397
385
  valid = true;
@@ -401,19 +389,18 @@ class AuthModule extends _asab_webui_components.Module {
401
389
 
402
390
  // Validate tenant access
403
391
  validateTenant() {
404
- var resources = [];
405
- var tenants = [];
406
- var currentTenant = this.App.Services.TenantService.getCurrentTenant();
392
+ let resources = [];
393
+ let tenants = [];
394
+ let currentTenant = this.App.Services.TenantService.getCurrentTenant();
407
395
  if (this.UserInfo !== null) {
408
396
  resources = this.UserInfo.resources ? this.UserInfo.resources[currentTenant] : [];
409
397
  tenants = this.UserInfo.tenants ? this.UserInfo.tenants : [];
410
398
  if (tenants == null || tenants.length === 0) {
411
- var _this$UserInfo$resour;
412
399
  // Fallback to tenant from resources if tenants list is not available
413
- tenants = Object.keys((_this$UserInfo$resour = this.UserInfo.resources) !== null && _this$UserInfo$resour !== void 0 ? _this$UserInfo$resour : {}).filter(tenant => tenant !== '*');
400
+ tenants = Object.keys(this.UserInfo.resources ?? {}).filter(tenant => tenant !== '*');
414
401
  }
415
402
  }
416
- var valid = tenants ? tenants.indexOf(currentTenant) !== -1 : false;
403
+ let valid = tenants ? tenants.indexOf(currentTenant) !== -1 : false;
417
404
  // If user is superuser, then tenant access is granted
418
405
  if (resources && resources.indexOf('authz:superuser') !== -1) {
419
406
  valid = true;
@@ -425,97 +412,85 @@ class AuthModule extends _asab_webui_components.Module {
425
412
  Returns true on success, false when the token is rejected (401)
426
413
  and undefined on a transient error (network, 5xx) which keeps the current user info
427
414
  */
428
- updateUserInfo() {
429
- var _this4 = this;
430
- return (0, _asyncToGenerator2.default)(function* () {
431
- var _response$data, _this4$UserInfo;
432
- var internal = _this4.OAuthTokens.internal || false;
433
- var response;
434
- try {
435
- response = yield _this4.Api.userinfo(_this4.OAuthTokens.access_token, internal);
436
- } catch (err) {
437
- var _err$response;
438
- console.error("Failed to update user info", err);
439
- if ((err === null || err === void 0 || (_err$response = err.response) === null || _err$response === void 0 ? void 0 : _err$response.status) !== 401) {
440
- return undefined;
441
- }
442
- _this4.UserInfo = null;
443
- if (_this4.App.AppStore) {
444
- var _this4$App$AppStore$d, _this4$App$AppStore;
445
- (_this4$App$AppStore$d = (_this4$App$AppStore = _this4.App.AppStore).dispatch) === null || _this4$App$AppStore$d === void 0 || _this4$App$AppStore$d.call(_this4$App$AppStore, {
446
- type: _actions.types.AUTH_USERINFO,
447
- payload: _this4.UserInfo
448
- });
449
- }
450
- return false;
415
+ async updateUserInfo() {
416
+ const internal = this.OAuthTokens.internal || false;
417
+ let response;
418
+ try {
419
+ response = await this.Api.userinfo(this.OAuthTokens.access_token, internal);
420
+ } catch (err) {
421
+ console.error("Failed to update user info", err);
422
+ if (err?.response?.status !== 401) {
423
+ return undefined;
451
424
  }
452
- _this4.UserInfo = response.data;
453
- if (internal) {
454
- // If the resource is `{'*': [....]}` then it is a global resources token (i.e. for API keys)
455
- var resources = response.data.resources;
456
- var isGlobalResources = resources != null && typeof resources === 'object' && !Array.isArray(resources) && Object.keys(resources).length === 1 && Array.isArray(resources['*']);
457
- if (isGlobalResources) {
458
- var tenant = (0, _extractTenantFromUrl.extractTenantFromUrl)();
459
- if (tenant) {
460
- // Monkey patch the userinfo to add the tenant and resources
461
- _this4.UserInfo['tenants'] = [tenant];
462
- _this4.UserInfo['resources'][tenant] = resources['*'];
463
- } else {
464
- var _this4$App, _this4$App$dispatch;
465
- console.error("Tenant not found in URL - if the global resources token is used, the tenant must be specified in the URL");
466
- _this4.UserInfo = null;
467
- _this4.SessionExpiration = null;
468
- (_this4$App = _this4.App) === null || _this4$App === void 0 || (_this4$App = _this4$App.AppStore) === null || _this4$App === void 0 || (_this4$App$dispatch = _this4$App.dispatch) === null || _this4$App$dispatch === void 0 || _this4$App$dispatch.call(_this4$App, {
469
- type: _actions.types.AUTH_USERINFO,
470
- payload: null
471
- });
472
- return false;
473
- }
474
- }
475
- }
476
- _this4.SessionExpiration = (_response$data = response.data) === null || _response$data === void 0 ? void 0 : _response$data.exp;
477
- if (_this4.App.AppStore) {
478
- var _this4$App$AppStore$d2, _this4$App$AppStore2;
479
- (_this4$App$AppStore$d2 = (_this4$App$AppStore2 = _this4.App.AppStore).dispatch) === null || _this4$App$AppStore$d2 === void 0 || _this4$App$AppStore$d2.call(_this4$App$AppStore2, {
425
+ this.UserInfo = null;
426
+ if (this.App.AppStore) {
427
+ this.App.AppStore.dispatch?.({
480
428
  type: _actions.types.AUTH_USERINFO,
481
- payload: _this4.UserInfo
429
+ payload: this.UserInfo
482
430
  });
483
431
  }
484
-
485
- // Check for TenantService and pass tenants list obtained from userinfo resources
486
- var availableTenants = _this4.UserInfo.tenants;
487
- if (availableTenants == null || availableTenants.length === 0) {
488
- var _this4$UserInfo$resou;
489
- // Fallback to tenant from resources if tenants list is not available
490
- availableTenants = Object.keys((_this4$UserInfo$resou = _this4.UserInfo.resources) !== null && _this4$UserInfo$resou !== void 0 ? _this4$UserInfo$resou : {}).filter(tenant => tenant !== '*');
491
- }
492
- if (((_this4$UserInfo = _this4.UserInfo) === null || _this4$UserInfo === void 0 ? void 0 : _this4$UserInfo.tenants) == null) {
493
- // This is a monkey patch to add the tenants list to the userinfo if missing
494
- _this4.UserInfo['tenants'] = availableTenants;
495
- }
496
- if (_this4.App.Services.TenantService) {
497
- yield _this4.App.Services.TenantService.setTenants(availableTenants, _this4._getAuthorizedTenant(_this4.UserInfo) // Get the authorized tenant
498
- );
432
+ return false;
433
+ }
434
+ this.UserInfo = response.data;
435
+ if (internal) {
436
+ // If the resource is `{'*': [....]}` then it is a global resources token (i.e. for API keys)
437
+ const resources = response.data.resources;
438
+ const isGlobalResources = resources != null && typeof resources === 'object' && !Array.isArray(resources) && Object.keys(resources).length === 1 && Array.isArray(resources['*']);
439
+ if (isGlobalResources) {
440
+ const tenant = (0, _extractTenantFromUrl.extractTenantFromUrl)();
441
+ if (tenant) {
442
+ // Monkey patch the userinfo to add the tenant and resources
443
+ this.UserInfo['tenants'] = [tenant];
444
+ this.UserInfo['resources'][tenant] = resources['*'];
445
+ } else {
446
+ console.error("Tenant not found in URL - if the global resources token is used, the tenant must be specified in the URL");
447
+ this.UserInfo = null;
448
+ this.SessionExpiration = null;
449
+ this.App?.AppStore?.dispatch?.({
450
+ type: _actions.types.AUTH_USERINFO,
451
+ payload: null
452
+ });
453
+ return false;
454
+ }
499
455
  }
500
- return true;
501
- })();
456
+ }
457
+ this.SessionExpiration = response.data?.exp;
458
+ if (this.App.AppStore) {
459
+ this.App.AppStore.dispatch?.({
460
+ type: _actions.types.AUTH_USERINFO,
461
+ payload: this.UserInfo
462
+ });
463
+ }
464
+
465
+ // Check for TenantService and pass tenants list obtained from userinfo resources
466
+ let availableTenants = this.UserInfo.tenants;
467
+ if (availableTenants == null || availableTenants.length === 0) {
468
+ // Fallback to tenant from resources if tenants list is not available
469
+ availableTenants = Object.keys(this.UserInfo.resources ?? {}).filter(tenant => tenant !== '*');
470
+ }
471
+ if (this.UserInfo?.tenants == null) {
472
+ // This is a monkey patch to add the tenants list to the userinfo if missing
473
+ this.UserInfo['tenants'] = availableTenants;
474
+ }
475
+ if (this.App.Services.TenantService) {
476
+ await this.App.Services.TenantService.setTenants(availableTenants, this._getAuthorizedTenant(this.UserInfo) // Get the authorized tenant
477
+ );
478
+ }
479
+ return true;
502
480
  }
503
481
 
504
482
  // Method for obtaining and storing the OAuth tokens based on authorization code
505
- _exchangeCodeForTokens(authorization_code) {
506
- var _this5 = this;
507
- return (0, _asyncToGenerator2.default)(function* () {
508
- try {
509
- var response = yield _this5.Api.token_authorization_code(authorization_code, _this5.RedirectURL);
510
- _this5.OAuthTokens = response.data;
511
- sessionStorage.setItem('SeaCatOAuth2Tokens', JSON.stringify(response.data));
512
- _this5._markAuthPageActive();
513
- return true;
514
- } catch (err) {
515
- console.error("Failed to update token", err);
516
- return false;
517
- }
518
- })();
483
+ async _exchangeCodeForTokens(authorization_code) {
484
+ try {
485
+ const response = await this.Api.token_authorization_code(authorization_code, this.RedirectURL);
486
+ this.OAuthTokens = response.data;
487
+ sessionStorage.setItem('SeaCatOAuth2Tokens', JSON.stringify(response.data));
488
+ this._markAuthPageActive();
489
+ return true;
490
+ } catch (err) {
491
+ console.error("Failed to update token", err);
492
+ return false;
493
+ }
519
494
  }
520
495
 
521
496
  /*
@@ -528,9 +503,10 @@ class AuthModule extends _asab_webui_components.Module {
528
503
  // Subscribe just once, it is not intentional to trigger pagehide twice
529
504
  if (this._unsubscribeLifecycle) return;
530
505
  // Subscribe to the pagehide event
531
- this._unsubscribeLifecycle = this.App.PubSub.subscribe('Application.lifecycle!', _ref3 => {
532
- var type = _ref3.type,
533
- persisted = _ref3.persisted;
506
+ this._unsubscribeLifecycle = this.App.PubSub.subscribe('Application.lifecycle!', ({
507
+ type,
508
+ persisted
509
+ }) => {
534
510
  if (type === 'pagehide' && !persisted) {
535
511
  sessionStorage.removeItem('SeaCatAuthTabActive');
536
512
  }
@@ -544,42 +520,33 @@ class AuthModule extends _asab_webui_components.Module {
544
520
  redirects are suppressed.
545
521
  The counter is cleared when initialize() completes successfully.
546
522
  */
547
- _attemptLogin(redirectURL) {
548
- var _arguments = arguments,
549
- _this6 = this;
550
- return (0, _asyncToGenerator2.default)(function* () {
551
- var force_login_prompt = _arguments.length > 1 && _arguments[1] !== undefined ? _arguments[1] : false;
552
- var MAX_LOGIN_ATTEMPTS = 10;
553
- _this6._loginAttempts += 1;
554
- sessionStorage.setItem('SeaCatLoginAttempts', String(_this6._loginAttempts));
555
- if (_this6._loginAttempts > MAX_LOGIN_ATTEMPTS) {
556
- // The info card for a user who ends up in a login redirect loop is shown by LoginLoopCard via sessionStorage SeaCatLoginAttempts
557
- console.error("AuthModule: Login redirect loop detected! ".concat(_this6._loginAttempts, " consecutive login redirects occurred! Please validate the authentication configuration."));
558
- return;
559
- }
560
- yield _this6.Api.login(redirectURL, force_login_prompt);
561
- })();
523
+ async _attemptLogin(redirectURL, force_login_prompt = false) {
524
+ const MAX_LOGIN_ATTEMPTS = 10;
525
+ this._loginAttempts += 1;
526
+ sessionStorage.setItem('SeaCatLoginAttempts', String(this._loginAttempts));
527
+ if (this._loginAttempts > MAX_LOGIN_ATTEMPTS) {
528
+ // The info card for a user who ends up in a login redirect loop is shown by LoginLoopCard via sessionStorage SeaCatLoginAttempts
529
+ console.error(`AuthModule: Login redirect loop detected! ${this._loginAttempts} consecutive login redirects occurred! Please validate the authentication configuration.`);
530
+ return;
531
+ }
532
+ await this.Api.login(redirectURL, force_login_prompt);
562
533
  }
563
534
 
564
535
  // Method for refreshing OAuth tokens
565
- _refreshTokens() {
566
- var _this7 = this;
567
- return (0, _asyncToGenerator2.default)(function* () {
568
- var _this7$OAuthTokens;
569
- // If no refresh_token found, return false
570
- if (!((_this7$OAuthTokens = _this7.OAuthTokens) !== null && _this7$OAuthTokens !== void 0 && _this7$OAuthTokens.refresh_token)) {
571
- return false;
572
- }
573
- try {
574
- var response = yield _this7.Api.token_refresh(_this7.OAuthTokens.refresh_token);
575
- _this7.OAuthTokens = response.data;
576
- sessionStorage.setItem('SeaCatOAuth2Tokens', JSON.stringify(response.data));
577
- return true;
578
- } catch (err) {
579
- console.error("Failed to refresh token", err);
580
- return false;
581
- }
582
- })();
536
+ async _refreshTokens() {
537
+ // If no refresh_token found, return false
538
+ if (!this.OAuthTokens?.refresh_token) {
539
+ return false;
540
+ }
541
+ try {
542
+ const response = await this.Api.token_refresh(this.OAuthTokens.refresh_token);
543
+ this.OAuthTokens = response.data;
544
+ sessionStorage.setItem('SeaCatOAuth2Tokens', JSON.stringify(response.data));
545
+ return true;
546
+ } catch (err) {
547
+ console.error("Failed to refresh token", err);
548
+ return false;
549
+ }
583
550
  }
584
551
 
585
552
  /*
@@ -589,22 +556,21 @@ class AuthModule extends _asab_webui_components.Module {
589
556
  Callers decide about the session expiration.
590
557
  */
591
558
  _renewSession() {
592
- var _this8 = this;
593
559
  if (this._sessionExpired) return Promise.resolve({
594
560
  tokensRefreshed: false,
595
561
  userInfoUpdated: undefined
596
562
  });
597
563
  if (!this._renewPromise) {
598
- this._renewPromise = (0, _asyncToGenerator2.default)(function* () {
564
+ this._renewPromise = (async () => {
599
565
  try {
600
- var tokensRefreshed = yield _this8._refreshTokens();
601
- var userInfoUpdated = yield _this8.updateUserInfo();
566
+ const tokensRefreshed = await this._refreshTokens();
567
+ const userInfoUpdated = await this.updateUserInfo();
602
568
  return {
603
569
  tokensRefreshed,
604
570
  userInfoUpdated
605
571
  };
606
572
  } finally {
607
- _this8._renewPromise = null;
573
+ this._renewPromise = null;
608
574
  }
609
575
  })();
610
576
  }
@@ -615,8 +581,8 @@ class AuthModule extends _asab_webui_components.Module {
615
581
  Return the authorized tenant ID from userinfo.
616
582
  Pick the first one if there are multiple tenants.
617
583
  */
618
- if (userInfo !== null && userInfo !== void 0 && userInfo.resources) {
619
- for (var tenantId in userInfo.resources) {
584
+ if (userInfo?.resources) {
585
+ for (let tenantId in userInfo.resources) {
620
586
  if (tenantId != '*' && userInfo.resources.hasOwnProperty(tenantId)) {
621
587
  return tenantId;
622
588
  }
@@ -639,12 +605,11 @@ class AuthModule extends _asab_webui_components.Module {
639
605
  this._unsubscribeLifecycle();
640
606
  this._unsubscribeLifecycle = null;
641
607
  }
642
- this.App.addAlert("info", "ASABAuthModule|Your session has expired.", 3600 * 1000, true, alert => /*#__PURE__*/_react.default.createElement(_SessionExpirationAlert.SessionExpirationAlert, {
608
+ this.App.addAlert("info", "ASABAuthModule|Your session has expired.", 3600 * 1000, true, alert => /*#__PURE__*/(0, _jsxRuntime.jsx)(_SessionExpirationAlert.SessionExpirationAlert, {
643
609
  alert: alert
644
610
  }));
645
611
  if (this.App.AppStore) {
646
- var _this$App$AppStore$di2, _this$App$AppStore2;
647
- (_this$App$AppStore$di2 = (_this$App$AppStore2 = this.App.AppStore).dispatch) === null || _this$App$AppStore$di2 === void 0 || _this$App$AppStore$di2.call(_this$App$AppStore2, {
612
+ this.App.AppStore.dispatch?.({
648
613
  type: _actions.types.AUTH_SESSION_EXPIRATION,
649
614
  sessionExpired: true
650
615
  });
@@ -663,98 +628,93 @@ class AuthModule extends _asab_webui_components.Module {
663
628
  }
664
629
 
665
630
  // Loop validating session expiration
666
- _startSessionExpirationValidation() {
667
- var _this9 = this;
668
- return (0, _asyncToGenerator2.default)(function* () {
669
- if (!_this9.SessionExpiration) {
670
- console.warn("Session expiration is not set.");
671
- return;
672
- }
631
+ async _startSessionExpirationValidation() {
632
+ if (!this.SessionExpiration) {
633
+ console.warn("Session expiration is not set.");
634
+ return;
635
+ }
673
636
 
674
- // Max session duration
675
- var MAX_SESSION_DURATION = Math.pow(2, 31) - 1;
676
-
677
- // Proactivelly validate session expiration
678
- var lastKnownExpiration = _this9.SessionExpiration; // Last known session expiration
679
- var sessionStartTime = Date.now() / 1000; // Session start time
680
- var sessionDuration = lastKnownExpiration - sessionStartTime; // Session duration
681
- // Prevent glitches on very large time remaining values
682
- if (sessionDuration > MAX_SESSION_DURATION) {
683
- // Set timeout to maximum allowed value
684
- sessionDuration = MAX_SESSION_DURATION;
685
- }
686
- var sessionMidpoint = sessionStartTime + sessionDuration / 2; // Session midpoint value
687
- var refreshSessionDone = false; // Tracks if the session has been proactivelly refreshed
688
- var warningDisplayed = false; // Tracks if the "about to expire" warning has been shown
689
-
690
- var _validateSession = /*#__PURE__*/function () {
691
- var _ref5 = (0, _asyncToGenerator2.default)(function* () {
692
- try {
693
- var currentTime = Date.now() / 1000; // Convert milliseconds to seconds
694
- var timeRemaining = _this9.SessionExpiration - currentTime; // Time difference for triggering "about to expire" warning
637
+ // Max session duration
638
+ const MAX_SESSION_DURATION = Math.pow(2, 31) - 1;
639
+
640
+ // Proactivelly validate session expiration
641
+ let lastKnownExpiration = this.SessionExpiration; // Last known session expiration
642
+ let sessionStartTime = Date.now() / 1000; // Session start time
643
+ let sessionDuration = lastKnownExpiration - sessionStartTime; // Session duration
644
+ // Prevent glitches on very large time remaining values
645
+ if (sessionDuration > MAX_SESSION_DURATION) {
646
+ // Set timeout to maximum allowed value
647
+ sessionDuration = MAX_SESSION_DURATION;
648
+ }
649
+ let sessionMidpoint = sessionStartTime + sessionDuration / 2; // Session midpoint value
650
+ let refreshSessionDone = false; // Tracks if the session has been proactivelly refreshed
651
+ let warningDisplayed = false; // Tracks if the "about to expire" warning has been shown
652
+
653
+ const validateSession = async () => {
654
+ try {
655
+ const currentTime = Date.now() / 1000; // Convert milliseconds to seconds
656
+ let timeRemaining = this.SessionExpiration - currentTime; // Time difference for triggering "about to expire" warning
657
+ // Prevent glitches on very large time remaining values
658
+ if (timeRemaining > MAX_SESSION_DURATION) {
659
+ // Set timeout to maximum allowed value
660
+ timeRemaining = MAX_SESSION_DURATION;
661
+ }
662
+
663
+ // Validate session on half of the session expiration or if the remaining time is <= 5min
664
+ if (!refreshSessionDone && (timeRemaining <= 300 || currentTime >= sessionMidpoint)) {
665
+ refreshSessionDone = true;
666
+ const {
667
+ tokensRefreshed
668
+ } = await this._renewSession();
669
+ // If current session expiration differs from last known expiration, recalculate session variables
670
+ if (tokensRefreshed && this.SessionExpiration !== lastKnownExpiration) {
671
+ lastKnownExpiration = this.SessionExpiration;
672
+ sessionStartTime = currentTime;
673
+ sessionDuration = lastKnownExpiration - sessionStartTime;
695
674
  // Prevent glitches on very large time remaining values
696
- if (timeRemaining > MAX_SESSION_DURATION) {
675
+ if (sessionDuration > MAX_SESSION_DURATION) {
697
676
  // Set timeout to maximum allowed value
698
- timeRemaining = MAX_SESSION_DURATION;
699
- }
700
-
701
- // Validate session on half of the session expiration or if the remaining time is <= 5min
702
- if (!refreshSessionDone && (timeRemaining <= 300 || currentTime >= sessionMidpoint)) {
703
- refreshSessionDone = true;
704
- var _yield$_this9$_renewS = yield _this9._renewSession(),
705
- tokensRefreshed = _yield$_this9$_renewS.tokensRefreshed;
706
- // If current session expiration differs from last known expiration, recalculate session variables
707
- if (tokensRefreshed && _this9.SessionExpiration !== lastKnownExpiration) {
708
- lastKnownExpiration = _this9.SessionExpiration;
709
- sessionStartTime = currentTime;
710
- sessionDuration = lastKnownExpiration - sessionStartTime;
711
- // Prevent glitches on very large time remaining values
712
- if (sessionDuration > MAX_SESSION_DURATION) {
713
- // Set timeout to maximum allowed value
714
- sessionDuration = MAX_SESSION_DURATION;
715
- }
716
- sessionMidpoint = sessionStartTime + sessionDuration / 2;
717
- refreshSessionDone = false;
718
- }
677
+ sessionDuration = MAX_SESSION_DURATION;
719
678
  }
679
+ sessionMidpoint = sessionStartTime + sessionDuration / 2;
680
+ refreshSessionDone = false;
681
+ }
682
+ }
720
683
 
721
- // If remaining time is between 1 and 60s, repetitivelly ask for userInfo and trigger "about to expire" warning
722
- if (timeRemaining <= 60 && timeRemaining > 0) {
723
- var _yield$_this9$_renewS2 = yield _this9._renewSession(),
724
- _tokensRefreshed = _yield$_this9$_renewS2.tokensRefreshed;
725
- if (!_tokensRefreshed && !warningDisplayed && !_this9._sessionExpired) {
726
- _this9.App.addAlert("info", "General|Your session will expire soon", 30, true);
727
- warningDisplayed = true; // Mark the warning as displayed
728
- }
729
- }
684
+ // If remaining time is between 1 and 60s, repetitivelly ask for userInfo and trigger "about to expire" warning
685
+ if (timeRemaining <= 60 && timeRemaining > 0) {
686
+ const {
687
+ tokensRefreshed
688
+ } = await this._renewSession();
689
+ if (!tokensRefreshed && !warningDisplayed && !this._sessionExpired) {
690
+ this.App.addAlert("info", "General|Your session will expire soon", 30, true);
691
+ warningDisplayed = true; // Mark the warning as displayed
692
+ }
693
+ }
730
694
 
731
- // Validation on expired session
732
- if (_this9.SessionExpiration <= currentTime) {
733
- var _yield$_this9$_renewS3 = yield _this9._renewSession(),
734
- userInfoUpdated = _yield$_this9$_renewS3.userInfoUpdated;
735
- if (userInfoUpdated === false) {
736
- _this9._triggerSessionExpired();
737
- }
738
- }
739
- } catch (err) {
740
- // Keep the validation loop running, the next cycle retries
741
- console.error("Failed to validate session", err);
695
+ // Validation on expired session
696
+ if (this.SessionExpiration <= currentTime) {
697
+ const {
698
+ userInfoUpdated
699
+ } = await this._renewSession();
700
+ if (userInfoUpdated === false) {
701
+ this._triggerSessionExpired();
742
702
  }
703
+ }
704
+ } catch (err) {
705
+ // Keep the validation loop running, the next cycle retries
706
+ console.error("Failed to validate session", err);
707
+ }
743
708
 
744
- // Stop further checks on expired session, it can be also triggered by the unauthorized interceptor meanwhile
745
- if (_this9._sessionExpired) return;
709
+ // Stop further checks on expired session, it can be also triggered by the unauthorized interceptor meanwhile
710
+ if (this._sessionExpired) return;
746
711
 
747
- // Re-trigger validation after 10 seconds
748
- _this9.sessionValidationInterval = setTimeout(_validateSession, 10000);
749
- });
750
- return function validateSession() {
751
- return _ref5.apply(this, arguments);
752
- };
753
- }();
754
-
755
- // Start the first validation cycle
756
- _validateSession();
757
- })();
712
+ // Re-trigger validation after 10 seconds
713
+ this.sessionValidationInterval = setTimeout(validateSession, 10000);
714
+ };
715
+
716
+ // Start the first validation cycle
717
+ validateSession();
758
718
  }
759
719
 
760
720
  // Stop looping on session expiration validation