@frontegg/redux-store 5.40.0 → 5.41.0

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.
@@ -0,0 +1,3612 @@
1
+ 'use strict';
2
+
3
+ var toolkit = require('@reduxjs/toolkit');
4
+ var restApi = require('@frontegg/rest-api');
5
+ var constants = require('./constants-52e37c08.js');
6
+ var tslib = require('tslib');
7
+ var effects = require('redux-saga/effects');
8
+ var vendor_index = require('./index-2ab7009b.js');
9
+ var uuid = require('uuid');
10
+ var audits_index = require('./audits/index.js');
11
+ var connectivity_index = require('./connectivity/index.js');
12
+ var subscriptions_index = require('./subscriptions/index.js');
13
+ var saga = require('./saga-b0d1a607.js');
14
+ var createSagaMiddleware = require('redux-saga');
15
+
16
+ function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
17
+
18
+ var createSagaMiddleware__default = /*#__PURE__*/_interopDefaultLegacy(createSagaMiddleware);
19
+
20
+ const resetStateByKey = (key, initialState) => (state) => (Object.assign(Object.assign({}, state), { [key]: initialState[key] }));
21
+ const typeReducer = (key) => (state, { payload }) => (Object.assign(Object.assign({}, state), { [key]: payload }));
22
+ const typeReducerForKey = (key) => ({
23
+ prepare: (payload) => ({ payload }),
24
+ reducer: (state, { payload }) => {
25
+ return Object.assign(Object.assign({}, state), { [key]: Object.assign(Object.assign({}, state[key]), payload) });
26
+ },
27
+ });
28
+ const typeReducerNestedKey = (key, nestedKey) => ({
29
+ prepare: (payload) => ({ payload }),
30
+ reducer: (state, { payload }) => {
31
+ var _a;
32
+ return Object.assign(Object.assign({}, state), { [key]: Object.assign(Object.assign({}, state[key]), { [nestedKey]: Object.assign(Object.assign({}, (_a = state === null || state === void 0 ? void 0 : state[key]) === null || _a === void 0 ? void 0 : _a[nestedKey]), payload) }) });
33
+ },
34
+ });
35
+ const loadersReducerForKey = (key) => ({
36
+ prepare: (payload) => ({ payload }),
37
+ reducer: (state, { payload }) => {
38
+ var _a;
39
+ return (Object.assign(Object.assign({}, state), { [key]: Object.assign(Object.assign({}, state[key]), { loaders: Object.assign(Object.assign({}, state[key].loaders), { [payload.key]: (_a = payload.value) !== null && _a !== void 0 ? _a : true }) }) }));
40
+ },
41
+ });
42
+ const errorsReducerForKey = (key) => ({
43
+ prepare: (payload) => ({ payload }),
44
+ reducer: (state, { payload }) => {
45
+ var _a;
46
+ return (Object.assign(Object.assign({}, state), { [key]: Object.assign(Object.assign({}, state[key]), { errors: Object.assign(Object.assign({}, state[key].errors), { [payload.key]: (_a = payload.value) !== null && _a !== void 0 ? _a : true }) }) }));
47
+ },
48
+ });
49
+ const delay = (delayTime = 500) => new Promise((resolve) => setTimeout(resolve, delayTime));
50
+
51
+ exports.LoginStep = void 0;
52
+ (function (LoginStep) {
53
+ LoginStep["preLogin"] = "preLogin";
54
+ LoginStep["magicLinkPreLoginSuccess"] = "magicLinkPreLoginSuccess";
55
+ LoginStep["loginWithSmsOtc"] = "loginWithSmsOtc";
56
+ LoginStep["loginWithOtc"] = "loginWithOtc";
57
+ LoginStep["loginWithPassword"] = "loginWithPassword";
58
+ LoginStep["loginWithTwoFactor"] = "loginWithTwoFactor";
59
+ LoginStep["redirectToSSO"] = "redirectToSSO";
60
+ LoginStep["loginWithSSOFailed"] = "loginWithSSOFailed";
61
+ LoginStep["success"] = "success";
62
+ LoginStep["forceTwoFactor"] = "forceTwoFactor";
63
+ LoginStep["recoverTwoFactor"] = "recoverTwoFactor";
64
+ })(exports.LoginStep || (exports.LoginStep = {}));
65
+
66
+ const loginState = {
67
+ step: exports.LoginStep.preLogin,
68
+ loading: false,
69
+ email: '',
70
+ tenants: [],
71
+ };
72
+ const reducers$f = {
73
+ setLoginState: typeReducerForKey('loginState'),
74
+ resetLoginState: resetStateByKey('loginState', { loginState }),
75
+ };
76
+ const actions$g = {
77
+ requestAuthorize: toolkit.createAction(`${constants.authStoreName}/requestAuthorize`, (payload = false) => ({ payload })),
78
+ requestHostedLoginAuthorize: toolkit.createAction(`${constants.authStoreName}/requestHostedLoginAuthorize`),
79
+ handleHostedLoginCallback: toolkit.createAction(`${constants.authStoreName}/handleHostedLoginCallback`, (payload) => ({ payload })),
80
+ afterAuthNavigation: toolkit.createAction(`${constants.authStoreName}/afterAuthNavigation`),
81
+ preLogin: toolkit.createAction(`${constants.authStoreName}/preLogin`, (payload) => ({ payload })),
82
+ postLogin: toolkit.createAction(`${constants.authStoreName}/postLogin`, (payload) => ({ payload })),
83
+ login: toolkit.createAction(`${constants.authStoreName}/login`, (payload) => ({ payload })),
84
+ loginWithMfa: toolkit.createAction(`${constants.authStoreName}/loginWithMfa`, (payload) => ({ payload })),
85
+ recoverMfa: toolkit.createAction(`${constants.authStoreName}/recoverMfa`, (payload) => ({ payload })),
86
+ logout: toolkit.createAction(`${constants.authStoreName}/logout`, (payload) => ({ payload })),
87
+ silentLogout: toolkit.createAction(`${constants.authStoreName}/silentLogout`, (payload) => ({ payload })),
88
+ checkIfAllowToRememberMfaDevice: toolkit.createAction(`${constants.authStoreName}/checkIfAllowToRememberMfaDevice`, (payload) => ({ payload })),
89
+ passwordlessPreLogin: toolkit.createAction(`${constants.authStoreName}/passwordlessPreLogin`, (payload) => ({ payload })),
90
+ passwordlessPostLogin: toolkit.createAction(`${constants.authStoreName}/passwordlessPostLogin`, (payload) => ({ payload })),
91
+ verifyInviteToken: toolkit.createAction(`${constants.authStoreName}/verifyInviteToken`, (payload) => ({ payload })),
92
+ };
93
+
94
+ exports.ActivateAccountStep = void 0;
95
+ (function (ActivateAccountStep) {
96
+ ActivateAccountStep["activating"] = "activating";
97
+ ActivateAccountStep["success"] = "success";
98
+ ActivateAccountStep["resend"] = "resend";
99
+ ActivateAccountStep["activatingForm"] = "activatingForm";
100
+ })(exports.ActivateAccountStep || (exports.ActivateAccountStep = {}));
101
+
102
+ const activateState = {
103
+ step: exports.ActivateAccountStep.activating,
104
+ loading: false,
105
+ resentEmail: false,
106
+ activationStrategy: {
107
+ loading: false,
108
+ },
109
+ };
110
+ const reducers$e = {
111
+ setActivateState: typeReducerForKey('activateState'),
112
+ resetActivateState: resetStateByKey('activateState', { activateState }),
113
+ setActivateStrategyState: typeReducerNestedKey('activateState', 'activationStrategy'),
114
+ };
115
+ const actions$f = {
116
+ activateAccount: toolkit.createAction(`${constants.authStoreName}/activateAccount`, (payload) => ({ payload })),
117
+ preActivateAccount: toolkit.createAction(`${constants.authStoreName}/preActivateAccount`, (payload) => ({ payload })),
118
+ getActivateAccountStrategy: toolkit.createAction(`${constants.authStoreName}/getActivateAccountStrategy`, (payload) => ({ payload })),
119
+ resendActivationEmail: toolkit.createAction(`${constants.authStoreName}/resendActivationEmail`, (payload) => ({
120
+ payload,
121
+ })),
122
+ };
123
+
124
+ exports.AcceptInvitationStep = void 0;
125
+ (function (AcceptInvitationStep) {
126
+ AcceptInvitationStep["validate"] = "validate";
127
+ AcceptInvitationStep["invalid"] = "invalid";
128
+ AcceptInvitationStep["pending"] = "pending";
129
+ AcceptInvitationStep["success"] = "success";
130
+ AcceptInvitationStep["failed"] = "failed";
131
+ })(exports.AcceptInvitationStep || (exports.AcceptInvitationStep = {}));
132
+
133
+ const acceptInvitationState = {
134
+ step: exports.AcceptInvitationStep.validate,
135
+ };
136
+ const reducers$d = {
137
+ setAcceptInvitationState: typeReducerForKey('acceptInvitationState'),
138
+ resetAcceptInvitationState: resetStateByKey('acceptInvitationState', {
139
+ acceptInvitationState,
140
+ }),
141
+ };
142
+ const actions$e = {
143
+ acceptInvitation: toolkit.createAction(`${constants.authStoreName}/acceptInvitation`, (payload) => ({ payload })),
144
+ };
145
+
146
+ exports.ForgotPasswordStep = void 0;
147
+ (function (ForgotPasswordStep) {
148
+ ForgotPasswordStep["forgotPassword"] = "forgotPassword";
149
+ ForgotPasswordStep["success"] = "success";
150
+ })(exports.ForgotPasswordStep || (exports.ForgotPasswordStep = {}));
151
+
152
+ const forgotPasswordState = {
153
+ step: exports.ForgotPasswordStep.forgotPassword,
154
+ loading: false,
155
+ email: '',
156
+ passwordConfig: null,
157
+ };
158
+ const reducers$c = {
159
+ setForgotPasswordState: typeReducerForKey('forgotPasswordState'),
160
+ resetForgotPasswordState: resetStateByKey('forgotPasswordState', { forgotPasswordState }),
161
+ };
162
+ const actions$d = {
163
+ forgotPassword: toolkit.createAction(`${constants.authStoreName}/forgotPassword`, (payload) => ({ payload })),
164
+ resetPassword: toolkit.createAction(`${constants.authStoreName}/resetPassword`, (payload) => ({ payload })),
165
+ loadPasswordConfig: toolkit.createAction(`${constants.authStoreName}/loadPasswordConfig`, (payload) => ({
166
+ payload,
167
+ })),
168
+ };
169
+
170
+ exports.ResetPhoneNumberStep = void 0;
171
+ (function (ResetPhoneNumberStep) {
172
+ ResetPhoneNumberStep["ResetPhoneNumber"] = "ResetPhoneNumber";
173
+ ResetPhoneNumberStep["VerifyResetPhoneNumber"] = "VerifyResetPhoneNumber";
174
+ ResetPhoneNumberStep["ChangePhoneNumber"] = "ChangePhoneNumber";
175
+ })(exports.ResetPhoneNumberStep || (exports.ResetPhoneNumberStep = {}));
176
+
177
+ const resetPhoneNumberState = {
178
+ step: exports.ResetPhoneNumberStep.ResetPhoneNumber,
179
+ loading: false,
180
+ };
181
+ const reducers$b = {
182
+ setResetPhoneNumberState: typeReducerForKey('resetPhoneNumberState'),
183
+ resetResetPhoneNumberState: resetStateByKey('resetPhoneNumberState', { resetPhoneNumberState }),
184
+ };
185
+ const actions$c = {
186
+ resetPhoneNumber: toolkit.createAction(`${constants.authStoreName}/resetPhoneNumber`, (payload) => ({ payload })),
187
+ verifyResetPhoneNumber: toolkit.createAction(`${constants.authStoreName}/verifyResetPhoneNumber`, (payload) => ({ payload })),
188
+ changePhoneNumber: toolkit.createAction(`${constants.authStoreName}/changePhoneNumber`, (payload) => ({ payload })),
189
+ };
190
+
191
+ const ssoState = {
192
+ firstLoad: true,
193
+ loading: true,
194
+ saving: false,
195
+ errors: {},
196
+ loaders: {},
197
+ ssoConfigurations: []
198
+ };
199
+ const reducers$a = {
200
+ setSSOLoader: loadersReducerForKey('ssoState'),
201
+ setSSOError: errorsReducerForKey('ssoState'),
202
+ setSSOState: typeReducerForKey('ssoState'),
203
+ resetSSOState: resetStateByKey('ssoState', { ssoState }),
204
+ };
205
+ const actions$b = {
206
+ loadSSOConfigurationsV2: toolkit.createAction(`${constants.authStoreName}/loadSSOConfigurationsV2`),
207
+ saveSSOConfigurationV2: toolkit.createAction(`${constants.authStoreName}/saveSSOConfigurationV2`, (payload) => ({ payload })),
208
+ updateSSOConfiguration: toolkit.createAction(`${constants.authStoreName}/updateSSOConfiguration`, (payload) => ({ payload })),
209
+ deleteSSOConfiguration: toolkit.createAction(`${constants.authStoreName}/deleteSSOConfiguration`, (payload) => ({ payload })),
210
+ saveSSODomain: toolkit.createAction(`${constants.authStoreName}/saveSSODomain`, (payload) => ({ payload })),
211
+ deleteSSODomain: toolkit.createAction(`${constants.authStoreName}/deleteSSODomain`, (payload) => ({ payload })),
212
+ validateSSODomainV2: toolkit.createAction(`${constants.authStoreName}/validateSSODomainV2`, (payload) => ({ payload })),
213
+ setSSODefaultRoles: toolkit.createAction(`${constants.authStoreName}/setSSODefaultRoles`, (payload) => ({ payload })),
214
+ setSSOGroups: toolkit.createAction(`${constants.authStoreName}/setSSOGroups`, (payload) => ({ payload })),
215
+ saveSSOConfigurationByMetadata: toolkit.createAction(`${constants.authStoreName}/saveSSOConfigurationByMetadata`, (payload) => ({ payload })),
216
+ updateSSOConfigurationByMetadata: toolkit.createAction(`${constants.authStoreName}/updateSSOConfigurationByMetadata`, (payload) => ({ payload })),
217
+ loadSSOConfigurations: toolkit.createAction(`${constants.authStoreName}/loadSSOConfigurations`),
218
+ loadSSOAuthorizationRoles: toolkit.createAction(`${constants.authStoreName}/loadSSOAuthorizationRoles`),
219
+ saveSSOConfigurations: toolkit.createAction(`${constants.authStoreName}/saveSSOConfigurations`, (payload) => ({ payload })),
220
+ // NOTE: use withCallback in case of promise response
221
+ saveSSOConfigurationsFile: toolkit.createAction(`${constants.authStoreName}/saveSSOConfigurationsFile`, (payload) => ({
222
+ payload,
223
+ })),
224
+ saveSSOConfigurationsFileWithCallback: toolkit.createAction(`${constants.authStoreName}/saveSSOConfigurationsFileWithCallback`, (payload) => ({ payload })),
225
+ validateSSODomain: toolkit.createAction(`${constants.authStoreName}/validateSSODomain`, (payload) => ({ payload })),
226
+ updateSSOAuthorizationRoles: toolkit.createAction(`${constants.authStoreName}/updateSSOAuthorizationRoles`, (payload) => ({ payload })),
227
+ deleteSamlGroup: toolkit.createAction(`${constants.authStoreName}/deleteSamlGroup`, (payload) => ({ payload })),
228
+ createSamlGroup: toolkit.createAction(`${constants.authStoreName}/createSamlGroup`, (payload) => ({ payload })),
229
+ oidcPostlogin: toolkit.createAction(`${constants.authStoreName}/oidcPostlogin`, (payload) => ({
230
+ payload,
231
+ })),
232
+ };
233
+
234
+ const profileState = {
235
+ loading: false,
236
+ error: null,
237
+ };
238
+ const reducers$9 = {
239
+ setProfileState: typeReducerForKey('profileState'),
240
+ resetProfileState: resetStateByKey('profileState', { profileState }),
241
+ };
242
+ const actions$a = {
243
+ loadProfile: toolkit.createAction(`${constants.authStoreName}/loadProfile`),
244
+ saveProfile: toolkit.createAction(`${constants.authStoreName}/saveProfile`, (payload) => ({ payload })),
245
+ changePassword: toolkit.createAction(`${constants.authStoreName}/changePassword`, (payload) => ({
246
+ payload,
247
+ })),
248
+ };
249
+
250
+ exports.MFAStep = void 0;
251
+ (function (MFAStep) {
252
+ MFAStep["verify"] = "verify";
253
+ MFAStep["recoveryCode"] = "recoveryCode";
254
+ })(exports.MFAStep || (exports.MFAStep = {}));
255
+
256
+ const mfaState = {
257
+ step: exports.MFAStep.verify,
258
+ loading: false,
259
+ };
260
+ const reducers$8 = {
261
+ setMfaState: typeReducerForKey('mfaState'),
262
+ resetMfaState: resetStateByKey('mfaState', { mfaState }),
263
+ };
264
+ const actions$9 = {
265
+ enrollMfa: toolkit.createAction(`${constants.authStoreName}/enrollMfa`),
266
+ verifyMfa: toolkit.createAction(`${constants.authStoreName}/verifyMfa`, (payload) => ({
267
+ payload,
268
+ })),
269
+ verifyMfaAfterForce: toolkit.createAction(`${constants.authStoreName}/verifyMfaAfterForce`, (payload) => ({
270
+ payload,
271
+ })),
272
+ disableMfa: toolkit.createAction(`${constants.authStoreName}/disableMfa`, (payload) => ({ payload })),
273
+ };
274
+
275
+ const teamState = {
276
+ loaders: {},
277
+ pageOffset: 0,
278
+ pageSize: 20,
279
+ errors: {},
280
+ users: [],
281
+ roles: [],
282
+ permissions: [],
283
+ totalPages: 0,
284
+ filter: [],
285
+ sort: [],
286
+ addUserDialogState: {
287
+ loading: false,
288
+ open: false,
289
+ },
290
+ deleteUserDialogState: {
291
+ loading: false,
292
+ open: false,
293
+ },
294
+ };
295
+ const reducers$7 = {
296
+ setTeamLoader: loadersReducerForKey('teamState'),
297
+ setTeamError: errorsReducerForKey('teamState'),
298
+ setTeamState: typeReducerForKey('teamState'),
299
+ resetTeamState: resetStateByKey('teamState', { teamState }),
300
+ };
301
+ const actions$8 = {
302
+ loadUsers: toolkit.createAction(`${constants.authStoreName}/loadUsers`, (payload) => ({ payload })),
303
+ loadRoles: toolkit.createAction(`${constants.authStoreName}/loadRoles`, (payload) => ({ payload })),
304
+ addUser: toolkit.createAction(`${constants.authStoreName}/addUser`, (payload) => ({ payload })),
305
+ updateUser: toolkit.createAction(`${constants.authStoreName}/updateUser`, (payload) => ({
306
+ payload,
307
+ })),
308
+ deleteUser: toolkit.createAction(`${constants.authStoreName}/deleteUser`, (payload) => ({ payload })),
309
+ resendActivationLink: toolkit.createAction(`${constants.authStoreName}/resendActivationLink`, (payload) => ({ payload })),
310
+ resendInvitationLink: toolkit.createAction(`${constants.authStoreName}/resendInvitationLink`, (payload) => ({ payload })),
311
+ getInvitationLink: toolkit.createAction(`${constants.authStoreName}/getInvitationLink`),
312
+ createInvitationLink: toolkit.createAction(`${constants.authStoreName}/createInvitationLink`, (payload) => ({ payload })),
313
+ updateInvitationLink: toolkit.createAction(`${constants.authStoreName}/updateInvitationLink`, (payload) => ({ payload })),
314
+ deleteInvitationLink: toolkit.createAction(`${constants.authStoreName}/deleteInvitationLink`, (payload) => ({ payload })),
315
+ openAddUserDialog: toolkit.createAction(`${constants.authStoreName}/openAddUserDialog`, (payload) => ({ payload })),
316
+ closeAddUserDialog: toolkit.createAction(`${constants.authStoreName}/closeAddUserDialog`, (payload) => ({ payload })),
317
+ openDeleteUserDialog: toolkit.createAction(`${constants.authStoreName}/openDeleteUserDialog`, (payload) => ({
318
+ payload,
319
+ })),
320
+ closeDeleteUserDialog: toolkit.createAction(`${constants.authStoreName}/closeDeleteUserDialog`, (payload) => ({ payload })),
321
+ };
322
+
323
+ const socialLoginState = {
324
+ firstLoad: true,
325
+ loading: false,
326
+ error: '',
327
+ };
328
+ const reducers$6 = {
329
+ setSocialLoginsState: typeReducerForKey('socialLoginState'),
330
+ resetSocialLoginsState: resetStateByKey('socialLoginState', { socialLoginState }),
331
+ };
332
+ const actions$7 = {
333
+ loadSocialLoginsConfiguration: toolkit.createAction(`${constants.authStoreName}/loadSocialLoginsConfiguration`),
334
+ loadSocialLoginsConfigurationV2: toolkit.createAction(`${constants.authStoreName}/loadSocialLoginsConfigurationV2`),
335
+ loginViaSocialLogin: toolkit.createAction(`${constants.authStoreName}/loginViaSocialLogin`, (payload) => ({
336
+ payload,
337
+ })),
338
+ setSocialLoginError: toolkit.createAction(`${constants.authStoreName}/setSocialLoginError`, (payload) => ({
339
+ payload,
340
+ })),
341
+ };
342
+
343
+ exports.SignUpStage = void 0;
344
+ (function (SignUpStage) {
345
+ SignUpStage["SignUp"] = "SignUp";
346
+ SignUpStage["SignUpSuccess"] = "SignUpSuccess";
347
+ })(exports.SignUpStage || (exports.SignUpStage = {}));
348
+
349
+ const signUpState = {
350
+ loading: false,
351
+ allowSignUps: false,
352
+ allowNotVerifiedUsersLogin: false,
353
+ firstLoad: true,
354
+ stage: exports.SignUpStage.SignUp,
355
+ };
356
+ const reducers$5 = {
357
+ setSignUpState: typeReducerForKey('signUpState'),
358
+ resetSignUpState: resetStateByKey('signUpState', { signUpState }),
359
+ };
360
+ const actions$6 = {
361
+ signUpUser: toolkit.createAction(`${constants.authStoreName}/signUpUser`, (payload) => ({ payload })),
362
+ resetSignUpStateSoft: toolkit.createAction(`${constants.authStoreName}/resetSignUpStateSoft`),
363
+ };
364
+
365
+ const apiTokensState = {
366
+ apiTokenType: null,
367
+ searchValue: '',
368
+ showAddTokenDialog: false,
369
+ createdByUserIdColumn: 'show',
370
+ deleteTokenDialog: {
371
+ open: false,
372
+ clientId: '',
373
+ },
374
+ successDialog: {
375
+ open: false,
376
+ secret: '',
377
+ clientId: '',
378
+ },
379
+ loaders: {},
380
+ apiTokensDataTenant: [],
381
+ apiTokensDataUser: [],
382
+ roles: [],
383
+ permissions: [],
384
+ errors: {},
385
+ };
386
+ const reducers$4 = {
387
+ setApiTokensLoader: loadersReducerForKey('apiTokensState'),
388
+ setApiTokensError: errorsReducerForKey('apiTokensState'),
389
+ setApiTokensState: typeReducerForKey('apiTokensState'),
390
+ resetApiTokensState: resetStateByKey('apiTokensState', { apiTokensState }),
391
+ };
392
+ const actions$5 = {
393
+ loadApiTokens: toolkit.createAction(`${constants.authStoreName}/loadApiTokens`, (payload) => ({
394
+ payload,
395
+ })),
396
+ initApiTokensData: toolkit.createAction(`${constants.authStoreName}/initApiTokensData`, (payload) => ({ payload })),
397
+ addTenantApiToken: toolkit.createAction(`${constants.authStoreName}/addTenantApiToken`, (payload) => ({
398
+ payload,
399
+ })),
400
+ addUserApiToken: toolkit.createAction(`${constants.authStoreName}/addUserApiToken`, (payload) => ({ payload })),
401
+ deleteUserApiToken: toolkit.createAction(`${constants.authStoreName}/deleteUserApiToken`, (payload) => ({ payload })),
402
+ deleteTenantApiToken: toolkit.createAction(`${constants.authStoreName}/deleteTenantApiToken`, (payload) => ({ payload })),
403
+ };
404
+
405
+ const securityPolicyState = {
406
+ globalPolicy: {
407
+ loading: true,
408
+ },
409
+ publicPolicy: {
410
+ loading: false,
411
+ },
412
+ mfaPolicy: {
413
+ loading: true,
414
+ },
415
+ lockoutPolicy: {
416
+ loading: true,
417
+ },
418
+ captchaPolicy: {
419
+ loading: true,
420
+ },
421
+ passwordHistoryPolicy: {
422
+ loading: true,
423
+ },
424
+ passwordPolicy: {
425
+ loading: true,
426
+ },
427
+ };
428
+ const reducers$3 = {
429
+ setSecurityPolicyState: typeReducerForKey('securityPolicyState'),
430
+ setSecurityPolicyGlobalState: typeReducerNestedKey('securityPolicyState', 'globalPolicy'),
431
+ setSecurityPolicyPublicState: typeReducerNestedKey('securityPolicyState', 'publicPolicy'),
432
+ setSecurityPolicyMfaState: typeReducerNestedKey('securityPolicyState', 'mfaPolicy'),
433
+ setSecurityPolicyLockoutState: typeReducerNestedKey('securityPolicyState', 'lockoutPolicy'),
434
+ setSecurityPolicyCaptchaState: typeReducerNestedKey('securityPolicyState', 'captchaPolicy'),
435
+ setSecurityPolicyPasswordHistoryState: typeReducerNestedKey('securityPolicyState', 'passwordHistoryPolicy'),
436
+ setSecurityPolicyPasswordState: typeReducerNestedKey('securityPolicyState', 'passwordPolicy'),
437
+ resetSecurityPolicyState: resetStateByKey('securityPolicyState', { securityPolicyState }),
438
+ };
439
+ const actions$4 = {
440
+ loadSecurityPolicy: toolkit.createAction(`${constants.authStoreName}/loadSecurityPolicy`),
441
+ loadPublicSecurityPolicy: toolkit.createAction(`${constants.authStoreName}/loadPublicSecurityPolicy`),
442
+ loadSecurityPolicyMfa: toolkit.createAction(`${constants.authStoreName}/loadSecurityPolicyMfa`),
443
+ saveSecurityPolicyMfa: toolkit.createAction(`${constants.authStoreName}/saveSecurityPolicyMfa`, (payload) => ({ payload })),
444
+ loadSecurityPolicyLockout: toolkit.createAction(`${constants.authStoreName}/loadSecurityPolicyLockout`),
445
+ saveSecurityPolicyLockout: toolkit.createAction(`${constants.authStoreName}/saveSecurityPolicyLockout`, (payload) => ({ payload })),
446
+ loadSecurityPolicyCaptcha: toolkit.createAction(`${constants.authStoreName}/loadSecurityPolicyCaptcha`),
447
+ loadSecurityPolicyPasswordHistory: toolkit.createAction(`${constants.authStoreName}/loadSecurityPolicyPasswordHistory`),
448
+ saveSecurityPolicyPasswordHistory: toolkit.createAction(`${constants.authStoreName}/saveSecurityPolicyPasswordHistory`, (payload) => ({ payload })),
449
+ loadVendorPasswordConfig: toolkit.createAction(`${constants.authStoreName}/loadVendorPasswordConfig`),
450
+ };
451
+
452
+ const accountSettingsState = {
453
+ loading: false,
454
+ };
455
+ const reducers$2 = {
456
+ setAccountSettingsState: typeReducerForKey('accountSettingsState'),
457
+ resetAccountSettingsState: resetStateByKey('accountSettingsState', { accountSettingsState }),
458
+ };
459
+ const actions$3 = {
460
+ loadAccountSettings: toolkit.createAction(`${constants.authStoreName}/loadAccountSettings`, (payload) => ({ payload })),
461
+ saveAccountSettings: toolkit.createAction(`${constants.authStoreName}/saveAccountSettings`, (payload) => ({ payload })),
462
+ };
463
+
464
+ const tenantsState = {
465
+ tenants: [],
466
+ subTenants: [],
467
+ loading: true,
468
+ };
469
+ const reducers$1 = {
470
+ setTenantsState: typeReducerForKey('tenantsState'),
471
+ resetTenantsState: resetStateByKey('tenantsState', { tenantsState }),
472
+ };
473
+ const actions$2 = {
474
+ switchTenant: toolkit.createAction(`${constants.authStoreName}/switchTenant`, (payload) => ({ payload })),
475
+ loadTenants: toolkit.createAction(`${constants.authStoreName}/loadTenants`, (payload) => ({
476
+ payload,
477
+ })),
478
+ loadSubTenants: toolkit.createAction(`${constants.authStoreName}/loadSubTenants`, (payload) => ({
479
+ payload,
480
+ })),
481
+ };
482
+
483
+ const rolesState = {
484
+ loading: false,
485
+ roles: [],
486
+ permissions: [],
487
+ permissionCategories: [],
488
+ };
489
+ const reducers = {
490
+ setRolesState: typeReducerForKey('rolesState'),
491
+ resetRolesState: resetStateByKey('rolesState', { rolesState }),
492
+ };
493
+ const actions$1 = {
494
+ loadRolesAndPermissions: toolkit.createAction(`${constants.authStoreName}/loadRoles`, (payload) => ({ payload })),
495
+ addRole: toolkit.createAction(`${constants.authStoreName}/addRole`, (payload) => ({ payload })),
496
+ updateRole: toolkit.createAction(`${constants.authStoreName}/updateRole`, (payload) => ({ payload })),
497
+ deleteRole: toolkit.createAction(`${constants.authStoreName}/deleteRole`, (payload) => ({ payload })),
498
+ attachPermissionsToRole: toolkit.createAction(`${constants.authStoreName}/attachPermissionsToRole`, (payload) => ({ payload })),
499
+ attachPermissionToRoles: toolkit.createAction(`${constants.authStoreName}/attachPermissionToRoles`, (payload) => ({ payload })),
500
+ };
501
+
502
+ const reinitializeState = {
503
+ isAuthenticated: false,
504
+ isLoading: true,
505
+ isSSOAuth: false,
506
+ user: null,
507
+ signUpState,
508
+ loginState,
509
+ activateState,
510
+ acceptInvitationState,
511
+ forgotPasswordState,
512
+ ssoState,
513
+ profileState,
514
+ mfaState,
515
+ teamState,
516
+ socialLoginState,
517
+ apiTokensState,
518
+ securityPolicyState,
519
+ accountSettingsState,
520
+ tenantsState,
521
+ rolesState,
522
+ resetPhoneNumberState
523
+ };
524
+ const initialState$1 = Object.assign({ routes: {
525
+ authenticatedUrl: '/',
526
+ loginUrl: '/account/login',
527
+ logoutUrl: '/account/logout',
528
+ activateUrl: '/account/activate',
529
+ acceptInvitationUrl: '/account/invitation/accept',
530
+ forgetPasswordUrl: '/account/forget-password',
531
+ resetPhoneNumberUrl: '/account/reset-phone-number',
532
+ resetPasswordUrl: '/account/reset-password',
533
+ socialLoginCallbackUrl: '/account/social/success',
534
+ signUpUrl: '/account/sign-up',
535
+ oidcRedirectUrl: '/account/oidc/callback',
536
+ samlCallbackUrl: '/account/saml/callback',
537
+ magicLinkCallbackUrl: '/account/login/magic-link',
538
+ hostedLoginRedirectUrl: '/oauth/callback'
539
+ }, onRedirectTo: () => { } }, reinitializeState);
540
+
541
+ const { reducer, actions: sliceActions } = toolkit.createSlice({
542
+ name: constants.authStoreName,
543
+ initialState: initialState$1,
544
+ reducers: Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({ resetState: (state) => (Object.assign(Object.assign({}, state), reinitializeState)), setState: (state, { payload }) => (Object.assign(Object.assign({}, state), payload)), setUser: typeReducer('user') }, reducers$f), reducers$6), reducers$e), reducers$d), reducers$c), reducers$b), reducers$5), reducers$9), reducers$a), reducers$8), reducers$7), reducers$4), reducers$3), reducers$2), reducers$1), reducers),
545
+ });
546
+ const actions = Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({}, sliceActions), actions$g), actions$7), actions$f), actions$e), actions$d), actions$c), actions$6), actions$a), actions$b), actions$9), actions$8), actions$5), actions$4), actions$3), actions$2), actions$1);
547
+
548
+ exports.SSOStateKeys = void 0;
549
+ (function (SSOStateKeys) {
550
+ SSOStateKeys["LOAD_SSO_CONFIGURATIONS"] = "LOAD_SSO_CONFIGURATIONS";
551
+ SSOStateKeys["SAVE_SSO_CONFIGURATION"] = "SAVE_SSO_CONFIGURATION";
552
+ SSOStateKeys["UPDATE_SSO_CONFIGURATION"] = "UPDATE_SSO_CONFIGURATION";
553
+ SSOStateKeys["SAVE_SSO_CONFIGURATION_BY_METADATA"] = "SAVE_SSO_CONFIGURATION_BY_METADATA";
554
+ SSOStateKeys["UPDATE_SSO_CONFIGURATION_BY_METADATA"] = "UPDATE_SSO_CONFIGURATION";
555
+ SSOStateKeys["DELETE_SSO_CONFIGURATION"] = "DELETE_SSO_CONFIGURATION";
556
+ SSOStateKeys["SAVE_SSO_DOMAIN"] = "SAVE_SSO_DOMAIN";
557
+ SSOStateKeys["DELETE_SSO_DOMAIN"] = "DELETE_SSO_DOMAIN";
558
+ SSOStateKeys["VALIDATE_SSO_DOMAIN"] = "VALIDATE_SSO_DOMAIN";
559
+ SSOStateKeys["UPDATE_SSO_DEFAULT_ROLES"] = "UPDATE_SSO_DEFAULT_ROLES";
560
+ SSOStateKeys["DELETE_SSO_GROUPS"] = "DELETE_SSO_GROUPS";
561
+ SSOStateKeys["SAVE_SSO_GROUPS"] = "SAVE_SSO_GROUPS";
562
+ SSOStateKeys["GET_SSO_AUTHORIZATION_ROLES"] = "GET_SSO_AUTHORIZATION_ROLES";
563
+ })(exports.SSOStateKeys || (exports.SSOStateKeys = {}));
564
+ exports.SamlVendors = void 0;
565
+ (function (SamlVendors) {
566
+ SamlVendors["Saml"] = "saml";
567
+ SamlVendors["Okta"] = "okta";
568
+ SamlVendors["Azure"] = "azure";
569
+ SamlVendors["Google"] = "google";
570
+ SamlVendors["Oidc"] = "oidc";
571
+ })(exports.SamlVendors || (exports.SamlVendors = {}));
572
+
573
+ function omitProps(props, keys) {
574
+ const newProps = Object.assign({}, props);
575
+ keys.forEach((key) => {
576
+ delete newProps[key];
577
+ });
578
+ return newProps;
579
+ }
580
+ function generateCodeChallenge(codeVerifier) {
581
+ return tslib.__awaiter(this, void 0, void 0, function* () {
582
+ const digest = yield crypto.subtle.digest('SHA-256', new TextEncoder().encode(codeVerifier));
583
+ // @ts-ignore
584
+ return btoa(String.fromCharCode(...new Uint8Array(digest)))
585
+ .replace(/=/g, '')
586
+ .replace(/\+/g, '-')
587
+ .replace(/\//g, '_');
588
+ });
589
+ }
590
+ function createRandomString(length = 16) {
591
+ let text = '';
592
+ const possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
593
+ for (let i = 0; i < length; i++) {
594
+ text += possible.charAt(Math.floor(Math.random() * possible.length));
595
+ }
596
+ return text;
597
+ }
598
+ const readFileAsText = (file) => new Promise((resolve, reject) => {
599
+ const reader = new FileReader();
600
+ reader.readAsText(file);
601
+ reader.onload = () => resolve(reader.result);
602
+ reader.onerror = reject;
603
+ });
604
+
605
+ const apiTokensDataDemo = {
606
+ clientId: 'CLIENT_ID_16806d3d-8fc3-4450-be97-abdaf66b723e',
607
+ secret: 'SECRET_16806d3d-8fc3-4450-be97-abdaf66b723e',
608
+ createdAt: 'createdAt',
609
+ description: 'This is dummy api token for preview only',
610
+ };
611
+ const apiTokensDataTenantDemo = Object.assign(Object.assign({}, apiTokensDataDemo), { roleIds: [], tenantId: 'my-tenant-id', createdByUserId: 'createdByUserId' });
612
+ const roleDemo = [
613
+ {
614
+ id: 'roleId',
615
+ key: 'admin',
616
+ isDefault: false,
617
+ name: 'Admin',
618
+ description: null,
619
+ permissions: ['adminPermissionId'],
620
+ tenantId: 'tenantId',
621
+ vendorId: 'vendorId',
622
+ createdAt: new Date(),
623
+ updatedAt: new Date(),
624
+ },
625
+ ];
626
+ const rolePermissionDemo = [
627
+ {
628
+ id: 'adminPermissionId',
629
+ key: 'fe.*',
630
+ name: 'General Admin',
631
+ description: undefined,
632
+ categoryId: 'category',
633
+ fePermission: true,
634
+ createdAt: new Date(),
635
+ updatedAt: new Date(),
636
+ },
637
+ ];
638
+ const userProfileDemo = {
639
+ id: 'testId',
640
+ name: 'Dummy User',
641
+ email: 'dummy@frontegg.com',
642
+ mfaEnrolled: true,
643
+ profileImage: undefined,
644
+ profilePictureUrl: 'https://www.gravatar.com/avatar/42b2ad2bad6fc9b9db5086dfcf8072ac?d=https://ui-avatars.com/api/fe/128/random?t=1617261890875?t=1617261917434',
645
+ roles: roleDemo,
646
+ permissions: rolePermissionDemo,
647
+ tenantId: 'my-tenant-id',
648
+ tenantIds: ['my-tenant-id'],
649
+ activatedForTenant: true,
650
+ metadata: {},
651
+ roleIds: undefined,
652
+ verified: undefined,
653
+ };
654
+ const userDemo = Object.assign(Object.assign({}, userProfileDemo), { accessToken: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiI1MTY5YmY0Zi02YmI5LTQ5NGMtOGNkZS05MDc4NDQ0NWY4MDciLCJuYW1lIjoiRHVtbXkgVXNlciIsImVtYWlsIjoiZHVtbXlAZnJvbnRlZ2cuY29tIiwiZW1haWxfdmVyaWZpZWQiOnRydWUsIm1ldGFkYXRhIjp7fSwicm9sZXMiOlsiYWRtaW4iXSwicGVybWlzc2lvbnMiOlsiZmUuKiJdLCJ0ZW5hbnRJZCI6Im15LXRlbmFudC1pZCIsInRlbmFudElkcyI6WyJteS10ZW5hbnQtaWQiXSwicHJvZmlsZVBpY3R1cmVVcmwiOiJodHRwczovL3d3dy5ncmF2YXRhci5jb20vYXZhdGFyLzQyYjJhZDJiYWQ2ZmM5YjlkYjUwODZkZmNmODA3MmFjP2Q9aHR0cHM6Ly91aS1hdmF0YXJzLmNvbS9hcGkvZmUvMTI4L3JhbmRvbT90PTE2MTcyNjE4OTA4NzU_dD0xNjE3MjYxOTE3NDM0IiwidHlwZSI6InVzZXJUb2tlbiIsImlhdCI6MTYxNzkwNjMyNCwiZXhwIjoxNjE3OTkyNzI0LCJpc3MiOiJmcm9udGVnZyJ9.paaXLkpWEWbQmUtoK2P8IwXCxK4WJp7XhXonvzF8g1I', expiresIn: 86400, mfaRequired: false, refreshToken: 'refresh-token-dummy-de39dc9c-9d22-4852-b7f5-c3c0aa613b58', type: 'userToken', iat: 1617906324, exp: 1617992724, iss: 'frontegg', email_verified: true });
655
+ const profileStateDemo = {
656
+ loading: false,
657
+ error: undefined,
658
+ saving: true,
659
+ profile: userProfileDemo,
660
+ };
661
+ const policyDemo = {
662
+ id: 'id',
663
+ enforceMFAType: 'DontForce',
664
+ createdAt: new Date(),
665
+ updatedAt: new Date(),
666
+ allowOverrideEnforcePasswordHistory: true,
667
+ allowOverridePasswordComplexity: false,
668
+ allowOverridePasswordExpiration: false,
669
+ allowSignups: true,
670
+ apiTokensEnabled: true,
671
+ cookieSameSite: 'cookieSameSite',
672
+ defaultRefreshTokenExpiration: 0,
673
+ defaultTokenExpiration: 1,
674
+ publicKey: 'publicKey',
675
+ };
676
+ const publicSecurityPolicy = {
677
+ allowSignups: true,
678
+ allowNotVerifiedUsersLogin: false,
679
+ apiTokensEnabled: true,
680
+ forcePermissions: false,
681
+ authStrategy: restApi.AuthStrategyEnum.EmailAndPassword,
682
+ };
683
+ const policyMfaDemo = {
684
+ id: 'id',
685
+ enforceMFAType: 'DontForce',
686
+ createdAt: new Date(),
687
+ updatedAt: new Date(),
688
+ };
689
+ const policyLockoutDemo = {
690
+ id: 'id',
691
+ enabled: true,
692
+ maxAttempts: 1,
693
+ createdAt: new Date(),
694
+ updatedAt: new Date(),
695
+ };
696
+ const policyPasswordHistoryDemo = {
697
+ id: 'id',
698
+ enabled: true,
699
+ historySize: 1,
700
+ createdAt: new Date(),
701
+ updatedAt: new Date(),
702
+ };
703
+ const samlConfigurationDemo = {
704
+ enabled: true,
705
+ domain: 'domain',
706
+ validated: true,
707
+ generatedVerification: 'generatedVerification',
708
+ ssoEndpoint: 'ssoEndpoint',
709
+ publicCertificate: 'publicCertificate',
710
+ signRequest: true,
711
+ createdAt: new Date(),
712
+ updatedAt: new Date(),
713
+ acsUrl: undefined,
714
+ spEntityId: undefined,
715
+ oidcClientId: undefined,
716
+ oidcSecret: undefined,
717
+ type: undefined,
718
+ };
719
+ const samlMetadataDemo = {
720
+ id: 'id',
721
+ createdAt: 'createdAt',
722
+ updatedAt: 'updatedAt',
723
+ properties: [],
724
+ vendorId: 'vendorId',
725
+ entityName: 'saml',
726
+ isActive: true,
727
+ configuration: {
728
+ acsUrl: 'acsUrl',
729
+ spEntityId: 'spEntityId',
730
+ },
731
+ };
732
+ const rolesDemo = [
733
+ {
734
+ id: 'id',
735
+ description: 'description',
736
+ key: 'key',
737
+ name: 'name',
738
+ permissions: [],
739
+ permissionLevel: 1,
740
+ },
741
+ ];
742
+ const ssoStateDemo = {
743
+ firstLoad: false,
744
+ loading: false,
745
+ error: undefined,
746
+ saving: false,
747
+ samlConfiguration: samlConfigurationDemo,
748
+ roles: rolesDemo,
749
+ authorizationRoles: [],
750
+ errors: {},
751
+ loaders: {},
752
+ ssoConfigurations: [],
753
+ };
754
+ const permissionsDemo = [
755
+ {
756
+ description: 'string',
757
+ fePermission: true,
758
+ id: 'id',
759
+ key: 'key',
760
+ name: 'name',
761
+ roleIds: [],
762
+ createdAt: new Date(),
763
+ updatedAt: new Date(),
764
+ categoryId: 'categoryId',
765
+ },
766
+ ];
767
+ const userTeamDemo = {
768
+ id: 'id',
769
+ email: 'email',
770
+ name: 'name',
771
+ phone: undefined,
772
+ profileImage: undefined,
773
+ profileImageUrl: undefined,
774
+ tenantId: 'tenantId',
775
+ vendorId: 'vendorId',
776
+ roleIds: [],
777
+ activatedForTenant: true,
778
+ createdAt: new Date().toISOString(),
779
+ customData: undefined,
780
+ lastLogin: undefined,
781
+ mfaEnabled: undefined,
782
+ roles: [],
783
+ };
784
+ const usersDemo = [userTeamDemo];
785
+ const tenantsDemo = [
786
+ {
787
+ id: 'my-tenant-id',
788
+ name: 'My Tenant Name',
789
+ deletedAt: null,
790
+ metadata: undefined,
791
+ tenantId: 'my-tenant-id',
792
+ vendorId: 'vendorId',
793
+ createdAt: new Date(),
794
+ updatedAt: new Date(),
795
+ address: undefined,
796
+ timezone: undefined,
797
+ dateFormat: undefined,
798
+ timeFormat: undefined,
799
+ currency: undefined,
800
+ logo: undefined,
801
+ },
802
+ ];
803
+
804
+ exports.UserVeirifedOriginTypes = void 0;
805
+ (function (UserVeirifedOriginTypes) {
806
+ UserVeirifedOriginTypes["SOCIAL_LOGIN"] = "SOCIAL_LOGIN";
807
+ UserVeirifedOriginTypes["PASSWORDLESS"] = "PASSWORDLESS";
808
+ UserVeirifedOriginTypes["ACTIVATION_LINK"] = "ACTIVATION_LINK";
809
+ })(exports.UserVeirifedOriginTypes || (exports.UserVeirifedOriginTypes = {}));
810
+ exports.AuthenticationTypes = void 0;
811
+ (function (AuthenticationTypes) {
812
+ AuthenticationTypes["SOCIAL_LOGIN"] = "SOCIAL_LOGIN";
813
+ AuthenticationTypes["PASSWORD"] = "PASSWORD";
814
+ })(exports.AuthenticationTypes || (exports.AuthenticationTypes = {}));
815
+
816
+ function* loadAllowSignUps() {
817
+ yield effects.put(actions.setSignUpState({ loading: true }));
818
+ try {
819
+ const policy = yield effects.call(restApi.api.auth.getVendorConfig);
820
+ const { allowSignups: allowSignUps, allowNotVerifiedUsersLogin } = policy;
821
+ yield effects.put(actions.setSignUpState({ loading: false, allowSignUps, allowNotVerifiedUsersLogin, firstLoad: false }));
822
+ yield effects.put(actions.setSecurityPolicyPublicState({ policy, loading: false }));
823
+ }
824
+ catch (e) {
825
+ yield effects.put(actions.setSignUpState({ loading: false, error: e.message, firstLoad: false }));
826
+ }
827
+ }
828
+ function* signUpUser(_a) {
829
+ var _b;
830
+ var _c = _a.payload, { events, url } = _c, payload = tslib.__rest(_c, ["events", "url"]);
831
+ yield effects.put(actions.setSignUpState({ loading: true }));
832
+ try {
833
+ const { routes, onRedirectTo } = yield effects.select((state) => state.auth);
834
+ const { shouldActivate, user } = yield effects.call(restApi.api.auth.signUpUser, payload);
835
+ if (!payload.invitationToken) {
836
+ const { email, name, companyName } = payload;
837
+ (_b = events === null || events === void 0 ? void 0 : events.signUpComplete) === null || _b === void 0 ? void 0 : _b.call(events, { email, name, companyName, url, authenticationType: exports.AuthenticationTypes.PASSWORD });
838
+ }
839
+ restApi.ContextHolder.setAccessToken(user === null || user === void 0 ? void 0 : user.accessToken);
840
+ restApi.ContextHolder.setUser(user);
841
+ if (!shouldActivate && (user === null || user === void 0 ? void 0 : user.mfaRequired) && (user === null || user === void 0 ? void 0 : user.mfaToken)) {
842
+ let step = exports.LoginStep.loginWithTwoFactor;
843
+ if (user.hasOwnProperty('mfaEnrolled') && !user.mfaEnrolled) {
844
+ yield effects.put(actions.setMfaState({
845
+ step: exports.MFAStep.verify,
846
+ qrCode: user.qrCode,
847
+ recoveryCode: user.recoveryCode,
848
+ mfaToken: user.mfaToken,
849
+ loading: false,
850
+ }));
851
+ step = exports.LoginStep.forceTwoFactor;
852
+ }
853
+ yield effects.put(actions.setLoginState({ step }));
854
+ onRedirectTo(routes.loginUrl);
855
+ }
856
+ else {
857
+ yield effects.put(actions.setSignUpState({ loading: false, shouldActivate, stage: exports.SignUpStage.SignUpSuccess }));
858
+ yield effects.put(actions.setState({
859
+ user,
860
+ isAuthenticated: !!(user === null || user === void 0 ? void 0 : user.accessToken),
861
+ }));
862
+ if (!shouldActivate) {
863
+ yield effects.put(actions.loadTenants());
864
+ }
865
+ }
866
+ }
867
+ catch (e) {
868
+ restApi.ContextHolder.setAccessToken(null);
869
+ restApi.ContextHolder.setUser(null);
870
+ yield effects.put(actions.setSignUpState({ loading: false, error: e.message }));
871
+ }
872
+ yield effects.put(actions.setSignUpState({ loading: false }));
873
+ }
874
+ function* resetSignUpStateSoft() {
875
+ const { allowSignUps, allowNotVerifiedUsersLogin } = yield effects.select((state) => state.auth.signUpState);
876
+ yield effects.put(actions.resetSignUpState());
877
+ yield effects.put(actions.setSignUpState({ allowSignUps, allowNotVerifiedUsersLogin }));
878
+ }
879
+ function* signUpSaga() {
880
+ yield effects.takeLeading(actions.signUpUser, signUpUser);
881
+ yield effects.takeLeading(actions.resetSignUpStateSoft, resetSignUpStateSoft);
882
+ }
883
+
884
+ const authStrategyLoginStepMap = {
885
+ [restApi.AuthStrategyEnum.Code]: exports.LoginStep.loginWithOtc,
886
+ [restApi.AuthStrategyEnum.EmailAndPassword]: exports.LoginStep.loginWithPassword,
887
+ [restApi.AuthStrategyEnum.MagicLink]: exports.LoginStep.magicLinkPreLoginSuccess,
888
+ [restApi.AuthStrategyEnum.SmsCode]: exports.LoginStep.loginWithSmsOtc,
889
+ };
890
+ function* afterAuthNavigation() {
891
+ var _a;
892
+ const onRedirectTo = restApi.ContextHolder.onRedirectTo;
893
+ const { routes, includeQueryParam } = yield effects.select((state) => state.auth);
894
+ const { loginUrl, logoutUrl, socialLoginCallbackUrl, activateUrl } = routes;
895
+ let { authenticatedUrl } = routes;
896
+ const afterAuthRedirect = window.localStorage.getItem(constants.FRONTEGG_AFTER_AUTH_REDIRECT_URL);
897
+ if (afterAuthRedirect && ![loginUrl, logoutUrl, socialLoginCallbackUrl, activateUrl].includes(afterAuthRedirect)) {
898
+ authenticatedUrl = afterAuthRedirect;
899
+ }
900
+ window.localStorage.removeItem(constants.FRONTEGG_AFTER_AUTH_REDIRECT_URL);
901
+ yield effects.delay(200);
902
+ effects.put(actions.resetLoginState());
903
+ const url = new URL(window === null || window === void 0 ? void 0 : window.location.href);
904
+ let redirectUrl = authenticatedUrl;
905
+ if (url.searchParams.get('redirectUrl')) {
906
+ redirectUrl = (_a = url.searchParams.get('redirectUrl')) !== null && _a !== void 0 ? _a : authenticatedUrl;
907
+ }
908
+ else if (includeQueryParam) {
909
+ redirectUrl += window.location.search;
910
+ }
911
+ onRedirectTo(redirectUrl, { refresh: redirectUrl.startsWith('http') });
912
+ }
913
+ function* refreshMetadata() {
914
+ var _a;
915
+ let ssoACS;
916
+ try {
917
+ const metadata = yield effects.call(restApi.api.metadata.getSamlMetadata);
918
+ ssoACS = (_a = metadata === null || metadata === void 0 ? void 0 : metadata.configuration) === null || _a === void 0 ? void 0 : _a.acsUrl;
919
+ }
920
+ catch (e) {
921
+ console.error(e);
922
+ }
923
+ yield effects.put(actions.setState({ ssoACS }));
924
+ }
925
+ function* loadSSOPublicConfigurationFunction() {
926
+ try {
927
+ const { isActive } = yield effects.call(restApi.api.auth.getSSOPublicConfiguration);
928
+ yield effects.put(actions.setState({ isSSOAuth: isActive }));
929
+ }
930
+ catch (e) {
931
+ console.error(e);
932
+ }
933
+ }
934
+ const isMfaRequired = (user) => {
935
+ if (user.mfaRequired && user.mfaToken) {
936
+ restApi.ContextHolder.setAccessToken(null);
937
+ restApi.ContextHolder.setUser(null);
938
+ return true;
939
+ }
940
+ else {
941
+ restApi.ContextHolder.setAccessToken(user.accessToken);
942
+ restApi.ContextHolder.setUser(user);
943
+ return false;
944
+ }
945
+ };
946
+ function* getMfaRequiredState(user) {
947
+ let setMfaState = {};
948
+ let step = exports.LoginStep.loginWithTwoFactor;
949
+ const { loginState } = yield effects.select((state) => state.auth);
950
+ const { isAllowedToRemember, mfaDeviceExpiration } = yield effects.call(restApi.api.auth.checkIfAllowToRememberMfaDevice, user.mfaToken);
951
+ if (user.hasOwnProperty('mfaEnrolled') && !user.mfaEnrolled) {
952
+ setMfaState = {
953
+ mfaState: {
954
+ step: exports.MFAStep.verify,
955
+ qrCode: user.qrCode,
956
+ recoveryCode: user.recoveryCode,
957
+ loading: false,
958
+ mfaToken: user.mfaToken,
959
+ },
960
+ };
961
+ step = exports.LoginStep.forceTwoFactor;
962
+ }
963
+ return Object.assign(Object.assign({ user: undefined, isAuthenticated: false }, setMfaState), { loginState: Object.assign(Object.assign({}, loginState), { mfaToken: user.mfaToken, mfaRequired: user.mfaRequired, loading: false, error: undefined, step, tenantsLoading: true, tenants: [], allowRememberMfaDevice: isAllowedToRemember, mfaDeviceExpiration }) });
964
+ }
965
+ function* refreshToken() {
966
+ try {
967
+ const onRedirectTo = restApi.ContextHolder.onRedirectTo;
968
+ const { routes, loginState } = yield effects.select((state) => state.auth);
969
+ const { user, tenants } = yield effects.call(restApi.api.auth.refreshTokenV2);
970
+ if (isMfaRequired(user)) {
971
+ const mfaRequiredState = yield getMfaRequiredState(user);
972
+ yield effects.put(actions.setState(mfaRequiredState));
973
+ onRedirectTo(routes.loginUrl, { preserveQueryParams: true });
974
+ }
975
+ else {
976
+ yield effects.put(actions.setTenantsState({ tenants, loading: false }));
977
+ yield effects.put(actions.setState({ user, isAuthenticated: true }));
978
+ if ([routes.loginUrl, routes.socialLoginCallbackUrl, routes.signUpUrl, routes.oidcRedirectUrl, routes.samlCallbackUrl]
979
+ .some(url => url && window.location.pathname.endsWith(url))) {
980
+ if (loginState.isNewUser && routes.signUpSuccessUrl && routes.socialLoginCallbackUrl === window.location.pathname) {
981
+ onRedirectTo(routes.signUpSuccessUrl, { refresh: routes.signUpSuccessUrl.startsWith('http') });
982
+ }
983
+ else {
984
+ yield afterAuthNavigation();
985
+ }
986
+ }
987
+ }
988
+ }
989
+ catch (e) {
990
+ restApi.ContextHolder.setAccessToken(null);
991
+ restApi.ContextHolder.setUser(null);
992
+ yield effects.put(actions.setState({ user: undefined, isAuthenticated: false }));
993
+ }
994
+ }
995
+ function* requestAuthorize({ payload: firstTime }) {
996
+ const calls = [];
997
+ if (firstTime) {
998
+ yield effects.put(actions.setState({ isLoading: true }));
999
+ yield effects.put(actions.loadSocialLoginsConfigurationV2());
1000
+ calls.push(effects.call(loadAllowSignUps));
1001
+ calls.push(effects.call(loadSSOPublicConfigurationFunction));
1002
+ calls.push(effects.call(vendor_index.loadVendorPublicInfo));
1003
+ calls.push(effects.call(refreshMetadata));
1004
+ }
1005
+ calls.push(effects.call(refreshToken));
1006
+ yield effects.all(calls);
1007
+ yield effects.put(actions.setState({ isLoading: false }));
1008
+ }
1009
+ function* requestHostedLoginAuthorize() {
1010
+ const { routes, context, onRedirectTo } = yield effects.select((state) => ({
1011
+ routes: state.auth.routes,
1012
+ onRedirectTo: state.auth.onRedirectTo,
1013
+ context: state.root.context,
1014
+ }));
1015
+ // Generate the relevant params for the redirect
1016
+ const nonce = createRandomString();
1017
+ const code_verifier = createRandomString();
1018
+ const code_challenge = yield effects.call(generateCodeChallenge, code_verifier);
1019
+ // We are saving the verifier in session storage to be able to validate the response
1020
+ localStorage.setItem(constants.HOSTED_LOGIN_VERIFIER_KEY, code_verifier);
1021
+ const redirectUrl = `${window.location.origin}${routes.hostedLoginRedirectUrl}`;
1022
+ const baseUrl = restApi.fetch.getBaseUrl(context, '/oauth/authorize');
1023
+ // Hard coded for now
1024
+ const oauthUrl = `${baseUrl}/oauth/authorize`;
1025
+ const params = {
1026
+ response_type: 'code',
1027
+ client_id: context.clientId || 'INVALID-CLIENT-ID',
1028
+ scope: 'openid email profile',
1029
+ redirect_uri: redirectUrl,
1030
+ code_challenge: code_challenge,
1031
+ code_challenge_method: 'S256',
1032
+ nonce,
1033
+ };
1034
+ const searchParams = new URLSearchParams(params);
1035
+ const url = `${oauthUrl}?${searchParams.toString()}`;
1036
+ onRedirectTo(url, { refresh: true });
1037
+ }
1038
+ function* handleHostedLoginCallback({ payload }) {
1039
+ // Hard coded for now
1040
+ const code_verifier = localStorage.getItem(constants.HOSTED_LOGIN_VERIFIER_KEY) || 'INVALID-CODE-VERIFIER';
1041
+ const routes = yield effects.select((state) => state.auth.routes);
1042
+ const redirectUrl = `${window.location.origin}${routes.hostedLoginRedirectUrl}`;
1043
+ const body = {
1044
+ code: payload.code,
1045
+ redirect_uri: redirectUrl,
1046
+ code_verifier,
1047
+ grant_type: 'authorization_code',
1048
+ };
1049
+ const user = yield effects.call(restApi.api.auth.exchangeOAuthTokens, body);
1050
+ // TODO: Validate nonce and aud
1051
+ yield effects.put(actions.setState({ user, isAuthenticated: true }));
1052
+ yield effects.put(actions.loadTenants());
1053
+ yield afterAuthNavigation();
1054
+ }
1055
+ function* passwordlessPreLogin(_a) {
1056
+ var _b = _a.payload, { callback } = _b, payload = tslib.__rest(_b, ["callback"]);
1057
+ try {
1058
+ const { onRedirectTo, routes } = yield effects.select(({ auth: { onRedirectTo, routes } }) => ({ onRedirectTo, routes }));
1059
+ yield effects.put(actions.setLoginState({ loading: true }));
1060
+ const preloginRes = yield effects.call(restApi.api.auth.passwordlessPreLogin, payload);
1061
+ const step = authStrategyLoginStepMap[payload.type];
1062
+ if (step === exports.LoginStep.loginWithSmsOtc && preloginRes.resetPhoneNumberToken) {
1063
+ yield effects.put(actions.setResetPhoneNumberState({ resetPhoneNumberToken: preloginRes.resetPhoneNumberToken, step: exports.ResetPhoneNumberStep.VerifyResetPhoneNumber }));
1064
+ onRedirectTo(routes.resetPhoneNumberUrl);
1065
+ return;
1066
+ }
1067
+ yield effects.put(actions.setLoginState({ step, loading: false, email: payload.email, phoneNumber: preloginRes === null || preloginRes === void 0 ? void 0 : preloginRes.phoneNumber }));
1068
+ callback === null || callback === void 0 ? void 0 : callback();
1069
+ }
1070
+ catch (e) {
1071
+ yield effects.put(actions.setLoginState({ error: e.message, loading: false }));
1072
+ callback === null || callback === void 0 ? void 0 : callback();
1073
+ }
1074
+ }
1075
+ function* passwordlessPostLogin(_a) {
1076
+ var _b, _c;
1077
+ var _d = _a.payload, { callback, events } = _d, payload = tslib.__rest(_d, ["callback", "events"]);
1078
+ try {
1079
+ yield effects.put(actions.setLoginState({ loading: true }));
1080
+ const data = yield effects.call(restApi.api.auth.passwordlessPostLogin, payload);
1081
+ if (isMfaRequired(data)) {
1082
+ const onRedirectTo = restApi.ContextHolder.onRedirectTo;
1083
+ const { routes } = yield effects.select((state) => state.auth);
1084
+ const mfaRequiredState = yield getMfaRequiredState(data);
1085
+ yield effects.put(actions.setState(mfaRequiredState));
1086
+ onRedirectTo(routes.loginUrl, { preserveQueryParams: true });
1087
+ }
1088
+ else {
1089
+ const user = yield effects.call(restApi.api.auth.generateLoginResponse, data);
1090
+ if (data.emailVerified) {
1091
+ (_b = events === null || events === void 0 ? void 0 : events.userVerified) === null || _b === void 0 ? void 0 : _b.call(events, { email: user.email, origin: exports.UserVeirifedOriginTypes.PASSWORDLESS });
1092
+ }
1093
+ yield effects.put(actions.loadTenants());
1094
+ yield effects.put(actions.setState({ user, isAuthenticated: true }));
1095
+ yield afterAuthNavigation();
1096
+ }
1097
+ callback === null || callback === void 0 ? void 0 : callback(true);
1098
+ }
1099
+ catch (e) {
1100
+ yield effects.put(actions.setLoginState({ error: (_c = e.message) !== null && _c !== void 0 ? _c : 'Failed to authenticate' }));
1101
+ }
1102
+ finally {
1103
+ yield effects.put(actions.setLoginState({ loading: false }));
1104
+ }
1105
+ }
1106
+ function* verifyInviteToken({ payload }) {
1107
+ var _a;
1108
+ try {
1109
+ yield effects.put(actions.setLoginState({ loading: true }));
1110
+ const { name: inviteTokenTenantName } = yield effects.call(restApi.api.auth.verifyInviteToken, payload);
1111
+ yield effects.put(actions.setLoginState({ inviteTokenTenantName }));
1112
+ }
1113
+ catch (e) {
1114
+ console.error(e);
1115
+ yield effects.put(actions.setLoginState({ inviteTokenError: (_a = e.message) !== null && _a !== void 0 ? _a : `We couldn't verify your invitation` }));
1116
+ }
1117
+ finally {
1118
+ yield effects.put(actions.setLoginState({ loading: false }));
1119
+ }
1120
+ }
1121
+ function* preLogin({ payload: { email, recaptchaToken, invitationToken, callback } }) {
1122
+ yield effects.put(actions.setLoginState({ loading: true }));
1123
+ try {
1124
+ const onRedirectTo = yield effects.select(({ auth: { onRedirectTo } }) => onRedirectTo);
1125
+ let { address, idpType } = yield effects.call(restApi.api.auth.preLoginV2, { email });
1126
+ if (address) {
1127
+ if (idpType === exports.SamlVendors.Oidc && !address.includes('redirect_uri')) {
1128
+ const { routes: { oidcRedirectUrl } } = yield effects.select(({ auth: { routes } }) => ({ routes }));
1129
+ address += `&redirect_uri=${window.location.origin}${oidcRedirectUrl}`;
1130
+ }
1131
+ yield effects.put(actions.setLoginState({ step: exports.LoginStep.redirectToSSO, loading: false, ssoRedirectUrl: address }));
1132
+ setTimeout(() => {
1133
+ onRedirectTo(address, { refresh: true });
1134
+ }, 2000);
1135
+ }
1136
+ else {
1137
+ yield ssoPreloginFailed({ email, recaptchaToken, callback, invitationToken });
1138
+ }
1139
+ }
1140
+ catch (e) {
1141
+ yield ssoPreloginFailed({ email, recaptchaToken, callback, invitationToken });
1142
+ }
1143
+ }
1144
+ function* ssoPreloginFailed(_a) {
1145
+ var { callback } = _a, body = tslib.__rest(_a, ["callback"]);
1146
+ const publicPolicy = yield effects.select(({ auth: { securityPolicyState: { publicPolicy: { policy: publicPolicy } } } }) => publicPolicy);
1147
+ if (!(publicPolicy === null || publicPolicy === void 0 ? void 0 : publicPolicy.authStrategy)) {
1148
+ yield effects.put(actions.setLoginState({ step: exports.LoginStep.loginWithPassword, loading: false }));
1149
+ callback === null || callback === void 0 ? void 0 : callback();
1150
+ return;
1151
+ }
1152
+ if ((publicPolicy === null || publicPolicy === void 0 ? void 0 : publicPolicy.authStrategy) === restApi.AuthStrategyEnum.EmailAndPassword) {
1153
+ yield effects.put(actions.setLoginState({ step: exports.LoginStep.loginWithPassword, loading: false }));
1154
+ callback === null || callback === void 0 ? void 0 : callback();
1155
+ }
1156
+ else if ([restApi.AuthStrategyEnum.MagicLink, restApi.AuthStrategyEnum.Code, restApi.AuthStrategyEnum.SmsCode].includes(publicPolicy === null || publicPolicy === void 0 ? void 0 : publicPolicy.authStrategy)) {
1157
+ yield effects.put(actions.passwordlessPreLogin(Object.assign(Object.assign({}, body), { type: publicPolicy === null || publicPolicy === void 0 ? void 0 : publicPolicy.authStrategy, callback })));
1158
+ }
1159
+ else {
1160
+ yield effects.put(actions.setLoginState({ step: exports.LoginStep.loginWithPassword, loading: false }));
1161
+ callback === null || callback === void 0 ? void 0 : callback();
1162
+ }
1163
+ }
1164
+ function* postLogin({ payload }) {
1165
+ const { onRedirectTo, routes } = yield effects.select(({ auth: { onRedirectTo, routes } }) => ({ onRedirectTo, routes }));
1166
+ yield effects.put(actions.setLoginState({ loading: true }));
1167
+ try {
1168
+ const user = yield effects.call(restApi.api.auth.postLogin, payload);
1169
+ restApi.ContextHolder.setAccessToken(user.accessToken);
1170
+ restApi.ContextHolder.setUser(user);
1171
+ yield effects.put(actions.setState({
1172
+ user: !!user.accessToken ? user : undefined,
1173
+ isAuthenticated: !!user.accessToken,
1174
+ }));
1175
+ yield afterAuthNavigation();
1176
+ }
1177
+ catch (e) {
1178
+ setTimeout(() => {
1179
+ onRedirectTo(routes.authenticatedUrl);
1180
+ }, 1000);
1181
+ yield effects.put(actions.setLoginState({ step: exports.LoginStep.loginWithSSOFailed, loading: false }));
1182
+ }
1183
+ }
1184
+ function* login({ payload: { email, password, recaptchaToken, invitationToken, callback } }) {
1185
+ yield effects.put(actions.setLoginState({ loading: true }));
1186
+ try {
1187
+ const user = yield effects.call(restApi.api.auth.login, {
1188
+ email,
1189
+ password,
1190
+ recaptchaToken,
1191
+ invitationToken,
1192
+ });
1193
+ restApi.ContextHolder.setAccessToken(user.accessToken);
1194
+ restApi.ContextHolder.setUser(user);
1195
+ let setMfaState = {};
1196
+ let step = exports.LoginStep.success;
1197
+ if (user.mfaRequired && user.mfaToken) {
1198
+ step = exports.LoginStep.loginWithTwoFactor;
1199
+ if (user.hasOwnProperty('mfaEnrolled') && !user.mfaEnrolled) {
1200
+ setMfaState = {
1201
+ mfaState: {
1202
+ step: exports.MFAStep.verify,
1203
+ qrCode: user.qrCode,
1204
+ recoveryCode: user.recoveryCode,
1205
+ mfaToken: user.mfaToken,
1206
+ loading: false,
1207
+ },
1208
+ };
1209
+ step = exports.LoginStep.forceTwoFactor;
1210
+ }
1211
+ }
1212
+ const isAuthenticated = step === exports.LoginStep.success && !!user.accessToken;
1213
+ const loggedInUser = step === exports.LoginStep.success && step === exports.LoginStep.success ? user : undefined;
1214
+ let allowRememberDevice = { isAllowedToRemember: false, mfaDeviceExpiration: 0 };
1215
+ if (user.mfaRequired && user.mfaToken) {
1216
+ allowRememberDevice = yield effects.call(restApi.api.auth.checkIfAllowToRememberMfaDevice, user.mfaToken);
1217
+ }
1218
+ const { isAllowedToRemember, mfaDeviceExpiration } = allowRememberDevice;
1219
+ yield effects.put(actions.setState(Object.assign(Object.assign({ user: loggedInUser, isAuthenticated }, setMfaState), { loginState: {
1220
+ email,
1221
+ loading: false,
1222
+ error: undefined,
1223
+ mfaToken: user.mfaToken,
1224
+ step,
1225
+ tenants: [],
1226
+ tenantsLoading: true,
1227
+ allowRememberMfaDevice: isAllowedToRemember,
1228
+ mfaDeviceExpiration,
1229
+ } })));
1230
+ if (step === exports.LoginStep.success) {
1231
+ yield effects.put(actions.loadTenants());
1232
+ yield afterAuthNavigation();
1233
+ }
1234
+ callback === null || callback === void 0 ? void 0 : callback(true);
1235
+ }
1236
+ catch (e) {
1237
+ restApi.ContextHolder.setAccessToken(null);
1238
+ restApi.ContextHolder.setUser(null);
1239
+ yield effects.put(actions.setLoginState({
1240
+ email,
1241
+ error: e.message,
1242
+ loading: false,
1243
+ }));
1244
+ }
1245
+ }
1246
+ function* loginWithMfa({ payload: { mfaToken, value, rememberDevice, callback }, }) {
1247
+ yield effects.put(actions.setLoginState({ loading: true }));
1248
+ try {
1249
+ const user = yield effects.call(restApi.api.auth.loginWithMfa, { mfaToken, value, rememberDevice });
1250
+ const step = exports.LoginStep.success;
1251
+ yield effects.put(actions.setState({
1252
+ loginState: { loading: false, error: undefined, step, tenantsLoading: true, tenants: [] },
1253
+ user,
1254
+ isAuthenticated: true,
1255
+ }));
1256
+ yield effects.put(actions.loadTenants());
1257
+ callback === null || callback === void 0 ? void 0 : callback(true);
1258
+ if (step === exports.LoginStep.success) {
1259
+ yield afterAuthNavigation();
1260
+ }
1261
+ }
1262
+ catch (e) {
1263
+ yield effects.put(actions.setLoginState({ error: e.message, loading: false }));
1264
+ callback === null || callback === void 0 ? void 0 : callback(false, e);
1265
+ }
1266
+ }
1267
+ function* recoverMfa({ payload }) {
1268
+ yield effects.put(actions.setLoginState({ loading: true }));
1269
+ try {
1270
+ yield effects.call(restApi.api.auth.recoverMfaToken, payload);
1271
+ yield effects.put(actions.setLoginState({ loading: false, error: undefined, step: exports.LoginStep.preLogin }));
1272
+ yield effects.put(actions.setState({ user: undefined, isAuthenticated: false }));
1273
+ }
1274
+ catch (e) {
1275
+ yield effects.put(actions.setLoginState({ error: e.message, loading: false }));
1276
+ }
1277
+ }
1278
+ function* logout({ payload }) {
1279
+ yield effects.put(actions.setState({ isLoading: true }));
1280
+ try {
1281
+ yield effects.call(restApi.api.auth.logout);
1282
+ }
1283
+ catch (_a) {
1284
+ }
1285
+ yield effects.put(actions.resetState());
1286
+ yield effects.put(actions.requestAuthorize(true));
1287
+ payload === null || payload === void 0 ? void 0 : payload();
1288
+ }
1289
+ function* silentLogout({ payload }) {
1290
+ try {
1291
+ yield effects.call(restApi.api.auth.logout);
1292
+ }
1293
+ catch (_a) {
1294
+ }
1295
+ setTimeout(() => payload === null || payload === void 0 ? void 0 : payload(), 500);
1296
+ }
1297
+ function* loginSagas() {
1298
+ yield effects.takeLeading(actions.requestAuthorize, requestAuthorize);
1299
+ yield effects.takeLeading(actions.requestHostedLoginAuthorize, requestHostedLoginAuthorize);
1300
+ yield effects.takeLeading(actions.handleHostedLoginCallback, handleHostedLoginCallback);
1301
+ yield effects.takeLeading(actions.preLogin, preLogin);
1302
+ yield effects.takeLeading(actions.postLogin, postLogin);
1303
+ yield effects.takeLeading(actions.login, login);
1304
+ yield effects.takeLeading(actions.logout, logout);
1305
+ yield effects.takeLeading(actions.silentLogout, silentLogout);
1306
+ yield effects.takeLeading(actions.loginWithMfa, loginWithMfa);
1307
+ yield effects.takeLeading(actions.recoverMfa, recoverMfa);
1308
+ yield effects.takeLeading(actions.passwordlessPreLogin, passwordlessPreLogin);
1309
+ yield effects.takeLeading(actions.passwordlessPostLogin, passwordlessPostLogin);
1310
+ yield effects.takeLeading(actions.verifyInviteToken, verifyInviteToken);
1311
+ }
1312
+ /*********************************
1313
+ * Preview Sagas
1314
+ *********************************/
1315
+ function* requestAuthorizeMock({ payload: firstTime }) {
1316
+ if (firstTime) {
1317
+ yield effects.put(actions.setState({ isLoading: true }));
1318
+ }
1319
+ const user = userDemo;
1320
+ yield effects.put(actions.loadTenants());
1321
+ yield effects.put(actions.setState({ user, isAuthenticated: true, isLoading: false }));
1322
+ }
1323
+ function* loginSagasMock() {
1324
+ yield effects.takeLeading(actions.requestAuthorize, requestAuthorizeMock);
1325
+ yield effects.takeLeading(actions.afterAuthNavigation, afterAuthNavigation);
1326
+ }
1327
+
1328
+ function* loadSSOConfigurations() {
1329
+ var _a, _b;
1330
+ try {
1331
+ yield effects.put(actions.setSSOState({ loading: true }));
1332
+ const samlConfiguration = yield effects.call(restApi.api.auth.getSamlConfiguration);
1333
+ const oidcConfiguration = yield effects.call(restApi.api.auth.getOidcConfiguration);
1334
+ const samlMetadata = yield effects.call(restApi.api.metadata.getSamlMetadata);
1335
+ samlConfiguration.acsUrl = (_a = samlMetadata === null || samlMetadata === void 0 ? void 0 : samlMetadata.configuration) === null || _a === void 0 ? void 0 : _a.acsUrl;
1336
+ samlConfiguration.spEntityId = (_b = samlMetadata === null || samlMetadata === void 0 ? void 0 : samlMetadata.configuration) === null || _b === void 0 ? void 0 : _b.spEntityId;
1337
+ samlConfiguration.isSamlActive = samlMetadata === null || samlMetadata === void 0 ? void 0 : samlMetadata.isActive;
1338
+ yield effects.put(actions.setSSOState({ samlConfiguration, oidcConfiguration, loading: false, firstLoad: false }));
1339
+ }
1340
+ catch (e) {
1341
+ yield effects.put(actions.setSSOState({ error: e.message, loading: false }));
1342
+ }
1343
+ }
1344
+ function* saveSSOConfigurationsFile({ payload: configFile }) {
1345
+ const oldSamlConfiguration = yield effects.select((state) => state.auth.ssoState.samlConfiguration);
1346
+ const loaderKey = 'saving';
1347
+ yield effects.put(actions.setSSOState({ error: undefined, [loaderKey]: true }));
1348
+ try {
1349
+ const metadata = yield readFileAsText(configFile[0]);
1350
+ const newSamlConfiguration = yield effects.call(restApi.api.auth.updateSamlVendorMetadata, { metadata });
1351
+ newSamlConfiguration.isSamlActive = oldSamlConfiguration === null || oldSamlConfiguration === void 0 ? void 0 : oldSamlConfiguration.isSamlActive;
1352
+ yield effects.put(actions.setSSOState({ samlConfiguration: newSamlConfiguration, error: undefined, [loaderKey]: false }));
1353
+ }
1354
+ catch (e) {
1355
+ yield effects.put(actions.setSSOState({ samlConfiguration: oldSamlConfiguration, error: e.message, [loaderKey]: false }));
1356
+ }
1357
+ }
1358
+ function* saveSSOConfigurationsFileWithCallback({ payload }) {
1359
+ const { configFile, callback } = payload;
1360
+ const oldSamlConfiguration = yield effects.select((state) => state.auth.ssoState.samlConfiguration);
1361
+ const loaderKey = 'saving';
1362
+ yield effects.put(actions.setSSOState({ error: undefined, [loaderKey]: true }));
1363
+ try {
1364
+ const metadata = yield readFileAsText(configFile);
1365
+ const newSamlConfiguration = yield effects.call(restApi.api.auth.updateSamlVendorMetadata, { metadata });
1366
+ newSamlConfiguration.isSamlActive = oldSamlConfiguration === null || oldSamlConfiguration === void 0 ? void 0 : oldSamlConfiguration.isSamlActive;
1367
+ yield effects.put(actions.setSSOState({ samlConfiguration: newSamlConfiguration, error: undefined, [loaderKey]: false }));
1368
+ callback === null || callback === void 0 ? void 0 : callback(true);
1369
+ }
1370
+ catch (e) {
1371
+ yield effects.put(actions.setSSOState({ samlConfiguration: oldSamlConfiguration, error: e.message, [loaderKey]: false }));
1372
+ callback === null || callback === void 0 ? void 0 : callback(null, e);
1373
+ }
1374
+ }
1375
+ function* saveSSOConfigurations({ payload }) {
1376
+ var _a, _b;
1377
+ const { callback, samlVendor } = payload, newSamlConfiguration = tslib.__rest(payload, ["callback", "samlVendor"]);
1378
+ const oldSamlConfiguration = yield effects.select((state) => state.auth.ssoState.samlConfiguration);
1379
+ const samlConfiguration = Object.assign(Object.assign({}, oldSamlConfiguration), newSamlConfiguration);
1380
+ let loaderKey = 'saving';
1381
+ if ((samlConfiguration === null || samlConfiguration === void 0 ? void 0 : samlConfiguration.enabled) !== oldSamlConfiguration.enabled) {
1382
+ loaderKey = 'loading';
1383
+ }
1384
+ try {
1385
+ const firstTimeConfigure = !(samlConfiguration === null || samlConfiguration === void 0 ? void 0 : samlConfiguration.domain);
1386
+ if (firstTimeConfigure) {
1387
+ yield effects.put(actions.setSSOState({ samlConfiguration: Object.assign(Object.assign({}, oldSamlConfiguration), samlConfiguration) }));
1388
+ return;
1389
+ }
1390
+ else {
1391
+ yield effects.put(actions.setSSOState({ error: undefined, [loaderKey]: true }));
1392
+ }
1393
+ if (payload.type === exports.SamlVendors.Saml) {
1394
+ const samlMetadata = yield effects.call(restApi.api.metadata.getSamlMetadata);
1395
+ samlConfiguration.acsUrl = (_a = samlMetadata === null || samlMetadata === void 0 ? void 0 : samlMetadata.configuration) === null || _a === void 0 ? void 0 : _a.acsUrl;
1396
+ samlConfiguration.spEntityId = (_b = samlMetadata === null || samlMetadata === void 0 ? void 0 : samlMetadata.configuration) === null || _b === void 0 ? void 0 : _b.spEntityId;
1397
+ }
1398
+ const updateSamlConfiguration = omitProps(samlConfiguration, [
1399
+ 'validated',
1400
+ 'generatedVerification',
1401
+ 'createdAt',
1402
+ 'updatedAt',
1403
+ ]);
1404
+ if ((oldSamlConfiguration === null || oldSamlConfiguration === void 0 ? void 0 : oldSamlConfiguration.domain) !== (updateSamlConfiguration === null || updateSamlConfiguration === void 0 ? void 0 : updateSamlConfiguration.domain)) {
1405
+ updateSamlConfiguration.ssoEndpoint = '';
1406
+ updateSamlConfiguration.publicCertificate = '';
1407
+ updateSamlConfiguration.signRequest = false;
1408
+ }
1409
+ updateSamlConfiguration.type = samlVendor === null || samlVendor === void 0 ? void 0 : samlVendor.toLowerCase();
1410
+ const newSamlConfiguration = yield effects.call(restApi.api.auth.updateSamlConfiguration, updateSamlConfiguration);
1411
+ newSamlConfiguration.isSamlActive = oldSamlConfiguration === null || oldSamlConfiguration === void 0 ? void 0 : oldSamlConfiguration.isSamlActive;
1412
+ yield effects.put(actions.setSSOState({ samlConfiguration: newSamlConfiguration, error: undefined, [loaderKey]: false }));
1413
+ callback === null || callback === void 0 ? void 0 : callback(true);
1414
+ }
1415
+ catch (e) {
1416
+ yield effects.put(actions.setSSOState({ samlConfiguration: oldSamlConfiguration, error: e.message, [loaderKey]: false }));
1417
+ callback === null || callback === void 0 ? void 0 : callback(null, e);
1418
+ }
1419
+ }
1420
+ function* validateSSODomain({ payload: { callback } = {} }) {
1421
+ const samlConfiguration = yield effects.select((state) => state.auth.ssoState.samlConfiguration);
1422
+ try {
1423
+ yield effects.put(actions.setSSOState({ error: undefined, saving: true }));
1424
+ yield effects.call(restApi.api.auth.validateSamlDomain);
1425
+ yield effects.put(actions.setSSOState({
1426
+ samlConfiguration: Object.assign(Object.assign({}, samlConfiguration), { validated: true }),
1427
+ error: undefined,
1428
+ saving: false,
1429
+ }));
1430
+ callback === null || callback === void 0 ? void 0 : callback(true);
1431
+ }
1432
+ catch (e) {
1433
+ yield effects.put(actions.setSSOState({
1434
+ samlConfiguration: Object.assign(Object.assign({}, samlConfiguration), { validated: false }),
1435
+ error: e.message,
1436
+ saving: false,
1437
+ }));
1438
+ callback === null || callback === void 0 ? void 0 : callback(null, e);
1439
+ }
1440
+ }
1441
+ function* getAuthorizationRoles() {
1442
+ try {
1443
+ const data = yield effects.call(restApi.api.auth.getSamlRoles);
1444
+ const groupsData = yield effects.call(restApi.api.auth.getSamlRolesGroups);
1445
+ yield effects.put(actions.setSSOState({
1446
+ authorizationRoles: data.roleIds,
1447
+ rolesGroups: groupsData,
1448
+ error: undefined,
1449
+ }));
1450
+ }
1451
+ catch (e) {
1452
+ yield effects.put(actions.setSSOState({
1453
+ error: e.message,
1454
+ }));
1455
+ }
1456
+ }
1457
+ function* updateRolesGroups(groups) {
1458
+ try {
1459
+ yield effects.all(groups.map((group) => effects.call(restApi.api.auth.updateSamlGroup, { id: group.id, roleIds: group.roleIds, group: group.group })));
1460
+ }
1461
+ catch (e) {
1462
+ yield effects.put(actions.setSSOState({
1463
+ error: e.message,
1464
+ }));
1465
+ }
1466
+ }
1467
+ function* updateAuthorizationRoles({ payload: { callback, authorizationRoles, groups }, }) {
1468
+ try {
1469
+ yield effects.put(actions.setSSOState({ error: undefined, saving: true }));
1470
+ yield effects.call(restApi.api.auth.updateSamlRoles, { roleIds: authorizationRoles });
1471
+ if (groups) {
1472
+ yield updateRolesGroups(groups);
1473
+ }
1474
+ yield getAuthorizationRoles();
1475
+ yield effects.put(actions.setSSOState({ error: undefined, saving: false }));
1476
+ callback === null || callback === void 0 ? void 0 : callback(true);
1477
+ }
1478
+ catch (e) {
1479
+ yield effects.put(actions.setSSOState({
1480
+ error: e.message,
1481
+ saving: false,
1482
+ }));
1483
+ callback === null || callback === void 0 ? void 0 : callback(null, e);
1484
+ }
1485
+ }
1486
+ function* deleteSamlGroupFunction({ payload: { callback, id } }) {
1487
+ try {
1488
+ yield effects.put(actions.setSSOState({ error: undefined, saving: true }));
1489
+ yield effects.call(restApi.api.auth.deleteSamlGroup, { id });
1490
+ yield getAuthorizationRoles();
1491
+ yield effects.put(actions.setSSOState({ error: undefined, saving: false }));
1492
+ callback === null || callback === void 0 ? void 0 : callback(true);
1493
+ }
1494
+ catch (e) {
1495
+ yield effects.put(actions.setSSOState({
1496
+ error: e.message,
1497
+ saving: false,
1498
+ }));
1499
+ callback === null || callback === void 0 ? void 0 : callback(null, e);
1500
+ }
1501
+ }
1502
+ function* createSamlGroupFunction({ payload: { group, roleIds, callback } }) {
1503
+ try {
1504
+ yield effects.put(actions.setSSOState({ error: undefined, saving: true }));
1505
+ yield effects.call(restApi.api.auth.createSamlGroup, { group, roleIds });
1506
+ yield getAuthorizationRoles();
1507
+ yield effects.put(actions.setSSOState({ error: undefined, saving: false }));
1508
+ callback === null || callback === void 0 ? void 0 : callback(true);
1509
+ }
1510
+ catch (e) {
1511
+ yield effects.put(actions.setSSOState({
1512
+ error: e.message,
1513
+ saving: false,
1514
+ }));
1515
+ callback === null || callback === void 0 ? void 0 : callback(null, e);
1516
+ }
1517
+ }
1518
+ function* oidcPostloginFunction({ payload }) {
1519
+ var _a;
1520
+ const data = { code: payload.code, redirectUri: payload.redirectUri, RelayState: payload.state };
1521
+ try {
1522
+ yield effects.put(actions.setSSOState({ loading: true }));
1523
+ yield effects.call(restApi.api.auth.oidcPostLoginV2, data);
1524
+ yield refreshToken();
1525
+ yield effects.put(actions.setSSOState({ loading: false }));
1526
+ }
1527
+ catch (e) {
1528
+ yield effects.put(actions.setSSOState({ loading: false, error: (_a = e.message) !== null && _a !== void 0 ? _a : 'Failed to authenticate', firstLoad: false }));
1529
+ }
1530
+ }
1531
+ function* ssoSagas$1() {
1532
+ yield effects.takeEvery(actions.loadSSOConfigurations, loadSSOConfigurations);
1533
+ yield effects.takeEvery(actions.saveSSOConfigurations, saveSSOConfigurations);
1534
+ yield effects.takeEvery(actions.saveSSOConfigurationsFile, saveSSOConfigurationsFile);
1535
+ yield effects.takeEvery(actions.saveSSOConfigurationsFileWithCallback, saveSSOConfigurationsFileWithCallback);
1536
+ yield effects.takeEvery(actions.validateSSODomain, validateSSODomain);
1537
+ yield effects.takeEvery(actions.loadSSOAuthorizationRoles, getAuthorizationRoles);
1538
+ yield effects.takeEvery(actions.updateSSOAuthorizationRoles, updateAuthorizationRoles);
1539
+ yield effects.takeEvery(actions.deleteSamlGroup, deleteSamlGroupFunction);
1540
+ yield effects.takeEvery(actions.createSamlGroup, createSamlGroupFunction);
1541
+ yield effects.takeEvery(actions.oidcPostlogin, oidcPostloginFunction);
1542
+ }
1543
+ /*********************************
1544
+ * Preview Sagas
1545
+ *********************************/
1546
+ function* loadSSOConfigurationsMock() {
1547
+ yield effects.put(actions.setSSOState({ loading: true }));
1548
+ yield delay();
1549
+ yield effects.put(actions.setSSOState({ samlConfiguration: samlConfigurationDemo, loading: false, firstLoad: false }));
1550
+ }
1551
+ function* saveSSOConfigurationsFileMock({ payload: configFile }) {
1552
+ const loaderKey = 'saving';
1553
+ yield effects.put(actions.setSSOState({ error: undefined, [loaderKey]: true }));
1554
+ const oldSamlConfiguration = yield effects.select((state) => state.auth.ssoState.samlConfiguration);
1555
+ const newSamlConfiguration = Object.assign(Object.assign(Object.assign({}, oldSamlConfiguration), { enabled: true }), configFile[0]);
1556
+ yield effects.put(actions.setSSOState({ samlConfiguration: newSamlConfiguration, error: undefined, [loaderKey]: false }));
1557
+ }
1558
+ function* saveSSOConfigurationsMock({ payload }) {
1559
+ var _a, _b;
1560
+ const { callback, samlVendor } = payload, newSamlConfiguration = tslib.__rest(payload, ["callback", "samlVendor"]);
1561
+ const oldSamlConfiguration = ssoStateDemo.samlConfiguration;
1562
+ const samlConfiguration = Object.assign(Object.assign({}, oldSamlConfiguration), newSamlConfiguration);
1563
+ let loaderKey = 'saving';
1564
+ if ((samlConfiguration === null || samlConfiguration === void 0 ? void 0 : samlConfiguration.enabled) !== oldSamlConfiguration.enabled) {
1565
+ loaderKey = 'loading';
1566
+ }
1567
+ const firstTimeConfigure = !(samlConfiguration === null || samlConfiguration === void 0 ? void 0 : samlConfiguration.domain);
1568
+ if (firstTimeConfigure) {
1569
+ yield effects.put(actions.setSSOState({ samlConfiguration: Object.assign(Object.assign({}, oldSamlConfiguration), samlConfiguration) }));
1570
+ return;
1571
+ }
1572
+ else {
1573
+ yield effects.put(actions.setSSOState({ error: undefined, [loaderKey]: true }));
1574
+ }
1575
+ yield delay();
1576
+ samlConfiguration.acsUrl = (_a = samlMetadataDemo === null || samlMetadataDemo === void 0 ? void 0 : samlMetadataDemo.configuration) === null || _a === void 0 ? void 0 : _a.acsUrl;
1577
+ samlConfiguration.spEntityId = (_b = samlMetadataDemo === null || samlMetadataDemo === void 0 ? void 0 : samlMetadataDemo.configuration) === null || _b === void 0 ? void 0 : _b.spEntityId;
1578
+ const updateSamlConfiguration = omitProps(samlConfiguration, [
1579
+ 'validated',
1580
+ 'generatedVerification',
1581
+ 'createdAt',
1582
+ 'updatedAt',
1583
+ ]);
1584
+ if ((oldSamlConfiguration === null || oldSamlConfiguration === void 0 ? void 0 : oldSamlConfiguration.domain) !== (updateSamlConfiguration === null || updateSamlConfiguration === void 0 ? void 0 : updateSamlConfiguration.domain)) {
1585
+ updateSamlConfiguration.ssoEndpoint = '';
1586
+ updateSamlConfiguration.publicCertificate = '';
1587
+ updateSamlConfiguration.signRequest = false;
1588
+ }
1589
+ updateSamlConfiguration.type = samlVendor === null || samlVendor === void 0 ? void 0 : samlVendor.toLowerCase();
1590
+ yield delay();
1591
+ yield effects.put(actions.setSSOState({ samlConfiguration: updateSamlConfiguration, error: undefined, [loaderKey]: false }));
1592
+ callback === null || callback === void 0 ? void 0 : callback(true);
1593
+ }
1594
+ function* validateSSODomainMock({ payload: { callback } = {} }) {
1595
+ const samlConfiguration = ssoStateDemo.samlConfiguration;
1596
+ yield effects.put(actions.setSSOState({ error: undefined, saving: true }));
1597
+ yield delay();
1598
+ yield effects.put(actions.setSSOState({
1599
+ samlConfiguration: Object.assign(Object.assign({}, samlConfiguration), { validated: true }),
1600
+ error: undefined,
1601
+ saving: false,
1602
+ }));
1603
+ callback === null || callback === void 0 ? void 0 : callback(true);
1604
+ }
1605
+ function* getAuthorizationRolesMock() {
1606
+ yield delay();
1607
+ const data = { roleIds: ['1', '2', '3'] };
1608
+ yield effects.put(actions.setSSOState({
1609
+ authorizationRoles: data.roleIds,
1610
+ error: undefined,
1611
+ }));
1612
+ }
1613
+ function* updateAuthorizationRolesMock({ payload: { callback, authorizationRoles }, }) {
1614
+ yield effects.put(actions.setSSOState({ error: undefined, saving: true }));
1615
+ yield delay();
1616
+ yield effects.put(actions.setSSOState({ authorizationRoles, error: undefined, saving: false }));
1617
+ callback === null || callback === void 0 ? void 0 : callback(true);
1618
+ }
1619
+ function* ssoSagasMock() {
1620
+ yield effects.takeEvery(actions.loadSSOConfigurations, loadSSOConfigurationsMock);
1621
+ yield effects.takeEvery(actions.saveSSOConfigurations, saveSSOConfigurationsMock);
1622
+ yield effects.takeEvery(actions.saveSSOConfigurationsFile, saveSSOConfigurationsFileMock);
1623
+ yield effects.takeEvery(actions.validateSSODomain, validateSSODomainMock);
1624
+ yield effects.takeEvery(actions.loadSSOAuthorizationRoles, getAuthorizationRolesMock);
1625
+ yield effects.takeEvery(actions.updateSSOAuthorizationRoles, updateAuthorizationRolesMock);
1626
+ }
1627
+
1628
+ function* loadOidc() {
1629
+ try {
1630
+ const oidcConfiguration = yield effects.call(restApi.api.auth.getOidcConfiguration);
1631
+ return oidcConfiguration;
1632
+ }
1633
+ catch (e) {
1634
+ return null;
1635
+ }
1636
+ }
1637
+ function* loadSaml() {
1638
+ try {
1639
+ const samlMetadata = yield effects.call(restApi.api.metadata.getSamlMetadata);
1640
+ return samlMetadata;
1641
+ }
1642
+ catch (e) {
1643
+ return null;
1644
+ }
1645
+ }
1646
+ function* loadSSOConfigurationsV2() {
1647
+ try {
1648
+ yield effects.put(actions.setSSOLoader({ key: exports.SSOStateKeys.LOAD_SSO_CONFIGURATIONS, value: true }));
1649
+ const [oidcConfiguration, samlMetadata] = yield effects.all([effects.call(loadOidc), effects.call(loadSaml)]);
1650
+ const ssoConfigurations = yield effects.call(restApi.api.auth.getSSOConfigurations);
1651
+ yield effects.put(actions.setSSOState({
1652
+ ssoConfigurations,
1653
+ oidcConfiguration,
1654
+ samlMetadata
1655
+ }));
1656
+ }
1657
+ catch (error) {
1658
+ yield effects.put(actions.setSSOError({ key: exports.SSOStateKeys.LOAD_SSO_CONFIGURATIONS, value: error.message }));
1659
+ }
1660
+ finally {
1661
+ yield effects.put(actions.setSSOLoader({ key: exports.SSOStateKeys.LOAD_SSO_CONFIGURATIONS, value: false }));
1662
+ }
1663
+ }
1664
+ function* saveSSOConfigurationV2({ payload }) {
1665
+ var _a;
1666
+ yield effects.put(actions.setSSOLoader({ key: exports.SSOStateKeys.SAVE_SSO_CONFIGURATION, value: true }));
1667
+ const { callback } = payload, ssoConfiguration = tslib.__rest(payload, ["callback"]);
1668
+ const ssoConfigurations = yield effects.select((state) => state.auth.ssoState.ssoConfigurations);
1669
+ try {
1670
+ const newSsoConfiguration = yield effects.call(restApi.api.auth.createSSOConfiguration, Object.assign(Object.assign({}, ssoConfiguration), { enabled: (_a = ssoConfiguration.enabled) !== null && _a !== void 0 ? _a : false }));
1671
+ yield effects.put(actions.setSSOState({ ssoConfigurations: [...ssoConfigurations, newSsoConfiguration] }));
1672
+ callback === null || callback === void 0 ? void 0 : callback(newSsoConfiguration);
1673
+ }
1674
+ catch (error) {
1675
+ yield effects.put(actions.setSSOError({ key: exports.SSOStateKeys.SAVE_SSO_CONFIGURATION, value: error.message }));
1676
+ callback === null || callback === void 0 ? void 0 : callback(null, error);
1677
+ }
1678
+ finally {
1679
+ yield effects.put(actions.setSSOLoader({ key: exports.SSOStateKeys.SAVE_SSO_CONFIGURATION, value: false }));
1680
+ }
1681
+ }
1682
+ function* saveSSOConfigurationByMetadata({ payload }) {
1683
+ yield effects.put(actions.setSSOLoader({ key: exports.SSOStateKeys.SAVE_SSO_CONFIGURATION_BY_METADATA, value: true }));
1684
+ const { configFile, callback } = payload;
1685
+ const ssoConfigurations = yield effects.select((state) => state.auth.ssoState.ssoConfigurations);
1686
+ try {
1687
+ const metadata = yield readFileAsText(configFile);
1688
+ const newSsoConfiguration = yield effects.call(restApi.api.auth.createSSOConfigurationByMetadata, { metadata });
1689
+ yield effects.put(actions.setSSOState({ ssoConfigurations: [...ssoConfigurations, newSsoConfiguration] }));
1690
+ callback === null || callback === void 0 ? void 0 : callback(newSsoConfiguration);
1691
+ }
1692
+ catch (error) {
1693
+ yield effects.put(actions.setSSOError({ key: exports.SSOStateKeys.SAVE_SSO_CONFIGURATION_BY_METADATA, value: error.message }));
1694
+ callback === null || callback === void 0 ? void 0 : callback(null, error);
1695
+ }
1696
+ finally {
1697
+ yield effects.put(actions.setSSOLoader({ key: exports.SSOStateKeys.SAVE_SSO_CONFIGURATION_BY_METADATA, value: false }));
1698
+ }
1699
+ }
1700
+ function* updateSSOConfiguration({ payload }) {
1701
+ yield effects.put(actions.setSSOLoader({ key: exports.SSOStateKeys.UPDATE_SSO_CONFIGURATION, value: true }));
1702
+ const { callback, ssoConfigId } = payload, ssoConfiguration = tslib.__rest(payload, ["callback", "ssoConfigId"]);
1703
+ const ssoConfigurations = yield effects.select((state) => state.auth.ssoState.ssoConfigurations);
1704
+ try {
1705
+ const newSsoConfiguration = yield effects.call(restApi.api.auth.updateSSOConfiguration, ssoConfigId, ssoConfiguration);
1706
+ const newSsoConfigurations = ssoConfigurations.map((ssoConfig) => ssoConfig.id === ssoConfigId ? newSsoConfiguration : ssoConfig);
1707
+ yield effects.put(actions.setSSOState({ ssoConfigurations: newSsoConfigurations }));
1708
+ callback === null || callback === void 0 ? void 0 : callback(newSsoConfiguration);
1709
+ }
1710
+ catch (error) {
1711
+ yield effects.put(actions.setSSOError({ key: exports.SSOStateKeys.UPDATE_SSO_CONFIGURATION, value: error.message }));
1712
+ callback === null || callback === void 0 ? void 0 : callback(null, error);
1713
+ }
1714
+ finally {
1715
+ yield effects.put(actions.setSSOLoader({ key: exports.SSOStateKeys.UPDATE_SSO_CONFIGURATION, value: false }));
1716
+ }
1717
+ }
1718
+ function* updateSSOConfigurationByMetadata({ payload }) {
1719
+ yield effects.put(actions.setSSOLoader({ key: exports.SSOStateKeys.UPDATE_SSO_CONFIGURATION_BY_METADATA, value: true }));
1720
+ const { callback, ssoConfigId, configFile } = payload;
1721
+ const ssoConfigurations = yield effects.select((state) => state.auth.ssoState.ssoConfigurations);
1722
+ try {
1723
+ const metadata = yield readFileAsText(configFile);
1724
+ const newSsoConfiguration = yield effects.call(restApi.api.auth.updateSSOConfigurationByMetadata, ssoConfigId, { metadata });
1725
+ const newSsoConfigurations = ssoConfigurations.map((ssoConfig) => ssoConfig.id === ssoConfigId ? newSsoConfiguration : ssoConfig);
1726
+ yield effects.put(actions.setSSOState({ ssoConfigurations: newSsoConfigurations }));
1727
+ callback === null || callback === void 0 ? void 0 : callback(newSsoConfiguration);
1728
+ }
1729
+ catch (error) {
1730
+ yield effects.put(actions.setSSOError({ key: exports.SSOStateKeys.UPDATE_SSO_CONFIGURATION, value: error.message }));
1731
+ callback === null || callback === void 0 ? void 0 : callback(null, error);
1732
+ }
1733
+ finally {
1734
+ yield effects.put(actions.setSSOLoader({ key: exports.SSOStateKeys.UPDATE_SSO_CONFIGURATION, value: false }));
1735
+ }
1736
+ }
1737
+ function* deleteSSOConfiguration({ payload }) {
1738
+ yield effects.put(actions.setSSOLoader({ key: exports.SSOStateKeys.DELETE_SSO_CONFIGURATION, value: true }));
1739
+ const { ssoConfigId, callback } = payload;
1740
+ const ssoConfigurations = yield effects.select((state) => state.auth.ssoState.ssoConfigurations);
1741
+ try {
1742
+ yield effects.call(restApi.api.auth.deleteSSOConfiguration, ssoConfigId);
1743
+ yield effects.put(actions.setSSOState({ ssoConfigurations: ssoConfigurations.filter(({ id }) => id !== ssoConfigId) }));
1744
+ callback === null || callback === void 0 ? void 0 : callback(true);
1745
+ }
1746
+ catch (error) {
1747
+ yield effects.put(actions.setSSOError({ key: exports.SSOStateKeys.DELETE_SSO_CONFIGURATION, value: error.message }));
1748
+ callback === null || callback === void 0 ? void 0 : callback(null, error);
1749
+ }
1750
+ finally {
1751
+ yield effects.put(actions.setSSOLoader({ key: exports.SSOStateKeys.DELETE_SSO_CONFIGURATION, value: false }));
1752
+ }
1753
+ }
1754
+ function* saveSSODomain({ payload }) {
1755
+ const { callback, ssoConfigId } = payload, body = tslib.__rest(payload, ["callback", "ssoConfigId"]);
1756
+ yield effects.put(actions.setSSOLoader({ key: exports.SSOStateKeys.SAVE_SSO_DOMAIN, value: true }));
1757
+ const ssoConfigurations = yield effects.select((state) => state.auth.ssoState.ssoConfigurations);
1758
+ try {
1759
+ const domain = yield effects.call(restApi.api.auth.createSSODomain, ssoConfigId, body);
1760
+ const newSsoConfigurations = ssoConfigurations.map((ssoConfig) => {
1761
+ if (ssoConfig.id === ssoConfigId) {
1762
+ return Object.assign(Object.assign({}, ssoConfig), { domains: [...ssoConfig.domains, domain] });
1763
+ }
1764
+ return ssoConfig;
1765
+ });
1766
+ yield effects.put(actions.setSSOState({ ssoConfigurations: newSsoConfigurations }));
1767
+ callback === null || callback === void 0 ? void 0 : callback(domain);
1768
+ }
1769
+ catch (error) {
1770
+ yield effects.put(actions.setSSOError({ key: exports.SSOStateKeys.SAVE_SSO_DOMAIN, value: error.message }));
1771
+ callback === null || callback === void 0 ? void 0 : callback(null, error);
1772
+ }
1773
+ finally {
1774
+ yield effects.put(actions.setSSOLoader({ key: exports.SSOStateKeys.SAVE_SSO_DOMAIN, value: false }));
1775
+ }
1776
+ }
1777
+ function* deleteSSODomain({ payload }) {
1778
+ const { ssoConfigId, domainId, callback } = payload;
1779
+ yield effects.put(actions.setSSOLoader({ key: exports.SSOStateKeys.DELETE_SSO_DOMAIN, value: true }));
1780
+ const ssoConfigurations = yield effects.select((state) => state.auth.ssoState.ssoConfigurations);
1781
+ try {
1782
+ yield effects.call(restApi.api.auth.deleteSSODomain, ssoConfigId, domainId);
1783
+ const newSsoConfigurations = ssoConfigurations.map((ssoConfig) => {
1784
+ if (ssoConfig.id === ssoConfigId) {
1785
+ return Object.assign(Object.assign({}, ssoConfig), { domains: ssoConfig.domains.filter(({ id }) => id !== domainId) });
1786
+ }
1787
+ return ssoConfig;
1788
+ });
1789
+ yield effects.put(actions.setSSOState({ ssoConfigurations: newSsoConfigurations }));
1790
+ callback === null || callback === void 0 ? void 0 : callback(true);
1791
+ }
1792
+ catch (error) {
1793
+ yield effects.put(actions.setSSOError({ key: exports.SSOStateKeys.DELETE_SSO_DOMAIN, value: error.message }));
1794
+ callback === null || callback === void 0 ? void 0 : callback(null, error);
1795
+ }
1796
+ finally {
1797
+ yield effects.put(actions.setSSOLoader({ key: exports.SSOStateKeys.DELETE_SSO_DOMAIN, value: false }));
1798
+ }
1799
+ }
1800
+ function* validateSSODomainV2({ payload }) {
1801
+ const { callback, domainId, ssoConfigId } = payload;
1802
+ yield effects.put(actions.setSSOLoader({ key: exports.SSOStateKeys.VALIDATE_SSO_DOMAIN, value: true }));
1803
+ const ssoConfigurations = yield effects.select((state) => state.auth.ssoState.ssoConfigurations);
1804
+ try {
1805
+ yield effects.call(restApi.api.auth.validateSSODomain, ssoConfigId, domainId);
1806
+ const newSsoConfigurations = ssoConfigurations.map((ssoConfig) => {
1807
+ if (ssoConfig.id === ssoConfigId) {
1808
+ return Object.assign(Object.assign({}, ssoConfig), { domains: ssoConfig.domains.map((ssoDomain) => ssoDomain.id === domainId ? Object.assign(Object.assign({}, ssoDomain), { validated: true }) : ssoDomain) });
1809
+ }
1810
+ return ssoConfig;
1811
+ });
1812
+ yield effects.put(actions.setSSOState({ ssoConfigurations: newSsoConfigurations }));
1813
+ callback === null || callback === void 0 ? void 0 : callback(true);
1814
+ }
1815
+ catch (error) {
1816
+ yield effects.put(actions.setSSOError({ key: exports.SSOStateKeys.VALIDATE_SSO_DOMAIN, value: error.message }));
1817
+ callback === null || callback === void 0 ? void 0 : callback(null, error);
1818
+ }
1819
+ finally {
1820
+ yield effects.put(actions.setSSOLoader({ key: exports.SSOStateKeys.VALIDATE_SSO_DOMAIN, value: false }));
1821
+ }
1822
+ }
1823
+ function* setSSODefaultRoles({ payload: { callback, ssoConfigId, roleIds }, }) {
1824
+ yield effects.put(actions.setSSOLoader({ key: exports.SSOStateKeys.UPDATE_SSO_DEFAULT_ROLES, value: true }));
1825
+ const ssoConfigurations = yield effects.select((state) => state.auth.ssoState.ssoConfigurations);
1826
+ try {
1827
+ yield effects.call(restApi.api.auth.setSSODefaultRoles, ssoConfigId, { roleIds });
1828
+ const newSsoConfigurations = ssoConfigurations.map((ssoConfig) => {
1829
+ if (ssoConfig.id === ssoConfigId) {
1830
+ return Object.assign(Object.assign({}, ssoConfig), { roleIds });
1831
+ }
1832
+ return ssoConfig;
1833
+ });
1834
+ yield effects.put(actions.setSSOState({ ssoConfigurations: newSsoConfigurations }));
1835
+ callback === null || callback === void 0 ? void 0 : callback(true);
1836
+ }
1837
+ catch (error) {
1838
+ yield effects.put(actions.setSSOError({ key: exports.SSOStateKeys.UPDATE_SSO_DEFAULT_ROLES, value: error.message }));
1839
+ callback === null || callback === void 0 ? void 0 : callback(null, error);
1840
+ }
1841
+ finally {
1842
+ yield effects.put(actions.setSSOLoader({ key: exports.SSOStateKeys.UPDATE_SSO_DEFAULT_ROLES, value: false }));
1843
+ }
1844
+ }
1845
+ function* setSSOGroups({ payload: { groupsToAdd, groupsToDelete, ssoConfigId, callback } }) {
1846
+ yield effects.put(actions.setSSOLoader({ key: exports.SSOStateKeys.SAVE_SSO_GROUPS, value: true }));
1847
+ const ssoConfigurations = yield effects.select((state) => state.auth.ssoState.ssoConfigurations);
1848
+ try {
1849
+ yield effects.all(groupsToDelete.map((groupId) => effects.call(restApi.api.auth.deleteSSOGroup, ssoConfigId, groupId)));
1850
+ yield effects.all(groupsToAdd.map((group) => effects.call(restApi.api.auth.createSSOGroup, ssoConfigId, group)));
1851
+ const groups = yield effects.call(restApi.api.auth.getSSOGroups, ssoConfigId);
1852
+ const newSsoConfigurations = ssoConfigurations.map((ssoConfig) => {
1853
+ if (ssoConfig.id === ssoConfigId) {
1854
+ return Object.assign(Object.assign({}, ssoConfig), { groups });
1855
+ }
1856
+ return ssoConfig;
1857
+ });
1858
+ yield effects.put(actions.setSSOState({ ssoConfigurations: newSsoConfigurations }));
1859
+ callback === null || callback === void 0 ? void 0 : callback(true);
1860
+ }
1861
+ catch (error) {
1862
+ yield effects.put(actions.setSSOError({ key: exports.SSOStateKeys.SAVE_SSO_GROUPS, value: error.message }));
1863
+ callback === null || callback === void 0 ? void 0 : callback(null, error);
1864
+ }
1865
+ finally {
1866
+ yield effects.put(actions.setSSOLoader({ key: exports.SSOStateKeys.SAVE_SSO_GROUPS, value: false }));
1867
+ }
1868
+ }
1869
+ function* ssoSagas() {
1870
+ yield effects.takeEvery(actions.loadSSOConfigurationsV2, loadSSOConfigurationsV2);
1871
+ yield effects.takeEvery(actions.saveSSOConfigurationV2, saveSSOConfigurationV2);
1872
+ yield effects.takeEvery(actions.saveSSODomain, saveSSODomain);
1873
+ yield effects.takeEvery(actions.deleteSSODomain, deleteSSODomain);
1874
+ yield effects.takeEvery(actions.validateSSODomainV2, validateSSODomainV2);
1875
+ yield effects.takeEvery(actions.updateSSOConfiguration, updateSSOConfiguration);
1876
+ yield effects.takeEvery(actions.deleteSSOConfiguration, deleteSSOConfiguration);
1877
+ yield effects.takeEvery(actions.setSSOGroups, setSSOGroups);
1878
+ yield effects.takeEvery(actions.setSSODefaultRoles, setSSODefaultRoles);
1879
+ yield effects.takeEvery(actions.saveSSOConfigurationByMetadata, saveSSOConfigurationByMetadata);
1880
+ yield effects.takeEvery(actions.updateSSOConfigurationByMetadata, updateSSOConfigurationByMetadata);
1881
+ }
1882
+
1883
+ function* loadProfile() {
1884
+ yield effects.put(actions.setProfileState({ loading: true }));
1885
+ try {
1886
+ const profile = yield effects.retry(3, 2000, restApi.api.teams.getProfile);
1887
+ const currentUser = yield effects.select((state) => state.auth.user);
1888
+ actions.setUser(Object.assign(Object.assign({}, currentUser), profile));
1889
+ yield effects.put(actions.setProfileState({ profile, loading: false }));
1890
+ }
1891
+ catch (e) {
1892
+ yield effects.put(actions.setProfileState({ loading: false, error: e.message }));
1893
+ }
1894
+ }
1895
+ function b64toBlob(base64, contentType) {
1896
+ const sliceSize = 512;
1897
+ const byteCharacters = atob(base64);
1898
+ const byteArrays = [];
1899
+ for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
1900
+ const slice = byteCharacters.slice(offset, offset + sliceSize);
1901
+ const byteNumbers = new Array(slice.length);
1902
+ for (let i = 0; i < slice.length; i++) {
1903
+ byteNumbers[i] = slice.charCodeAt(i);
1904
+ }
1905
+ byteArrays.push(new Uint8Array(byteNumbers));
1906
+ }
1907
+ return new Blob(byteArrays, { type: contentType });
1908
+ }
1909
+ function base64ToFormData(base64, key = 'file') {
1910
+ const matchResult = base64.match(/^data:image\/([A-Za-z-+\/]+);base64,(.+)$/);
1911
+ if (matchResult == null) {
1912
+ return null;
1913
+ }
1914
+ // Get the content type of the image
1915
+ const contentType = `image/${matchResult[1]}`;
1916
+ // get the real base64 content of the file
1917
+ const data = matchResult[2];
1918
+ // Convert it to a blob to upload
1919
+ const blob = b64toBlob(data, contentType);
1920
+ // Create a FormData and append the file with "image" as parameter name
1921
+ const formDataToUpload = new FormData();
1922
+ formDataToUpload.append(key, new File([blob], key, { type: contentType }));
1923
+ return formDataToUpload;
1924
+ }
1925
+ function* saveProfile(_a) {
1926
+ var _b = _a.payload, { callback, profilePictureUrl } = _b, payload = tslib.__rest(_b, ["callback", "profilePictureUrl"]);
1927
+ yield effects.put(actions.setProfileState({ saving: true, error: null }));
1928
+ try {
1929
+ const oldProfileData = yield effects.select((state) => state.auth.profileState.profile);
1930
+ let newProfilePictureUrl = oldProfileData.profilePictureUrl;
1931
+ if (profilePictureUrl !== oldProfileData.profilePictureUrl && profilePictureUrl) {
1932
+ const matchResult = (profilePictureUrl || '').match(/^data:image\/([A-Za-z-+\/]+);base64,(.+)$/);
1933
+ if (matchResult) {
1934
+ const profileImage = base64ToFormData(profilePictureUrl, 'image');
1935
+ if (profileImage) {
1936
+ newProfilePictureUrl = yield effects.call(restApi.api.teams.updateProfileImage, profileImage);
1937
+ const imageTimeStamp = Date.now().toString();
1938
+ const urlTemplate = new URL(newProfilePictureUrl);
1939
+ urlTemplate.searchParams.set('t', imageTimeStamp);
1940
+ newProfilePictureUrl = urlTemplate.href;
1941
+ }
1942
+ }
1943
+ }
1944
+ const newProfileData = Object.assign(Object.assign(Object.assign({}, oldProfileData), payload), { profilePictureUrl: newProfilePictureUrl });
1945
+ const profile = yield effects.call(restApi.api.teams.updateProfile, newProfileData);
1946
+ const currentUser = yield effects.select((state) => state.auth.user);
1947
+ yield effects.put(actions.setUser(Object.assign(Object.assign({}, currentUser), profile)));
1948
+ yield effects.put(actions.setProfileState({ profile, saving: false }));
1949
+ callback === null || callback === void 0 ? void 0 : callback(newProfileData);
1950
+ }
1951
+ catch (e) {
1952
+ yield effects.put(actions.setProfileState({ saving: false, error: e.message }));
1953
+ callback === null || callback === void 0 ? void 0 : callback(null, e);
1954
+ }
1955
+ }
1956
+ function* changePassword({ payload }) {
1957
+ var _a, _b;
1958
+ yield effects.put(actions.setProfileState({ loading: true }));
1959
+ try {
1960
+ yield effects.call(restApi.api.teams.changePassword, payload);
1961
+ yield effects.put(actions.setProfileState({ loading: false, error: undefined }));
1962
+ (_a = payload.callback) === null || _a === void 0 ? void 0 : _a.call(payload, true);
1963
+ }
1964
+ catch (e) {
1965
+ yield effects.put(actions.setProfileState({ loading: false, error: e.message }));
1966
+ (_b = payload.callback) === null || _b === void 0 ? void 0 : _b.call(payload, null, e);
1967
+ }
1968
+ }
1969
+ function* profileSagas() {
1970
+ yield effects.takeLeading(actions.loadProfile, loadProfile);
1971
+ yield effects.takeEvery(actions.saveProfile, saveProfile);
1972
+ yield effects.takeEvery(actions.changePassword, changePassword);
1973
+ }
1974
+ /*********************************
1975
+ * Preview Sagas
1976
+ *********************************/
1977
+ function* loadProfileMock() {
1978
+ yield effects.put(actions.setProfileState({ loading: true }));
1979
+ yield delay();
1980
+ yield effects.put(actions.setUser(Object.assign(Object.assign({}, (userDemo)), userProfileDemo)));
1981
+ yield effects.put(actions.setProfileState({ loading: false, profile: userProfileDemo }));
1982
+ }
1983
+ function* saveProfileMock(_a) {
1984
+ var _b = _a.payload, { callback, profilePictureUrl } = _b, payload = tslib.__rest(_b, ["callback", "profilePictureUrl"]);
1985
+ yield effects.put(actions.setProfileState({ saving: true, error: null }));
1986
+ const oldProfileData = profileStateDemo;
1987
+ let newProfilePictureUrl = oldProfileData.profile.profilePictureUrl;
1988
+ if (profilePictureUrl !== oldProfileData.profile.profilePictureUrl && profilePictureUrl) {
1989
+ const matchResult = (profilePictureUrl || '').match(/^data:image\/([A-Za-z-+\/]+);base64,(.+)$/);
1990
+ if (matchResult) {
1991
+ newProfilePictureUrl = profilePictureUrl;
1992
+ }
1993
+ }
1994
+ const newProfileData = Object.assign(Object.assign(Object.assign({}, oldProfileData.profile), payload), { profilePictureUrl: newProfilePictureUrl });
1995
+ const currentUser = userDemo;
1996
+ yield delay();
1997
+ yield effects.put(actions.setUser(Object.assign(Object.assign({}, currentUser), newProfileData)));
1998
+ yield effects.put(actions.setProfileState({ loading: false, error: null, saving: false, profile: newProfileData }));
1999
+ callback === null || callback === void 0 ? void 0 : callback(newProfileData);
2000
+ }
2001
+ function* changePasswordMock({ payload }) {
2002
+ var _a;
2003
+ yield effects.put(actions.setProfileState({ loading: true }));
2004
+ yield delay();
2005
+ yield effects.put(actions.setProfileState({ loading: false, error: undefined }));
2006
+ (_a = payload.callback) === null || _a === void 0 ? void 0 : _a.call(payload, true);
2007
+ }
2008
+ function* profileSagasMock() {
2009
+ yield effects.takeLeading(actions.loadProfile, loadProfileMock);
2010
+ yield effects.takeEvery(actions.saveProfile, saveProfileMock);
2011
+ yield effects.takeEvery(actions.changePassword, changePasswordMock);
2012
+ }
2013
+
2014
+ function* enrollMfa() {
2015
+ yield effects.put(actions.setMfaState({ loading: true }));
2016
+ try {
2017
+ const { qrCode } = yield effects.call(restApi.api.auth.enrollMfa);
2018
+ yield effects.put(actions.setMfaState({ loading: false, error: undefined, qrCode }));
2019
+ }
2020
+ catch (e) {
2021
+ yield effects.put(actions.setMfaState({ loading: false, error: e.message }));
2022
+ }
2023
+ }
2024
+ function* verifyMfa(_a) {
2025
+ var _b = _a.payload, { callback } = _b, payload = tslib.__rest(_b, ["callback"]);
2026
+ yield effects.put(actions.setMfaState({ loading: true }));
2027
+ try {
2028
+ const user = yield effects.select((state) => state.auth.user);
2029
+ const data = yield effects.call(restApi.api.auth.verifyMfa, payload);
2030
+ const mfaState = {
2031
+ step: exports.MFAStep.recoveryCode,
2032
+ loading: false,
2033
+ error: undefined,
2034
+ };
2035
+ if (data === null || data === void 0 ? void 0 : data.recoveryCode) {
2036
+ mfaState.recoveryCode = data.recoveryCode;
2037
+ }
2038
+ yield effects.put(actions.setMfaState(mfaState));
2039
+ yield effects.put(actions.setUser(Object.assign(Object.assign({}, user), { mfaEnrolled: true })));
2040
+ callback === null || callback === void 0 ? void 0 : callback(mfaState.recoveryCode);
2041
+ }
2042
+ catch (e) {
2043
+ yield effects.put(actions.setMfaState({ loading: false, error: e.message }));
2044
+ callback === null || callback === void 0 ? void 0 : callback(null, e);
2045
+ }
2046
+ }
2047
+ function* verifyMfaAfterForce(_a) {
2048
+ var _b = _a.payload, { callback } = _b, payload = tslib.__rest(_b, ["callback"]);
2049
+ yield effects.put(actions.setMfaState({ loading: true }));
2050
+ try {
2051
+ const user = yield effects.call(restApi.api.auth.loginWithMfa, payload);
2052
+ const mfaState = {
2053
+ step: exports.MFAStep.recoveryCode,
2054
+ loading: false,
2055
+ error: undefined,
2056
+ };
2057
+ if (user === null || user === void 0 ? void 0 : user.recoveryCode) {
2058
+ mfaState.recoveryCode = user.recoveryCode;
2059
+ }
2060
+ yield effects.put(actions.setMfaState(mfaState));
2061
+ yield effects.put(actions.setState({ user }));
2062
+ yield effects.put(actions.loadTenants());
2063
+ callback === null || callback === void 0 ? void 0 : callback(mfaState.recoveryCode);
2064
+ }
2065
+ catch (e) {
2066
+ yield effects.put(actions.setMfaState({ loading: false, error: e.message }));
2067
+ callback === null || callback === void 0 ? void 0 : callback(null, e);
2068
+ }
2069
+ }
2070
+ function* disableMfa({ payload }) {
2071
+ var _a, _b;
2072
+ yield effects.put(actions.setMfaState({ loading: true }));
2073
+ try {
2074
+ const user = yield effects.select((state) => state.auth.user);
2075
+ yield restApi.api.auth.disableMfa(payload);
2076
+ yield effects.put(actions.setMfaState({ loading: false, error: undefined }));
2077
+ yield effects.put(actions.setUser(Object.assign(Object.assign({}, user), { mfaEnrolled: false })));
2078
+ (_a = payload.callback) === null || _a === void 0 ? void 0 : _a.call(payload, true);
2079
+ }
2080
+ catch (e) {
2081
+ yield effects.put(actions.setMfaState({ loading: false, error: e.message }));
2082
+ (_b = payload.callback) === null || _b === void 0 ? void 0 : _b.call(payload, false, e);
2083
+ }
2084
+ }
2085
+ function* mfaSagas() {
2086
+ yield effects.takeEvery(actions.enrollMfa, enrollMfa);
2087
+ yield effects.takeEvery(actions.verifyMfa, verifyMfa);
2088
+ yield effects.takeEvery(actions.disableMfa, disableMfa);
2089
+ yield effects.takeEvery(actions.verifyMfaAfterForce, verifyMfaAfterForce);
2090
+ }
2091
+ /*********************************
2092
+ * Preview Sagas
2093
+ *********************************/
2094
+ function* enrollMfaMock() {
2095
+ yield effects.put(actions.setMfaState({ loading: true }));
2096
+ const qrCode = 'test';
2097
+ yield effects.put(actions.setMfaState({ loading: false, error: undefined, qrCode }));
2098
+ }
2099
+ function* verifyMfaMock({ payload: { callback }, }) {
2100
+ yield effects.put(actions.setMfaState({ loading: true }));
2101
+ yield delay();
2102
+ const data = { token: 'token', recoveryCode: 'recoveryCode' };
2103
+ const mfaState = {
2104
+ step: exports.MFAStep.recoveryCode,
2105
+ loading: false,
2106
+ error: undefined,
2107
+ };
2108
+ if (data === null || data === void 0 ? void 0 : data.recoveryCode) {
2109
+ mfaState.recoveryCode = data.recoveryCode;
2110
+ }
2111
+ yield effects.put(actions.setMfaState(mfaState));
2112
+ yield effects.put(actions.setUser(Object.assign(Object.assign({}, userDemo), { mfaEnrolled: true })));
2113
+ callback === null || callback === void 0 ? void 0 : callback(mfaState.recoveryCode);
2114
+ }
2115
+ function* verifyMfaAfterForceMock(_a) {
2116
+ var _b = _a.payload, { callback } = _b, payload = tslib.__rest(_b, ["callback"]);
2117
+ yield effects.put(actions.setMfaState({ loading: true }));
2118
+ yield delay();
2119
+ const data = Object.assign(Object.assign({}, payload), { recoveryCode: 'recoveryCode' });
2120
+ const mfaState = {
2121
+ step: exports.MFAStep.recoveryCode,
2122
+ loading: false,
2123
+ error: undefined,
2124
+ };
2125
+ if (data === null || data === void 0 ? void 0 : data.recoveryCode) {
2126
+ mfaState.recoveryCode = data.recoveryCode;
2127
+ }
2128
+ yield effects.put(actions.setMfaState(mfaState));
2129
+ yield delay();
2130
+ yield effects.put(actions.setUser(Object.assign(Object.assign({}, userDemo), { mfaEnrolled: true })));
2131
+ callback === null || callback === void 0 ? void 0 : callback(mfaState.recoveryCode);
2132
+ }
2133
+ function* disableMfaMock({ payload }) {
2134
+ var _a;
2135
+ yield effects.put(actions.setMfaState({ loading: true }));
2136
+ yield delay();
2137
+ yield effects.put(actions.setMfaState({ loading: false, error: undefined }));
2138
+ yield effects.put(actions.setUser(Object.assign(Object.assign({}, userDemo), { mfaEnrolled: false })));
2139
+ (_a = payload.callback) === null || _a === void 0 ? void 0 : _a.call(payload, true);
2140
+ }
2141
+ function* mfaSagasMock() {
2142
+ yield effects.takeEvery(actions.enrollMfa, enrollMfaMock);
2143
+ yield effects.takeEvery(actions.verifyMfa, verifyMfaMock);
2144
+ yield effects.takeEvery(actions.disableMfa, disableMfaMock);
2145
+ yield effects.takeEvery(actions.verifyMfaAfterForce, verifyMfaAfterForceMock);
2146
+ }
2147
+
2148
+ function* forgotPassword({ payload }) {
2149
+ yield effects.put(actions.setForgotPasswordState({ loading: true }));
2150
+ try {
2151
+ yield effects.call(restApi.api.auth.forgotPassword, payload);
2152
+ yield effects.put(actions.setForgotPasswordState({ loading: false, error: undefined, step: exports.ForgotPasswordStep.success }));
2153
+ }
2154
+ catch (e) {
2155
+ yield effects.put(actions.setForgotPasswordState({ loading: false, error: e.message || 'Unknown error occurred' }));
2156
+ }
2157
+ }
2158
+ function* resetPassword(_a) {
2159
+ var _b = _a.payload, { callback } = _b, body = tslib.__rest(_b, ["callback"]);
2160
+ yield effects.put(actions.setForgotPasswordState({ loading: true }));
2161
+ try {
2162
+ yield effects.call(restApi.api.auth.resetPassword, body);
2163
+ yield effects.put(actions.setForgotPasswordState({ loading: false, error: undefined, step: exports.ForgotPasswordStep.success }));
2164
+ callback === null || callback === void 0 ? void 0 : callback(true);
2165
+ }
2166
+ catch (e) {
2167
+ yield effects.put(actions.setForgotPasswordState({ loading: false, error: e.message }));
2168
+ callback === null || callback === void 0 ? void 0 : callback(false);
2169
+ }
2170
+ }
2171
+ function* loadPasswordConfig({ payload }) {
2172
+ yield effects.put(actions.setForgotPasswordState({ loading: true }));
2173
+ try {
2174
+ const passwordConfig = yield effects.call(restApi.api.auth.loadPasswordConfig, payload);
2175
+ yield effects.put(actions.setForgotPasswordState({ loading: false, passwordConfig }));
2176
+ }
2177
+ catch (e) {
2178
+ yield effects.put(actions.setForgotPasswordState({ loading: false, error: e.message }));
2179
+ }
2180
+ }
2181
+ function* forgotPasswordSagas() {
2182
+ yield effects.takeLeading(actions.forgotPassword, forgotPassword);
2183
+ yield effects.takeLeading(actions.resetPassword, resetPassword);
2184
+ yield effects.takeLeading(actions.loadPasswordConfig, loadPasswordConfig);
2185
+ }
2186
+
2187
+ function* preActivateAccount({ payload: { userId, token } }) {
2188
+ yield effects.put(actions.setActivateState({ loading: true, step: exports.ActivateAccountStep.activating }));
2189
+ try {
2190
+ const { isAuthenticated } = yield effects.select((state) => state.auth);
2191
+ if (isAuthenticated) {
2192
+ yield effects.put(actions.silentLogout());
2193
+ }
2194
+ const strategy = yield effects.call(restApi.api.auth.getActivateAccountStrategy, { userId, token });
2195
+ yield effects.put(actions.setActivateStrategyState({ strategy, loading: false, error: undefined }));
2196
+ if (strategy.shouldSetPassword) {
2197
+ yield effects.put(actions.setActivateState({ loading: false, step: exports.ActivateAccountStep.activatingForm }));
2198
+ }
2199
+ }
2200
+ catch (e) {
2201
+ yield effects.put(actions.setActivateState({ loading: false, error: e.message }));
2202
+ }
2203
+ }
2204
+ function* activateAccount(_a) {
2205
+ var _b;
2206
+ var _c = _a.payload, { callback, events } = _c, payload = tslib.__rest(_c, ["callback", "events"]);
2207
+ yield effects.put(actions.setActivateState({ loading: true }));
2208
+ try {
2209
+ const onRedirectTo = restApi.ContextHolder.onRedirectTo;
2210
+ const { routes } = yield effects.select((state) => state.auth);
2211
+ const data = yield effects.call(restApi.api.auth.activateAccount, payload);
2212
+ if (data.redirectLocation) {
2213
+ window.location.href = data.redirectLocation;
2214
+ return;
2215
+ }
2216
+ if (isMfaRequired(data)) {
2217
+ yield effects.put(actions.setActivateState({ step: exports.ActivateAccountStep.success }));
2218
+ const mfaRequiredState = yield getMfaRequiredState(data);
2219
+ yield effects.put(actions.setState(mfaRequiredState));
2220
+ yield effects.delay(1000);
2221
+ onRedirectTo(routes.loginUrl, { preserveQueryParams: true });
2222
+ }
2223
+ else {
2224
+ yield effects.put(actions.setActivateState({ step: exports.ActivateAccountStep.success }));
2225
+ const { user, tenants } = yield effects.call(restApi.api.auth.generateLoginResponseV2, data);
2226
+ (_b = events === null || events === void 0 ? void 0 : events.userVerified) === null || _b === void 0 ? void 0 : _b.call(events, { email: user.email, origin: exports.UserVeirifedOriginTypes.ACTIVATION_LINK });
2227
+ yield effects.put(actions.setTenantsState({ tenants, loading: false }));
2228
+ yield effects.put(actions.setState({ user, isAuthenticated: true }));
2229
+ yield effects.delay(1000);
2230
+ yield afterAuthNavigation();
2231
+ yield effects.put(actions.resetActivateState());
2232
+ }
2233
+ callback === null || callback === void 0 ? void 0 : callback(true);
2234
+ }
2235
+ catch (e) {
2236
+ yield effects.put(actions.setActivateState({ loading: false, error: e.message }));
2237
+ }
2238
+ }
2239
+ function* getActivateAccountStrategy({ payload, }) {
2240
+ const { callback } = payload, params = tslib.__rest(payload, ["callback"]);
2241
+ yield effects.put(actions.setActivateStrategyState({ loading: true }));
2242
+ try {
2243
+ const strategy = yield effects.call(restApi.api.auth.getActivateAccountStrategy, params);
2244
+ yield effects.put(actions.setActivateStrategyState({ strategy, loading: false, error: undefined }));
2245
+ callback === null || callback === void 0 ? void 0 : callback(strategy);
2246
+ }
2247
+ catch (e) {
2248
+ yield effects.put(actions.setActivateStrategyState({ loading: false, error: e.message }));
2249
+ }
2250
+ }
2251
+ function* resendActivationEmailFunction({ payload }) {
2252
+ yield effects.put(actions.setActivateState({ loading: true }));
2253
+ try {
2254
+ yield effects.call(restApi.api.auth.resendActivationEmail, { email: payload.email });
2255
+ yield effects.put(actions.setActivateState({ loading: false, error: undefined, resentEmail: true }));
2256
+ }
2257
+ catch (e) {
2258
+ yield effects.put(actions.setActivateState({ loading: false, error: e.message }));
2259
+ }
2260
+ }
2261
+ function* activateSagas() {
2262
+ yield effects.takeLeading(actions.activateAccount, activateAccount);
2263
+ yield effects.takeLeading(actions.preActivateAccount, preActivateAccount);
2264
+ yield effects.takeLeading(actions.getActivateAccountStrategy, getActivateAccountStrategy);
2265
+ yield effects.takeLeading(actions.resendActivationEmail, resendActivationEmailFunction);
2266
+ }
2267
+
2268
+ function* acceptInvitation({ payload }) {
2269
+ if (!payload.token || !payload.userId) {
2270
+ yield effects.put(actions.setAcceptInvitationState({ error: undefined, step: exports.AcceptInvitationStep.invalid }));
2271
+ return;
2272
+ }
2273
+ try {
2274
+ yield effects.put(actions.setAcceptInvitationState({ error: undefined, step: exports.AcceptInvitationStep.pending }));
2275
+ yield effects.call(restApi.api.auth.acceptInvitation, payload);
2276
+ yield effects.put(actions.setState({
2277
+ isAuthenticated: false,
2278
+ user: null,
2279
+ acceptInvitationState: { error: undefined, step: exports.AcceptInvitationStep.success },
2280
+ }));
2281
+ }
2282
+ catch (e) {
2283
+ yield effects.put(actions.setAcceptInvitationState({ step: exports.AcceptInvitationStep.failed, error: e.message }));
2284
+ }
2285
+ }
2286
+ function* acceptInvitationSagas() {
2287
+ yield effects.takeLeading(actions.acceptInvitation, acceptInvitation);
2288
+ }
2289
+
2290
+ exports.TeamStateKeys = void 0;
2291
+ (function (TeamStateKeys) {
2292
+ TeamStateKeys["USERS"] = "USERS";
2293
+ TeamStateKeys["STATS"] = "STATS";
2294
+ TeamStateKeys["UPDATE_USER"] = "UPDATE_USER";
2295
+ TeamStateKeys["DELETE_USER"] = "DELETE_USER";
2296
+ TeamStateKeys["RESEND_ACTIVATE_LINK"] = "RESEND_ACTIVATE_LINK";
2297
+ TeamStateKeys["RESEND_INVITATION_LINK"] = "RESEND_INVITATION_LINK";
2298
+ TeamStateKeys["ROLES_AND_PERMISSIONS"] = "ROLES_AND_PERMISSIONS";
2299
+ TeamStateKeys["CREATE_TOKEN_LINK"] = "CREATE_TOKEN_LINK";
2300
+ TeamStateKeys["GET_TOKEN_LINK"] = "GET_TOKEN_LINK";
2301
+ TeamStateKeys["UPDATE_TOKEN_LINK"] = "UPDATE_TOKEN_LINK";
2302
+ TeamStateKeys["DELETE_TOKEN_LINK"] = "DELETE_TOKEN_LINK";
2303
+ TeamStateKeys["CONFIG_TOKEN_LINK"] = "CONFIG_TOKEN_LINK";
2304
+ })(exports.TeamStateKeys || (exports.TeamStateKeys = {}));
2305
+
2306
+ const selectTeamState = () => effects.select((_) => _[constants.authStoreName].teamState);
2307
+ function* loadUsers({ payload }) {
2308
+ var _a, _b, _c, _d;
2309
+ const { silentLoading, callback } = payload;
2310
+ const teamState = yield selectTeamState();
2311
+ const pageSize = (_a = payload.pageSize) !== null && _a !== void 0 ? _a : teamState.pageSize;
2312
+ const pageOffset = (_b = payload.pageOffset) !== null && _b !== void 0 ? _b : teamState.pageOffset;
2313
+ const filter = (_c = payload.filter) !== null && _c !== void 0 ? _c : teamState.filter;
2314
+ const sort = (_d = payload.sort) !== null && _d !== void 0 ? _d : teamState.sort;
2315
+ yield effects.put(actions.setTeamLoader({ key: exports.TeamStateKeys.USERS, value: !silentLoading }));
2316
+ yield effects.put(actions.setTeamState({
2317
+ pageSize,
2318
+ pageOffset,
2319
+ filter,
2320
+ sort,
2321
+ }));
2322
+ try {
2323
+ const [{ items: users, totalPages, totalItems }, { items: roles }, { items: permissions }] = yield effects.all([
2324
+ effects.call(restApi.api.teams.loadUsers, {
2325
+ pageSize,
2326
+ pageOffset,
2327
+ filter,
2328
+ sort,
2329
+ }),
2330
+ effects.call(restApi.api.teams.loadAvailableRoles),
2331
+ effects.call(restApi.api.teams.loadAvailablePermissions),
2332
+ ]);
2333
+ yield effects.put(actions.setTeamState({ users, totalPages, totalItems, roles, permissions }));
2334
+ callback === null || callback === void 0 ? void 0 : callback(users);
2335
+ }
2336
+ catch (e) {
2337
+ yield effects.put(actions.setTeamError({ key: exports.TeamStateKeys.USERS, value: e.message }));
2338
+ yield effects.put(actions.setTeamState({ totalPages: 0, users: [] }));
2339
+ callback === null || callback === void 0 ? void 0 : callback(null, e);
2340
+ }
2341
+ yield effects.put(actions.setTeamLoader({ key: exports.TeamStateKeys.USERS, value: false }));
2342
+ }
2343
+ function* loadRoles({ payload }) {
2344
+ var _a, _b;
2345
+ yield effects.put(actions.setTeamLoader({ key: exports.TeamStateKeys.ROLES_AND_PERMISSIONS, value: true }));
2346
+ try {
2347
+ const [{ items: roles }, { items: permissions }] = yield effects.all([
2348
+ effects.call(restApi.api.teams.loadAvailableRoles),
2349
+ effects.call(restApi.api.teams.loadAvailablePermissions),
2350
+ ]);
2351
+ yield effects.put(actions.setTeamState({ roles, permissions }));
2352
+ (_a = payload === null || payload === void 0 ? void 0 : payload.callback) === null || _a === void 0 ? void 0 : _a.call(payload, { roles, permissions });
2353
+ }
2354
+ catch (e) {
2355
+ (_b = payload === null || payload === void 0 ? void 0 : payload.callback) === null || _b === void 0 ? void 0 : _b.call(payload, null, e);
2356
+ yield effects.put(actions.setTeamError({ key: exports.TeamStateKeys.ROLES_AND_PERMISSIONS, value: e.message }));
2357
+ }
2358
+ yield effects.put(actions.setTeamLoader({ key: exports.TeamStateKeys.ROLES_AND_PERMISSIONS, value: true }));
2359
+ }
2360
+ function* addUser({ payload }) {
2361
+ const { callback } = payload, body = tslib.__rest(payload, ["callback"]);
2362
+ const teamState = yield selectTeamState();
2363
+ yield effects.put(actions.setTeamState({ addUserDialogState: Object.assign(Object.assign({}, teamState.addUserDialogState), { loading: true }) }));
2364
+ try {
2365
+ const res = yield effects.call(restApi.api.teams.addUser, body);
2366
+ const { roles } = res, userWithoutRoleIds = tslib.__rest(res, ["roles"]);
2367
+ const roleIds = roles.map((role) => role.id);
2368
+ const newUser = Object.assign(Object.assign({}, userWithoutRoleIds), { roleIds });
2369
+ callback === null || callback === void 0 ? void 0 : callback(newUser);
2370
+ yield effects.put(actions.setTeamState({
2371
+ users: [newUser, ...teamState.users],
2372
+ addUserDialogState: { open: false, loading: false },
2373
+ }));
2374
+ }
2375
+ catch (e) {
2376
+ yield effects.put(actions.setTeamState({
2377
+ addUserDialogState: Object.assign(Object.assign({}, teamState.addUserDialogState), { loading: false, error: e.message }),
2378
+ }));
2379
+ callback === null || callback === void 0 ? void 0 : callback(null, e.message);
2380
+ }
2381
+ }
2382
+ function* updateUser({ payload }) {
2383
+ var _a;
2384
+ const { callback, profileImage } = payload, body = tslib.__rest(payload, ["callback", "profileImage"]);
2385
+ const { id: userId } = body;
2386
+ const teamState = yield selectTeamState();
2387
+ const oldUserData = teamState.users.find((user) => user.id === body.id);
2388
+ yield effects.put(actions.setTeamLoader({ key: exports.TeamStateKeys.UPDATE_USER, value: userId || '' }));
2389
+ yield effects.put(actions.setTeamState({ addUserDialogState: Object.assign(Object.assign({}, teamState.addUserDialogState), { loading: true }) }));
2390
+ yield effects.put(actions.setTeamState({
2391
+ addUserDialogState: Object.assign(Object.assign({}, teamState.addUserDialogState), { loading: true }),
2392
+ users: teamState.users.map((user) => {
2393
+ if (user.id === body.id) {
2394
+ return Object.assign(Object.assign({}, user), body);
2395
+ }
2396
+ return user;
2397
+ }),
2398
+ }));
2399
+ try {
2400
+ if (oldUserData.roleIds.length > 0 && ((_a = body.roleIds) === null || _a === void 0 ? void 0 : _a.length) === 0) {
2401
+ body.roleIds = [''];
2402
+ }
2403
+ const { item: newUser } = yield effects.call(restApi.api.teams.updateUser, body);
2404
+ callback === null || callback === void 0 ? void 0 : callback(newUser);
2405
+ yield effects.put(actions.setTeamState({
2406
+ users: teamState.users.map((user) => user.id === newUser.id
2407
+ ? Object.assign(Object.assign(Object.assign({}, user), newUser), { createdAt: user.createdAt, customData: user.customData, lastLogin: user.lastLogin }) : user),
2408
+ }));
2409
+ yield effects.put(actions.setTeamLoader({ key: exports.TeamStateKeys.UPDATE_USER, value: false }));
2410
+ }
2411
+ catch (e) {
2412
+ yield effects.put(actions.setTeamState({
2413
+ addUserDialogState: Object.assign(Object.assign({}, teamState.addUserDialogState), { loading: false, error: e.message }),
2414
+ users: teamState.users.map((user) => (user.id === body.id ? Object.assign(Object.assign({}, user), oldUserData) : user)),
2415
+ }));
2416
+ yield effects.put(actions.setTeamLoader({ key: exports.TeamStateKeys.UPDATE_USER, value: false }));
2417
+ callback === null || callback === void 0 ? void 0 : callback(null, e.message);
2418
+ }
2419
+ }
2420
+ function* deleteUser({ payload }) {
2421
+ const { callback } = payload, body = tslib.__rest(payload, ["callback"]);
2422
+ const teamState = yield selectTeamState();
2423
+ yield effects.put(actions.setTeamState({ deleteUserDialogState: Object.assign(Object.assign({}, teamState.deleteUserDialogState), { loading: true }) }));
2424
+ try {
2425
+ yield effects.call(restApi.api.teams.deleteUser, body);
2426
+ callback === null || callback === void 0 ? void 0 : callback(true);
2427
+ yield effects.put(actions.setTeamState({
2428
+ users: teamState.users.filter((user) => user.id !== body.userId),
2429
+ deleteUserDialogState: { open: false, loading: false },
2430
+ }));
2431
+ }
2432
+ catch (e) {
2433
+ yield effects.put(actions.setTeamState({
2434
+ deleteUserDialogState: Object.assign(Object.assign({}, teamState.deleteUserDialogState), { loading: false, error: e.message }),
2435
+ }));
2436
+ callback === null || callback === void 0 ? void 0 : callback(null, e.message);
2437
+ }
2438
+ }
2439
+ function* resendActivationLink({ payload }) {
2440
+ const { callback } = payload, body = tslib.__rest(payload, ["callback"]);
2441
+ yield effects.put(actions.setTeamLoader({ key: exports.TeamStateKeys.RESEND_ACTIVATE_LINK, value: body.userId }));
2442
+ try {
2443
+ yield effects.call(restApi.api.teams.resendActivationLink, body);
2444
+ callback === null || callback === void 0 ? void 0 : callback(true);
2445
+ }
2446
+ catch (e) {
2447
+ yield effects.put(actions.setTeamError({ key: exports.TeamStateKeys.RESEND_ACTIVATE_LINK, value: e.message }));
2448
+ callback === null || callback === void 0 ? void 0 : callback(null, e.message);
2449
+ }
2450
+ yield effects.put(actions.setTeamLoader({ key: exports.TeamStateKeys.RESEND_ACTIVATE_LINK, value: false }));
2451
+ }
2452
+ function* resendInvitationLink({ payload }) {
2453
+ const { callback } = payload, body = tslib.__rest(payload, ["callback"]);
2454
+ yield effects.put(actions.setTeamLoader({ key: exports.TeamStateKeys.RESEND_INVITATION_LINK, value: body.email }));
2455
+ try {
2456
+ yield effects.call(restApi.api.teams.resendInvitationLink, body);
2457
+ callback === null || callback === void 0 ? void 0 : callback(true);
2458
+ }
2459
+ catch (e) {
2460
+ yield effects.put(actions.setTeamError({ key: exports.TeamStateKeys.RESEND_INVITATION_LINK, value: e.message }));
2461
+ callback === null || callback === void 0 ? void 0 : callback(null, e.message);
2462
+ }
2463
+ yield effects.put(actions.setTeamLoader({ key: exports.TeamStateKeys.RESEND_INVITATION_LINK, value: false }));
2464
+ }
2465
+ function* getInvitationLinkConfig() {
2466
+ yield effects.put(actions.setTeamError({ key: exports.TeamStateKeys.CONFIG_TOKEN_LINK, value: false }));
2467
+ try {
2468
+ const invitationLinkConfig = yield effects.call(restApi.api.teams.getInviteLinkConfiguration);
2469
+ yield effects.put(actions.setTeamState({ inviteTokenState: Object.assign({}, invitationLinkConfig) }));
2470
+ }
2471
+ catch (e) {
2472
+ yield effects.put(actions.setTeamError({ key: exports.TeamStateKeys.CONFIG_TOKEN_LINK, value: e.message }));
2473
+ }
2474
+ }
2475
+ function* getInvitationLink() {
2476
+ yield effects.put(actions.setTeamError({ key: exports.TeamStateKeys.GET_TOKEN_LINK, value: false }));
2477
+ try {
2478
+ yield effects.call(getInvitationLinkConfig);
2479
+ const data = yield effects.call(restApi.api.teams.getInviteUserLink);
2480
+ const { inviteTokenState } = yield selectTeamState();
2481
+ yield effects.put(actions.setTeamState({ inviteTokenState: Object.assign(Object.assign({}, inviteTokenState), data) }));
2482
+ }
2483
+ catch (e) {
2484
+ yield effects.put(actions.setTeamError({ key: exports.TeamStateKeys.GET_TOKEN_LINK, value: e.message }));
2485
+ }
2486
+ }
2487
+ function* createInvitationLink({ payload: { callback } }) {
2488
+ yield effects.put(actions.setTeamError({ key: exports.TeamStateKeys.CREATE_TOKEN_LINK, value: false }));
2489
+ const { inviteTokenState } = yield selectTeamState();
2490
+ try {
2491
+ const data = yield effects.call(restApi.api.teams.createInviteUserLink, { expiresInMinutes: 43200 });
2492
+ yield effects.put(actions.setTeamState({ inviteTokenState: Object.assign(Object.assign({}, inviteTokenState), data) }));
2493
+ callback === null || callback === void 0 ? void 0 : callback(data.token);
2494
+ }
2495
+ catch (e) {
2496
+ callback === null || callback === void 0 ? void 0 : callback(null, e.message);
2497
+ yield effects.put(actions.setTeamError({ key: exports.TeamStateKeys.CREATE_TOKEN_LINK, value: e.message }));
2498
+ }
2499
+ }
2500
+ function* updateInvitationLink({ payload: { callback, expiresInMinutes, shouldSendEmail } }) {
2501
+ const { inviteTokenState } = yield selectTeamState();
2502
+ yield effects.put(actions.setTeamError({ key: exports.TeamStateKeys.UPDATE_TOKEN_LINK, value: false }));
2503
+ try {
2504
+ const data = yield effects.call(restApi.api.teams.updateInviteUserLink, { expiresInMinutes, shouldSendEmail });
2505
+ yield effects.put(actions.setTeamState({ inviteTokenState: Object.assign(Object.assign({}, inviteTokenState), data) }));
2506
+ callback === null || callback === void 0 ? void 0 : callback(true);
2507
+ }
2508
+ catch (e) {
2509
+ callback === null || callback === void 0 ? void 0 : callback(null, e.message);
2510
+ yield effects.put(actions.setTeamError({ key: exports.TeamStateKeys.UPDATE_TOKEN_LINK, value: e.message }));
2511
+ }
2512
+ }
2513
+ function* deleteInvitationLink({ payload }) {
2514
+ const { callback } = payload !== null && payload !== void 0 ? payload : {};
2515
+ yield effects.put(actions.setTeamError({ key: exports.TeamStateKeys.DELETE_TOKEN_LINK, value: false }));
2516
+ try {
2517
+ yield effects.call(restApi.api.teams.deleteInviteUserLink);
2518
+ yield effects.put(actions.setTeamState({ inviteTokenState: undefined }));
2519
+ callback === null || callback === void 0 ? void 0 : callback(true);
2520
+ }
2521
+ catch (e) {
2522
+ yield effects.put(actions.setTeamError({ key: exports.TeamStateKeys.DELETE_TOKEN_LINK, value: e.message }));
2523
+ callback === null || callback === void 0 ? void 0 : callback(false, e.message);
2524
+ }
2525
+ }
2526
+ function* openAddUserDialog({ payload }) {
2527
+ yield effects.put(actions.setTeamState({
2528
+ addUserDialogState: Object.assign({ open: true, loading: false, error: false }, payload),
2529
+ }));
2530
+ }
2531
+ function* closeAddUserDialog({ payload }) {
2532
+ const teamState = yield selectTeamState();
2533
+ const { addUserDialogState: { onClose } } = teamState;
2534
+ onClose === null || onClose === void 0 ? void 0 : onClose(payload);
2535
+ yield effects.put(actions.setTeamState({
2536
+ addUserDialogState: {
2537
+ loading: false,
2538
+ error: false,
2539
+ open: false,
2540
+ },
2541
+ }));
2542
+ }
2543
+ function* openDeleteUserDialog({ payload }) {
2544
+ yield effects.put(actions.setTeamState({
2545
+ deleteUserDialogState: Object.assign({ open: true, loading: false, error: false }, payload),
2546
+ }));
2547
+ }
2548
+ function* closeDeleteUserDialog({ payload }) {
2549
+ const teamState = yield selectTeamState();
2550
+ const { deleteUserDialogState: { onClose } } = teamState;
2551
+ onClose === null || onClose === void 0 ? void 0 : onClose(payload);
2552
+ yield effects.put(actions.setTeamState({
2553
+ deleteUserDialogState: {
2554
+ loading: false,
2555
+ error: false,
2556
+ open: false,
2557
+ },
2558
+ }));
2559
+ }
2560
+ function* teamSagas() {
2561
+ yield effects.takeLatest(actions.loadUsers, loadUsers);
2562
+ yield effects.takeLatest(actions.loadRoles, loadRoles);
2563
+ yield effects.takeEvery(actions.addUser, addUser);
2564
+ yield effects.takeEvery(actions.updateUser, updateUser);
2565
+ yield effects.takeEvery(actions.deleteUser, deleteUser);
2566
+ yield effects.takeEvery(actions.resendActivationLink, resendActivationLink);
2567
+ yield effects.takeEvery(actions.resendInvitationLink, resendInvitationLink);
2568
+ yield effects.takeEvery(actions.getInvitationLink, getInvitationLink);
2569
+ yield effects.takeEvery(actions.createInvitationLink, createInvitationLink);
2570
+ yield effects.takeEvery(actions.updateInvitationLink, updateInvitationLink);
2571
+ yield effects.takeEvery(actions.deleteInvitationLink, deleteInvitationLink);
2572
+ yield effects.takeEvery(actions.openAddUserDialog, openAddUserDialog);
2573
+ yield effects.takeEvery(actions.closeAddUserDialog, closeAddUserDialog);
2574
+ yield effects.takeEvery(actions.openDeleteUserDialog, openDeleteUserDialog);
2575
+ yield effects.takeEvery(actions.closeDeleteUserDialog, closeDeleteUserDialog);
2576
+ }
2577
+ /*********************************
2578
+ * Preview Sagas
2579
+ *********************************/
2580
+ function* loadUsersMock({ payload }) {
2581
+ var _a, _b, _c, _d;
2582
+ const { silentLoading, callback } = payload;
2583
+ const teamState = yield selectTeamState();
2584
+ const pageSize = (_a = payload.pageSize) !== null && _a !== void 0 ? _a : teamState.pageSize;
2585
+ const pageOffset = (_b = payload.pageOffset) !== null && _b !== void 0 ? _b : teamState.pageOffset;
2586
+ const filter = (_c = payload.filter) !== null && _c !== void 0 ? _c : teamState.filter;
2587
+ const sort = (_d = payload.sort) !== null && _d !== void 0 ? _d : teamState.sort;
2588
+ yield effects.put(actions.setTeamLoader({ key: exports.TeamStateKeys.USERS, value: !silentLoading }));
2589
+ yield effects.put(actions.setTeamState({
2590
+ pageSize,
2591
+ pageOffset,
2592
+ filter,
2593
+ sort,
2594
+ }));
2595
+ const totalPages = 2;
2596
+ const totalItems = 10;
2597
+ yield delay();
2598
+ yield effects.put(actions.setTeamState({ users: usersDemo, totalPages, totalItems, roles: rolesDemo, permissions: permissionsDemo }));
2599
+ yield effects.put(actions.setTeamLoader({ key: exports.TeamStateKeys.USERS, value: false }));
2600
+ callback === null || callback === void 0 ? void 0 : callback(usersDemo);
2601
+ }
2602
+ function* loadRolesMock({ payload }) {
2603
+ var _a;
2604
+ yield effects.put(actions.setTeamLoader({ key: exports.TeamStateKeys.ROLES_AND_PERMISSIONS, value: true }));
2605
+ yield delay();
2606
+ yield effects.put(actions.setTeamState({ roles: rolesDemo, permissions: permissionsDemo }));
2607
+ yield effects.put(actions.setTeamLoader({ key: exports.TeamStateKeys.ROLES_AND_PERMISSIONS, value: true }));
2608
+ (_a = payload === null || payload === void 0 ? void 0 : payload.callback) === null || _a === void 0 ? void 0 : _a.call(payload, { roles: rolesDemo, permissions: permissionsDemo });
2609
+ }
2610
+ function* addUserMock({ payload }) {
2611
+ const { callback } = payload, body = tslib.__rest(payload, ["callback"]);
2612
+ const teamState = yield selectTeamState();
2613
+ yield effects.put(actions.setTeamState({ addUserDialogState: Object.assign(Object.assign({}, teamState.addUserDialogState), { loading: true }) }));
2614
+ yield delay();
2615
+ const newUser = Object.assign(Object.assign(Object.assign({}, userTeamDemo), body), { id: `${uuid.v4()}` });
2616
+ callback === null || callback === void 0 ? void 0 : callback(newUser);
2617
+ yield effects.put(actions.setTeamState({
2618
+ users: [newUser, ...teamState.users],
2619
+ addUserDialogState: { open: false, loading: false },
2620
+ }));
2621
+ }
2622
+ function* updateUserMock({ payload }) {
2623
+ var _a;
2624
+ const { callback, profileImage } = payload, body = tslib.__rest(payload, ["callback", "profileImage"]);
2625
+ const { id: userId } = body;
2626
+ const teamState = yield selectTeamState();
2627
+ const oldUserData = teamState.users.find((user) => user.id === body.id);
2628
+ yield effects.put(actions.setTeamLoader({ key: exports.TeamStateKeys.UPDATE_USER, value: userId || '' }));
2629
+ yield effects.put(actions.setTeamState({ addUserDialogState: Object.assign(Object.assign({}, teamState.addUserDialogState), { loading: true }) }));
2630
+ yield effects.put(actions.setTeamState({
2631
+ addUserDialogState: Object.assign(Object.assign({}, teamState.addUserDialogState), { loading: true }),
2632
+ users: teamState.users.map((user) => {
2633
+ if (user.id === body.id) {
2634
+ return Object.assign(Object.assign({}, user), body);
2635
+ }
2636
+ return user;
2637
+ }),
2638
+ }));
2639
+ if (oldUserData.roleIds.length > 0 && ((_a = body.roleIds) === null || _a === void 0 ? void 0 : _a.length) === 0) {
2640
+ body.roleIds = [''];
2641
+ }
2642
+ yield delay();
2643
+ const newUser = Object.assign(Object.assign({}, oldUserData), body);
2644
+ callback === null || callback === void 0 ? void 0 : callback(newUser);
2645
+ yield effects.put(actions.setTeamState({
2646
+ users: teamState.users.map((user) => user.id === newUser.id
2647
+ ? Object.assign(Object.assign(Object.assign({}, user), newUser), { createdAt: user.createdAt, customData: user.customData, lastLogin: user.lastLogin }) : user),
2648
+ }));
2649
+ yield effects.put(actions.setTeamLoader({ key: exports.TeamStateKeys.UPDATE_USER, value: false }));
2650
+ }
2651
+ function* deleteUserMock({ payload }) {
2652
+ const { callback } = payload, body = tslib.__rest(payload, ["callback"]);
2653
+ const teamState = yield selectTeamState();
2654
+ yield effects.put(actions.setTeamState({ deleteUserDialogState: Object.assign(Object.assign({}, teamState.deleteUserDialogState), { loading: true }) }));
2655
+ yield delay();
2656
+ callback === null || callback === void 0 ? void 0 : callback(true);
2657
+ yield effects.put(actions.setTeamState({
2658
+ users: teamState.users.filter((user) => user.id !== body.userId),
2659
+ deleteUserDialogState: { open: false, loading: false },
2660
+ }));
2661
+ }
2662
+ function* resendActivationLinkMock({ payload }) {
2663
+ const { callback } = payload, body = tslib.__rest(payload, ["callback"]);
2664
+ yield effects.put(actions.setTeamLoader({ key: exports.TeamStateKeys.RESEND_ACTIVATE_LINK, value: body.userId }));
2665
+ yield delay();
2666
+ callback === null || callback === void 0 ? void 0 : callback(true);
2667
+ yield effects.put(actions.setTeamLoader({ key: exports.TeamStateKeys.RESEND_ACTIVATE_LINK, value: false }));
2668
+ }
2669
+ function* resendInvitationLinkMock({ payload }) {
2670
+ const { callback } = payload, body = tslib.__rest(payload, ["callback"]);
2671
+ yield effects.put(actions.setTeamLoader({ key: exports.TeamStateKeys.RESEND_INVITATION_LINK, value: body.email }));
2672
+ yield delay();
2673
+ callback === null || callback === void 0 ? void 0 : callback(true);
2674
+ yield effects.put(actions.setTeamLoader({ key: exports.TeamStateKeys.RESEND_INVITATION_LINK, value: false }));
2675
+ }
2676
+ function* teamSagasMock() {
2677
+ yield effects.takeLatest(actions.loadUsers, loadUsersMock);
2678
+ yield effects.takeLatest(actions.loadRoles, loadRolesMock);
2679
+ yield effects.takeEvery(actions.addUser, addUserMock);
2680
+ yield effects.takeEvery(actions.updateUser, updateUserMock);
2681
+ yield effects.takeEvery(actions.deleteUser, deleteUserMock);
2682
+ yield effects.takeEvery(actions.resendActivationLink, resendActivationLinkMock);
2683
+ yield effects.takeEvery(actions.resendInvitationLink, resendInvitationLinkMock);
2684
+ yield effects.takeEvery(actions.openAddUserDialog, openAddUserDialog);
2685
+ yield effects.takeEvery(actions.closeAddUserDialog, closeAddUserDialog);
2686
+ yield effects.takeEvery(actions.openDeleteUserDialog, openDeleteUserDialog);
2687
+ yield effects.takeEvery(actions.closeDeleteUserDialog, closeDeleteUserDialog);
2688
+ }
2689
+
2690
+ function* loadSocialLoginsConfigurations() {
2691
+ try {
2692
+ yield effects.put(actions.setSocialLoginsState({ loading: true }));
2693
+ const socialLoginsConfig = yield effects.call(restApi.api.auth.getSocialLoginProviders);
2694
+ yield effects.put(actions.setSocialLoginsState({ socialLoginsConfig, loading: false, firstLoad: false }));
2695
+ }
2696
+ catch (e) {
2697
+ yield effects.put(actions.setSocialLoginsState({ error: e.message, loading: false, firstLoad: false }));
2698
+ }
2699
+ }
2700
+ function* loadSocialLoginsConfigurationsV2() {
2701
+ try {
2702
+ const context = yield effects.select((state) => state.root.context);
2703
+ yield effects.put(actions.setSocialLoginsState({ loading: true }));
2704
+ const socialLoginsConfigV2 = yield effects.call(restApi.api.auth.getSocialLoginProvidersV2);
2705
+ const socialLoginsConfigWithFullUrl = socialLoginsConfigV2.map((_a) => {
2706
+ var { authorizationUrl } = _a, config = tslib.__rest(_a, ["authorizationUrl"]);
2707
+ const baseUrl = restApi.fetch.getBaseUrl(context, authorizationUrl !== null && authorizationUrl !== void 0 ? authorizationUrl : '');
2708
+ return (Object.assign(Object.assign({}, config), { authorizationUrl: authorizationUrl ? `${baseUrl}${authorizationUrl}` : null }));
2709
+ });
2710
+ yield effects.put(actions.setSocialLoginsState({ socialLoginsConfigV2: socialLoginsConfigWithFullUrl, loading: false, firstLoad: false }));
2711
+ }
2712
+ catch (e) {
2713
+ yield effects.put(actions.setSocialLoginsState({ error: e.message, loading: false, firstLoad: false }));
2714
+ }
2715
+ }
2716
+ function* loginViaSocialLogin(_a) {
2717
+ var _b, _c, _d;
2718
+ var _e = _a.payload, { events, url } = _e, payload = tslib.__rest(_e, ["events", "url"]);
2719
+ try {
2720
+ yield effects.put(actions.setSocialLoginsState({ loading: true }));
2721
+ const { email, isNewUser } = yield effects.call(restApi.api.auth.loginViaSocialLogin, payload);
2722
+ if (isNewUser) {
2723
+ (_b = events === null || events === void 0 ? void 0 : events.signUpComplete) === null || _b === void 0 ? void 0 : _b.call(events, { email, url, authenticationType: exports.AuthenticationTypes.SOCIAL_LOGIN, socialProvider: payload.provider });
2724
+ (_c = events === null || events === void 0 ? void 0 : events.userVerified) === null || _c === void 0 ? void 0 : _c.call(events, { email, origin: exports.UserVeirifedOriginTypes.SOCIAL_LOGIN });
2725
+ }
2726
+ yield effects.put(actions.setLoginState({ email, isNewUser }));
2727
+ yield refreshToken();
2728
+ yield effects.put(actions.setSocialLoginsState({ loading: false }));
2729
+ }
2730
+ catch (e) {
2731
+ yield effects.put(actions.setSocialLoginsState({ loading: false, error: (_d = e.message) !== null && _d !== void 0 ? _d : 'Failed to authenticate', firstLoad: false }));
2732
+ }
2733
+ }
2734
+ function* setSocialLoginError({ payload }) {
2735
+ yield effects.put(actions.setSocialLoginsState({ error: payload.error, loading: false, firstLoad: false }));
2736
+ }
2737
+ function* socialLoginsSaga() {
2738
+ yield effects.takeLeading(actions.loadSocialLoginsConfiguration, loadSocialLoginsConfigurations);
2739
+ yield effects.takeLeading(actions.loadSocialLoginsConfigurationV2, loadSocialLoginsConfigurationsV2);
2740
+ yield effects.takeLeading(actions.loginViaSocialLogin, loginViaSocialLogin);
2741
+ yield effects.takeLatest(actions.setSocialLoginError, setSocialLoginError);
2742
+ }
2743
+
2744
+ exports.ApiStateKeys = void 0;
2745
+ (function (ApiStateKeys) {
2746
+ ApiStateKeys["LOAD_API_TOKENS"] = "LOAD_API_TOKENS";
2747
+ ApiStateKeys["ADD_API_TOKEN"] = "ADD_API_TOKEN";
2748
+ ApiStateKeys["DELETE_API_TOKEN"] = "DELETE_API_TOKEN";
2749
+ })(exports.ApiStateKeys || (exports.ApiStateKeys = {}));
2750
+
2751
+ function* loadApiTokensData({ payload: apiTokenType }) {
2752
+ yield effects.put(actions.setApiTokensState({ apiTokenType }));
2753
+ try {
2754
+ yield effects.put(actions.setApiTokensLoader({ key: exports.ApiStateKeys.LOAD_API_TOKENS, value: true }));
2755
+ if (apiTokenType === 'user') {
2756
+ const apiTokensData = yield effects.call(restApi.api.auth.getUserApiTokensData);
2757
+ yield effects.put(actions.setApiTokensState({ apiTokensDataUser: apiTokensData !== null && apiTokensData !== void 0 ? apiTokensData : [] }));
2758
+ }
2759
+ else {
2760
+ const apiTenantTokensData = yield effects.call(restApi.api.auth.getTenantApiTokensData);
2761
+ const { items: roles } = yield effects.call(restApi.api.teams.loadAvailableRoles);
2762
+ const { items: permissions } = yield effects.call(restApi.api.teams.loadAvailablePermissions);
2763
+ yield effects.put(actions.setApiTokensState({
2764
+ apiTokensDataTenant: apiTenantTokensData !== null && apiTenantTokensData !== void 0 ? apiTenantTokensData : [],
2765
+ roles: roles !== null && roles !== void 0 ? roles : [],
2766
+ permissions: permissions !== null && permissions !== void 0 ? permissions : [],
2767
+ }));
2768
+ }
2769
+ yield effects.put(actions.setApiTokensLoader({ key: exports.ApiStateKeys.LOAD_API_TOKENS, value: false }));
2770
+ }
2771
+ catch (e) {
2772
+ yield effects.put(actions.setApiTokensError({ key: exports.ApiStateKeys.LOAD_API_TOKENS, value: e.message }));
2773
+ yield effects.put(actions.setApiTokensLoader({ key: exports.ApiStateKeys.LOAD_API_TOKENS, value: false }));
2774
+ }
2775
+ }
2776
+ function* addUserApiToken({ payload }) {
2777
+ const { description, callback } = payload;
2778
+ const { apiTokensDataUser } = yield effects.select((state) => state.auth.apiTokensState);
2779
+ try {
2780
+ yield effects.put(actions.setApiTokensLoader({ key: exports.ApiStateKeys.ADD_API_TOKEN, value: true }));
2781
+ const data = yield effects.call(restApi.api.auth.updateUserApiTokensData, { description });
2782
+ yield effects.put(actions.setApiTokensState({ showAddTokenDialog: false }));
2783
+ yield effects.delay(200);
2784
+ yield effects.put(actions.setApiTokensState({
2785
+ apiTokensDataUser: [data, ...apiTokensDataUser],
2786
+ successDialog: { open: true, secret: data.secret, clientId: data.clientId },
2787
+ }));
2788
+ yield effects.put(actions.setApiTokensLoader({ key: exports.ApiStateKeys.ADD_API_TOKEN, value: false }));
2789
+ callback === null || callback === void 0 ? void 0 : callback(null);
2790
+ }
2791
+ catch (e) {
2792
+ yield effects.put(actions.setApiTokensError({ key: exports.ApiStateKeys.ADD_API_TOKEN, value: e.message }));
2793
+ yield effects.put(actions.setApiTokensLoader({ key: exports.ApiStateKeys.ADD_API_TOKEN, value: false }));
2794
+ callback === null || callback === void 0 ? void 0 : callback(null, e.message);
2795
+ }
2796
+ }
2797
+ function* addTenantApiToken({ payload }) {
2798
+ const { description, roleIds, callback } = payload;
2799
+ const { apiTokensDataTenant } = yield effects.select((state) => state.auth.apiTokensState);
2800
+ try {
2801
+ yield effects.put(actions.setApiTokensLoader({ key: exports.ApiStateKeys.ADD_API_TOKEN, value: true }));
2802
+ const data = yield effects.call(restApi.api.auth.updateTenantApiTokensData, { description, roleIds });
2803
+ yield effects.put(actions.setApiTokensState({ showAddTokenDialog: false }));
2804
+ yield effects.delay(200);
2805
+ yield effects.put(actions.setApiTokensState({
2806
+ apiTokensDataTenant: [data, ...apiTokensDataTenant],
2807
+ successDialog: { open: true, secret: data.secret, clientId: data.clientId },
2808
+ }));
2809
+ yield effects.put(actions.setApiTokensLoader({ key: exports.ApiStateKeys.ADD_API_TOKEN, value: false }));
2810
+ callback === null || callback === void 0 ? void 0 : callback(null);
2811
+ }
2812
+ catch (e) {
2813
+ yield effects.put(actions.setApiTokensError({ key: exports.ApiStateKeys.ADD_API_TOKEN, value: e.message }));
2814
+ yield effects.put(actions.setApiTokensLoader({ key: exports.ApiStateKeys.ADD_API_TOKEN, value: false }));
2815
+ callback === null || callback === void 0 ? void 0 : callback(null, e.message);
2816
+ }
2817
+ }
2818
+ function* deleteUserApiToken({ payload }) {
2819
+ const { apiTokensDataUser } = yield effects.select((state) => state.auth.apiTokensState);
2820
+ try {
2821
+ yield effects.put(actions.setApiTokensLoader({ key: exports.ApiStateKeys.DELETE_API_TOKEN, value: true }));
2822
+ yield effects.call(restApi.api.auth.deleteUserApiToken, { tokenId: payload });
2823
+ yield effects.put(actions.setApiTokensState({
2824
+ apiTokensDataUser: apiTokensDataUser.filter((i) => i.clientId !== payload),
2825
+ deleteTokenDialog: { open: false, clientId: payload },
2826
+ }));
2827
+ yield effects.put(actions.setApiTokensLoader({ key: exports.ApiStateKeys.DELETE_API_TOKEN, value: false }));
2828
+ }
2829
+ catch (e) {
2830
+ yield effects.put(actions.setApiTokensError({ key: exports.ApiStateKeys.DELETE_API_TOKEN, value: e.message }));
2831
+ yield effects.put(actions.setApiTokensLoader({ key: exports.ApiStateKeys.DELETE_API_TOKEN, value: false }));
2832
+ }
2833
+ }
2834
+ function* deleteTenantApiToken({ payload }) {
2835
+ const { apiTokensDataTenant } = yield effects.select((state) => state.auth.apiTokensState);
2836
+ try {
2837
+ yield effects.put(actions.setApiTokensLoader({ key: exports.ApiStateKeys.DELETE_API_TOKEN, value: true }));
2838
+ yield effects.call(restApi.api.auth.deleteTenantApiToken, { tokenId: payload });
2839
+ yield effects.put(actions.setApiTokensState({
2840
+ apiTokensDataTenant: apiTokensDataTenant.filter((i) => i.clientId !== payload),
2841
+ deleteTokenDialog: { open: false, clientId: payload },
2842
+ }));
2843
+ yield effects.put(actions.setApiTokensLoader({ key: exports.ApiStateKeys.DELETE_API_TOKEN, value: false }));
2844
+ }
2845
+ catch (e) {
2846
+ yield effects.put(actions.setApiTokensError({ key: exports.ApiStateKeys.DELETE_API_TOKEN, value: e.message }));
2847
+ yield effects.put(actions.setApiTokensLoader({ key: exports.ApiStateKeys.DELETE_API_TOKEN, value: false }));
2848
+ }
2849
+ }
2850
+ function* loadApiTokens({ payload }) {
2851
+ var _a, _b;
2852
+ if (!(payload === null || payload === void 0 ? void 0 : payload.silentLoading)) {
2853
+ yield effects.put(actions.setApiTokensLoader({ key: exports.ApiStateKeys.LOAD_API_TOKENS, value: true }));
2854
+ }
2855
+ try {
2856
+ const [apiTokensDataUser = [], apiTokensDataTenant = []] = yield effects.all([
2857
+ effects.call(restApi.api.auth.getUserApiTokensData),
2858
+ effects.call(restApi.api.auth.getTenantApiTokensData),
2859
+ ]);
2860
+ yield effects.put(actions.setApiTokensState({
2861
+ apiTokensDataUser,
2862
+ apiTokensDataTenant,
2863
+ }));
2864
+ yield effects.put(actions.setApiTokensLoader({ key: exports.ApiStateKeys.LOAD_API_TOKENS, value: false }));
2865
+ (_a = payload === null || payload === void 0 ? void 0 : payload.callback) === null || _a === void 0 ? void 0 : _a.call(payload, true);
2866
+ }
2867
+ catch (e) {
2868
+ yield effects.put(actions.setApiTokensError({ key: exports.ApiStateKeys.LOAD_API_TOKENS, value: e.message }));
2869
+ yield effects.put(actions.setApiTokensLoader({ key: exports.ApiStateKeys.LOAD_API_TOKENS, value: false }));
2870
+ (_b = payload === null || payload === void 0 ? void 0 : payload.callback) === null || _b === void 0 ? void 0 : _b.call(payload, null, e);
2871
+ }
2872
+ }
2873
+ function* apiTokensSaga() {
2874
+ yield effects.takeLeading(actions.loadApiTokens, loadApiTokens);
2875
+ yield effects.takeLeading(actions.initApiTokensData, loadApiTokensData);
2876
+ yield effects.takeEvery(actions.addUserApiToken, addUserApiToken);
2877
+ yield effects.takeEvery(actions.addTenantApiToken, addTenantApiToken);
2878
+ yield effects.takeLatest(actions.deleteTenantApiToken, deleteTenantApiToken);
2879
+ yield effects.takeLatest(actions.deleteUserApiToken, deleteUserApiToken);
2880
+ }
2881
+ /*********************************
2882
+ * Preview Sagas
2883
+ *********************************/
2884
+ function* loadApiTokensDataMock({ payload: apiTokenType }) {
2885
+ var _a;
2886
+ yield effects.put(actions.setApiTokensState({ apiTokenType }));
2887
+ yield effects.put(actions.setApiTokensLoader({ key: exports.ApiStateKeys.LOAD_API_TOKENS, value: true }));
2888
+ if (apiTokenType === 'user') {
2889
+ yield effects.delay(200);
2890
+ const apiTokensData = [apiTokensDataDemo];
2891
+ yield effects.put(actions.setApiTokensState({ apiTokensDataUser: apiTokensData !== null && apiTokensData !== void 0 ? apiTokensData : [] }));
2892
+ }
2893
+ else {
2894
+ yield effects.delay(200);
2895
+ yield effects.put(actions.setApiTokensState({
2896
+ apiTokensDataTenant: (_a = [apiTokensDataTenantDemo]) !== null && _a !== void 0 ? _a : [],
2897
+ roles: rolesDemo !== null && rolesDemo !== void 0 ? rolesDemo : [],
2898
+ permissions: permissionsDemo !== null && permissionsDemo !== void 0 ? permissionsDemo : [],
2899
+ }));
2900
+ }
2901
+ yield effects.put(actions.setApiTokensLoader({ key: exports.ApiStateKeys.LOAD_API_TOKENS, value: false }));
2902
+ }
2903
+ function* addTenantApiTokenMock({ payload }) {
2904
+ const { description, roleIds, callback } = payload;
2905
+ yield effects.put(actions.setApiTokensLoader({ key: exports.ApiStateKeys.ADD_API_TOKEN, value: true }));
2906
+ const { apiTokensDataTenant } = yield effects.select((state) => state.auth.apiTokensState);
2907
+ const newToken = Object.assign(Object.assign({}, apiTokensDataTenantDemo), { description,
2908
+ roleIds, clientId: `CLIENT_ID_${uuid.v4()}` });
2909
+ yield effects.put(actions.setApiTokensState({ showAddTokenDialog: false }));
2910
+ yield effects.delay(200);
2911
+ yield effects.put(actions.setApiTokensState({
2912
+ apiTokensDataTenant: [...apiTokensDataTenant, newToken],
2913
+ successDialog: { open: true, secret: newToken.secret, clientId: newToken.clientId },
2914
+ }));
2915
+ yield effects.delay(200);
2916
+ yield effects.put(actions.setApiTokensLoader({ key: exports.ApiStateKeys.ADD_API_TOKEN, value: false }));
2917
+ callback === null || callback === void 0 ? void 0 : callback(null);
2918
+ }
2919
+ function* deleteTenantApiTokenMock({ payload }) {
2920
+ yield effects.put(actions.setApiTokensLoader({ key: exports.ApiStateKeys.DELETE_API_TOKEN, value: true }));
2921
+ yield effects.delay(200);
2922
+ const apiTokensDataTenant = [apiTokensDataTenantDemo];
2923
+ yield effects.put(actions.setApiTokensState({
2924
+ apiTokensDataTenant: apiTokensDataTenant.filter((i) => i.clientId !== payload),
2925
+ deleteTokenDialog: { open: false, clientId: payload },
2926
+ }));
2927
+ yield effects.put(actions.setApiTokensLoader({ key: exports.ApiStateKeys.DELETE_API_TOKEN, value: false }));
2928
+ }
2929
+ function* loadApiTokensMock({ payload }) {
2930
+ var _a;
2931
+ if (!(payload === null || payload === void 0 ? void 0 : payload.silentLoading)) {
2932
+ yield effects.put(actions.setApiTokensLoader({ key: exports.ApiStateKeys.LOAD_API_TOKENS, value: true }));
2933
+ }
2934
+ const apiTokensDataUser = [apiTokensDataDemo];
2935
+ const apiTokensDataTenant = [apiTokensDataTenantDemo];
2936
+ yield effects.put(actions.setApiTokensState({
2937
+ apiTokensDataUser,
2938
+ apiTokensDataTenant,
2939
+ }));
2940
+ yield effects.delay(200);
2941
+ yield effects.put(actions.setApiTokensLoader({ key: exports.ApiStateKeys.LOAD_API_TOKENS, value: false }));
2942
+ (_a = payload === null || payload === void 0 ? void 0 : payload.callback) === null || _a === void 0 ? void 0 : _a.call(payload, true);
2943
+ }
2944
+ function* apiTokensSagaMock() {
2945
+ yield effects.takeLeading(actions.loadApiTokens, loadApiTokensMock);
2946
+ yield effects.takeLeading(actions.initApiTokensData, loadApiTokensDataMock);
2947
+ yield effects.takeEvery(actions.addTenantApiToken, addTenantApiTokenMock);
2948
+ yield effects.takeLatest(actions.deleteTenantApiToken, deleteTenantApiTokenMock);
2949
+ }
2950
+
2951
+ function* loadSecurityPolicy() {
2952
+ yield effects.put(actions.setSecurityPolicyGlobalState({ loading: true, error: null }));
2953
+ try {
2954
+ const policy = yield effects.call(restApi.api.auth.getGlobalSecurityPolicy);
2955
+ yield effects.put(actions.setSecurityPolicyGlobalState({ policy, loading: false }));
2956
+ }
2957
+ catch (e) {
2958
+ yield effects.put(actions.setSecurityPolicyGlobalState({ error: e.message, loading: false }));
2959
+ }
2960
+ yield effects.put(actions.loadSecurityPolicyMfa());
2961
+ yield effects.put(actions.loadSecurityPolicyLockout());
2962
+ yield effects.put(actions.loadSecurityPolicyCaptcha());
2963
+ }
2964
+ function* loadPublicSecurityPolicy() {
2965
+ yield effects.put(actions.setSecurityPolicyPublicState({ loading: true, error: null }));
2966
+ try {
2967
+ const policy = yield effects.call(restApi.api.auth.getVendorConfig);
2968
+ yield effects.put(actions.setSecurityPolicyPublicState({ policy, loading: false }));
2969
+ }
2970
+ catch (e) {
2971
+ yield effects.put(actions.setSecurityPolicyPublicState({ error: e.message, loading: false }));
2972
+ }
2973
+ }
2974
+ function* loadSecurityPolicyMfa() {
2975
+ yield effects.put(actions.setSecurityPolicyMfaState({ loading: true, error: null }));
2976
+ try {
2977
+ const policy = yield effects.call(restApi.api.auth.getMfaPolicy);
2978
+ yield effects.put(actions.setSecurityPolicyMfaState({ policy, loading: false }));
2979
+ }
2980
+ catch (e) {
2981
+ yield effects.put(actions.setSecurityPolicyMfaState({ error: e.message, loading: false }));
2982
+ }
2983
+ }
2984
+ function* saveSecurityPolicyMfa(_a) {
2985
+ var _b = _a.payload, { callback } = _b, newSecurityPolicy = tslib.__rest(_b, ["callback"]);
2986
+ yield effects.put(actions.setSecurityPolicyMfaState({ saving: true, error: null }));
2987
+ try {
2988
+ const policy = yield effects.call(restApi.api.auth.saveMfaPolicy, newSecurityPolicy);
2989
+ yield effects.put(actions.setSecurityPolicyMfaState({ policy, saving: false }));
2990
+ callback === null || callback === void 0 ? void 0 : callback(policy);
2991
+ }
2992
+ catch (e) {
2993
+ yield effects.put(actions.setSecurityPolicyMfaState({ saving: false, error: e.message }));
2994
+ callback === null || callback === void 0 ? void 0 : callback(null, e);
2995
+ }
2996
+ }
2997
+ function* loadSecurityPolicyLockout() {
2998
+ yield effects.put(actions.setSecurityPolicyLockoutState({ loading: true, error: null }));
2999
+ try {
3000
+ const policy = yield effects.call(restApi.api.auth.getLockoutPolicy);
3001
+ yield effects.put(actions.setSecurityPolicyLockoutState({ policy, loading: false }));
3002
+ }
3003
+ catch (e) {
3004
+ yield effects.put(actions.setSecurityPolicyLockoutState({ error: e.message, loading: false }));
3005
+ }
3006
+ }
3007
+ function* saveSecurityPolicyLockout(_a) {
3008
+ var _b = _a.payload, { callback } = _b, newSecurityPolicy = tslib.__rest(_b, ["callback"]);
3009
+ yield effects.put(actions.setSecurityPolicyLockoutState({ saving: true, error: null }));
3010
+ try {
3011
+ const policy = yield effects.call(restApi.api.auth.saveLockoutPolicy, newSecurityPolicy);
3012
+ yield effects.put(actions.setSecurityPolicyLockoutState({ policy, saving: false }));
3013
+ callback === null || callback === void 0 ? void 0 : callback(policy);
3014
+ }
3015
+ catch (e) {
3016
+ yield effects.put(actions.setSecurityPolicyLockoutState({ saving: false, error: e.message }));
3017
+ callback === null || callback === void 0 ? void 0 : callback(null, e);
3018
+ }
3019
+ }
3020
+ function* loadSecurityPolicyCaptcha() {
3021
+ yield effects.put(actions.setSecurityPolicyLockoutState({ loading: true, error: null }));
3022
+ try {
3023
+ const policy = yield effects.call(restApi.api.auth.getCaptchaPolicy);
3024
+ yield effects.put(actions.setSecurityPolicyCaptchaState({ policy, loading: false }));
3025
+ }
3026
+ catch (e) {
3027
+ yield effects.put(actions.setSecurityPolicyCaptchaState({ error: e.message, loading: false }));
3028
+ }
3029
+ }
3030
+ function* loadSecurityPolicyPasswordHistory() {
3031
+ yield effects.put(actions.setSecurityPolicyPasswordHistoryState({ loading: true, error: null }));
3032
+ try {
3033
+ const policy = yield effects.call(restApi.api.auth.getPasswordHistoryPolicy);
3034
+ yield effects.put(actions.setSecurityPolicyPasswordHistoryState({ policy, loading: false }));
3035
+ }
3036
+ catch (e) {
3037
+ yield effects.put(actions.setSecurityPolicyPasswordHistoryState({ error: e.message, loading: false }));
3038
+ }
3039
+ }
3040
+ function* saveSecurityPolicyPasswordHistory(_a) {
3041
+ var _b = _a.payload, { callback } = _b, newSecurityPolicy = tslib.__rest(_b, ["callback"]);
3042
+ yield effects.put(actions.setSecurityPolicyPasswordHistoryState({ saving: true, error: null }));
3043
+ try {
3044
+ const policy = yield effects.call(restApi.api.auth.savePasswordHistoryPolicy, newSecurityPolicy);
3045
+ yield effects.put(actions.setSecurityPolicyPasswordHistoryState({ policy, saving: false }));
3046
+ callback === null || callback === void 0 ? void 0 : callback(policy);
3047
+ }
3048
+ catch (e) {
3049
+ yield effects.put(actions.setSecurityPolicyPasswordHistoryState({ saving: false, error: e.message }));
3050
+ callback === null || callback === void 0 ? void 0 : callback(null, e);
3051
+ }
3052
+ }
3053
+ function* loadVendorPasswordConfig() {
3054
+ yield effects.put(actions.setSecurityPolicyPasswordState({ loading: true, error: null }));
3055
+ try {
3056
+ const policy = yield effects.call(restApi.api.auth.getPasswordConfigPolicy);
3057
+ yield effects.put(actions.setSecurityPolicyPasswordState({ policy, loading: false }));
3058
+ }
3059
+ catch (e) {
3060
+ yield effects.put(actions.setSecurityPolicyPasswordState({ error: e.message, loading: false }));
3061
+ }
3062
+ }
3063
+ function* securityPolicySagas() {
3064
+ yield effects.takeLeading(actions.loadSecurityPolicy, loadSecurityPolicy);
3065
+ yield effects.takeEvery(actions.saveSecurityPolicyMfa, saveSecurityPolicyMfa);
3066
+ yield effects.takeEvery(actions.loadSecurityPolicyMfa, loadSecurityPolicyMfa);
3067
+ yield effects.takeEvery(actions.saveSecurityPolicyLockout, saveSecurityPolicyLockout);
3068
+ yield effects.takeEvery(actions.loadSecurityPolicyLockout, loadSecurityPolicyLockout);
3069
+ yield effects.takeEvery(actions.loadSecurityPolicyCaptcha, loadSecurityPolicyCaptcha);
3070
+ yield effects.takeEvery(actions.saveSecurityPolicyPasswordHistory, saveSecurityPolicyPasswordHistory);
3071
+ yield effects.takeEvery(actions.loadSecurityPolicyPasswordHistory, loadSecurityPolicyPasswordHistory);
3072
+ yield effects.takeEvery(actions.loadVendorPasswordConfig, loadVendorPasswordConfig);
3073
+ yield effects.takeEvery(actions.loadPublicSecurityPolicy, loadPublicSecurityPolicy);
3074
+ }
3075
+ /*********************************
3076
+ * Preview Sagas
3077
+ *********************************/
3078
+ function* loadPublicSecurityPolicyMock() {
3079
+ yield effects.put(actions.setSecurityPolicyPublicState({ loading: true, error: null }));
3080
+ try {
3081
+ yield effects.put(actions.setSecurityPolicyPublicState({ policy: publicSecurityPolicy, loading: false }));
3082
+ }
3083
+ catch (e) {
3084
+ yield effects.put(actions.setSecurityPolicyPublicState({ error: e.message, loading: false }));
3085
+ }
3086
+ }
3087
+ function* loadSecurityPolicyMock() {
3088
+ yield effects.put(actions.setSecurityPolicyGlobalState({ loading: true, error: null }));
3089
+ yield delay();
3090
+ yield effects.put(actions.setSecurityPolicyGlobalState({ policy: policyDemo, loading: false }));
3091
+ yield effects.put(actions.loadSecurityPolicyMfa());
3092
+ yield effects.put(actions.loadSecurityPolicyLockout());
3093
+ yield effects.put(actions.loadSecurityPolicyCaptcha());
3094
+ }
3095
+ function* loadSecurityPolicyMfaMock() {
3096
+ yield effects.put(actions.setSecurityPolicyMfaState({ loading: true, error: null }));
3097
+ yield delay();
3098
+ yield effects.put(actions.setSecurityPolicyMfaState({ policy: policyMfaDemo, loading: false }));
3099
+ }
3100
+ function* saveSecurityPolicyMfaMock(_a) {
3101
+ var _b;
3102
+ var _c = _a.payload, { callback } = _c, newSecurityPolicy = tslib.__rest(_c, ["callback"]);
3103
+ yield effects.put(actions.setSecurityPolicyMfaState({ saving: true, error: null }));
3104
+ const policy = Object.assign(Object.assign({}, policyLockoutDemo), { id: (_b = newSecurityPolicy.id) !== null && _b !== void 0 ? _b : policyLockoutDemo.id, enforceMFAType: newSecurityPolicy.enforceMFAType });
3105
+ yield delay();
3106
+ yield effects.put(actions.setSecurityPolicyMfaState({ policy, saving: false }));
3107
+ callback === null || callback === void 0 ? void 0 : callback(policy);
3108
+ }
3109
+ function* loadSecurityPolicyLockoutMock() {
3110
+ yield effects.put(actions.setSecurityPolicyLockoutState({ loading: true, error: null }));
3111
+ yield delay();
3112
+ yield effects.put(actions.setSecurityPolicyLockoutState({ policy: policyLockoutDemo, loading: false }));
3113
+ }
3114
+ function* saveSecurityPolicyLockoutMock(_a) {
3115
+ var _b = _a.payload, { callback } = _b, newSecurityPolicy = tslib.__rest(_b, ["callback"]);
3116
+ yield effects.put(actions.setSecurityPolicyLockoutState({ saving: true, error: null }));
3117
+ yield delay();
3118
+ const policy = Object.assign(Object.assign(Object.assign({}, newSecurityPolicy), policyLockoutDemo), { id: newSecurityPolicy.id ? newSecurityPolicy.id : policyLockoutDemo.id });
3119
+ callback === null || callback === void 0 ? void 0 : callback(policy);
3120
+ yield effects.put(actions.setSecurityPolicyLockoutState({ policy, saving: false }));
3121
+ }
3122
+ function* loadSecurityPolicyCaptchaMock() {
3123
+ yield effects.put(actions.setSecurityPolicyLockoutState({ loading: true, error: null }));
3124
+ yield delay();
3125
+ yield effects.put(actions.setSecurityPolicyLockoutState({ policy: policyLockoutDemo, loading: false }));
3126
+ }
3127
+ function* loadSecurityPolicyPasswordHistoryMock() {
3128
+ yield effects.put(actions.setSecurityPolicyPasswordHistoryState({ loading: true, error: null }));
3129
+ yield delay();
3130
+ yield effects.put(actions.setSecurityPolicyPasswordHistoryState({ policy: policyPasswordHistoryDemo, loading: false }));
3131
+ }
3132
+ function* saveSecurityPolicyPasswordHistoryMock(_a) {
3133
+ var _b = _a.payload, { callback } = _b, newSecurityPolicy = tslib.__rest(_b, ["callback"]);
3134
+ yield effects.put(actions.setSecurityPolicyPasswordHistoryState({ saving: true, error: null }));
3135
+ yield delay();
3136
+ const policy = Object.assign(Object.assign(Object.assign({}, newSecurityPolicy), policyPasswordHistoryDemo), { id: newSecurityPolicy.id ? newSecurityPolicy.id : policyPasswordHistoryDemo.id });
3137
+ callback === null || callback === void 0 ? void 0 : callback(policy);
3138
+ yield effects.put(actions.setSecurityPolicyPasswordHistoryState({ policy, saving: false }));
3139
+ }
3140
+ function* securityPolicySagasMock() {
3141
+ yield effects.takeLeading(actions.loadSecurityPolicy, loadSecurityPolicyMock);
3142
+ yield effects.takeEvery(actions.loadPublicSecurityPolicy, loadPublicSecurityPolicyMock);
3143
+ yield effects.takeEvery(actions.saveSecurityPolicyMfa, saveSecurityPolicyMfaMock);
3144
+ yield effects.takeEvery(actions.loadSecurityPolicyMfa, loadSecurityPolicyMfaMock);
3145
+ yield effects.takeEvery(actions.saveSecurityPolicyLockout, saveSecurityPolicyLockoutMock);
3146
+ yield effects.takeEvery(actions.loadSecurityPolicyLockout, loadSecurityPolicyLockoutMock);
3147
+ yield effects.takeEvery(actions.loadSecurityPolicyCaptcha, loadSecurityPolicyCaptchaMock);
3148
+ yield effects.takeEvery(actions.saveSecurityPolicyPasswordHistory, saveSecurityPolicyPasswordHistoryMock);
3149
+ yield effects.takeEvery(actions.loadSecurityPolicyPasswordHistory, loadSecurityPolicyPasswordHistoryMock);
3150
+ }
3151
+
3152
+ function* saveAccountSettings({ payload }) {
3153
+ var _a, _b;
3154
+ try {
3155
+ yield effects.put(actions.setAccountSettingsState({ loading: true }));
3156
+ const { accountSettingsState } = yield effects.select((state) => state.auth);
3157
+ const { address, timezone, dateFormat, timeFormat, currency, logo } = accountSettingsState;
3158
+ const body = yield effects.call(restApi.api.accountSettings.updateSettings, Object.assign({ address,
3159
+ timezone,
3160
+ dateFormat,
3161
+ timeFormat,
3162
+ currency,
3163
+ logo }, payload));
3164
+ yield effects.put(actions.setAccountSettingsState(Object.assign(Object.assign({}, body), { loading: false })));
3165
+ (_a = payload.callback) === null || _a === void 0 ? void 0 : _a.call(payload, body);
3166
+ }
3167
+ catch (e) {
3168
+ yield effects.put(actions.setAccountSettingsState({ loading: false, error: e.message }));
3169
+ (_b = payload.callback) === null || _b === void 0 ? void 0 : _b.call(payload, null, e);
3170
+ }
3171
+ }
3172
+ function* loadAccountSettings({ payload }) {
3173
+ yield effects.put(actions.setAccountSettingsState({ loading: !(payload === null || payload === void 0 ? void 0 : payload.silentLoading), error: null }));
3174
+ try {
3175
+ const body = yield effects.call(restApi.api.accountSettings.getSettings);
3176
+ yield effects.put(actions.setAccountSettingsState(Object.assign(Object.assign({}, body), { loading: false })));
3177
+ }
3178
+ catch (e) {
3179
+ yield effects.put(actions.setAccountSettingsState({ loading: false, error: e.message }));
3180
+ }
3181
+ }
3182
+ function* accountSettingsSaga() {
3183
+ yield effects.takeLeading(actions.saveAccountSettings, saveAccountSettings);
3184
+ yield effects.takeLeading(actions.loadAccountSettings, loadAccountSettings);
3185
+ }
3186
+ /*********************************
3187
+ * Preview Sagas
3188
+ *********************************/
3189
+ function* saveAccountSettingsMock({ payload }) {
3190
+ var _a;
3191
+ yield effects.put(actions.setAccountSettingsState({ loading: true }));
3192
+ yield delay();
3193
+ const { accountSettingsState } = yield effects.select((state) => state.auth);
3194
+ const { address, timezone, dateFormat, timeFormat, currency, logo } = accountSettingsState;
3195
+ const body = Object.assign({ address,
3196
+ timezone,
3197
+ dateFormat,
3198
+ timeFormat,
3199
+ currency,
3200
+ logo }, payload);
3201
+ yield effects.put(actions.setAccountSettingsState(Object.assign(Object.assign({}, body), { loading: false })));
3202
+ (_a = payload.callback) === null || _a === void 0 ? void 0 : _a.call(payload, body);
3203
+ }
3204
+ function* loadAccountSettingsMock({ payload }) {
3205
+ yield effects.put(actions.setAccountSettingsState({ loading: !(payload === null || payload === void 0 ? void 0 : payload.silentLoading), error: null }));
3206
+ yield delay();
3207
+ yield effects.put(actions.setAccountSettingsState({
3208
+ address: 'Tel-aviv',
3209
+ timezone: 'Asia/Jerusalem',
3210
+ dateFormat: 'DD/MM/YYYY',
3211
+ timeFormat: 'HH:mm',
3212
+ currency: 'USD',
3213
+ loading: false,
3214
+ }));
3215
+ }
3216
+ function* accountSettingsSagaMock() {
3217
+ yield effects.takeLeading(actions.saveAccountSettings, saveAccountSettingsMock);
3218
+ yield effects.takeLeading(actions.loadAccountSettings, loadAccountSettingsMock);
3219
+ }
3220
+
3221
+ function* switchTenant({ payload: { tenantId, callback } }) {
3222
+ yield effects.put(actions.setState({ isLoading: true }));
3223
+ try {
3224
+ yield effects.call(restApi.api.tenants.switchTenant, { tenantId });
3225
+ yield effects.call(refreshToken);
3226
+ const callbackConsumed = callback === null || callback === void 0 ? void 0 : callback(true);
3227
+ if (!callbackConsumed) {
3228
+ yield effects.put(actions.setState({ isLoading: false }));
3229
+ }
3230
+ }
3231
+ catch (e) {
3232
+ yield effects.put(actions.setState({ isLoading: false }));
3233
+ callback === null || callback === void 0 ? void 0 : callback(false, e);
3234
+ }
3235
+ }
3236
+ function* loadTenants({ payload }) {
3237
+ var _a, _b;
3238
+ yield effects.put(actions.setTenantsState({ loading: true }));
3239
+ try {
3240
+ const tenants = yield effects.call(restApi.api.tenants.getTenants);
3241
+ yield effects.put(actions.setTenantsState({ tenants, loading: false }));
3242
+ (_a = payload === null || payload === void 0 ? void 0 : payload.callback) === null || _a === void 0 ? void 0 : _a.call(payload, []);
3243
+ }
3244
+ catch (e) {
3245
+ (_b = payload === null || payload === void 0 ? void 0 : payload.callback) === null || _b === void 0 ? void 0 : _b.call(payload, [], e);
3246
+ yield effects.put(actions.setTenantsState({ loading: false }));
3247
+ }
3248
+ }
3249
+ function* loadSubTenants({ payload }) {
3250
+ var _a, _b;
3251
+ yield effects.put(actions.setTenantsState({ loading: true }));
3252
+ try {
3253
+ const subTenants = yield effects.call(restApi.api.tenants.getSubTenants);
3254
+ yield effects.put(actions.setTenantsState({ subTenants, loading: false }));
3255
+ (_a = payload === null || payload === void 0 ? void 0 : payload.callback) === null || _a === void 0 ? void 0 : _a.call(payload, true);
3256
+ }
3257
+ catch (e) {
3258
+ yield effects.put(actions.setTenantsState({ loading: false }));
3259
+ (_b = payload === null || payload === void 0 ? void 0 : payload.callback) === null || _b === void 0 ? void 0 : _b.call(payload, null, e);
3260
+ }
3261
+ }
3262
+ function* tenantsSagas() {
3263
+ yield effects.takeEvery(actions.loadTenants, loadTenants);
3264
+ yield effects.takeEvery(actions.loadSubTenants, loadSubTenants);
3265
+ yield effects.takeEvery(actions.switchTenant, switchTenant);
3266
+ }
3267
+ /*********************************
3268
+ * Preview Sagas
3269
+ *********************************/
3270
+ function* loadTenantsMock({}) {
3271
+ yield effects.put(actions.setTenantsState({ loading: true }));
3272
+ yield delay();
3273
+ yield effects.put(actions.setTenantsState({ tenants: tenantsDemo, loading: false }));
3274
+ }
3275
+ function* tenantsSagasMock() {
3276
+ yield effects.takeEvery(actions.loadTenants, loadTenantsMock);
3277
+ }
3278
+
3279
+ function* loadRolesAndPermissions({ payload }) {
3280
+ var _a;
3281
+ yield effects.put(actions.setRolesState({ loading: !((_a = payload === null || payload === void 0 ? void 0 : payload.silentLoading) !== null && _a !== void 0 ? _a : false), error: null }));
3282
+ try {
3283
+ const result = yield effects.all([
3284
+ effects.call(restApi.api.roles.getRoles),
3285
+ effects.call(restApi.api.roles.getPermissions),
3286
+ effects.call(restApi.api.roles.getPermissionCategories),
3287
+ ]);
3288
+ const [roles, permissions, permissionCategories] = result;
3289
+ yield effects.put(actions.setRolesState({ roles, permissions, permissionCategories, loading: false }));
3290
+ }
3291
+ catch (e) {
3292
+ yield effects.put(actions.setRolesState({ error: e.message, loading: false }));
3293
+ }
3294
+ }
3295
+ function* addRole(_a) {
3296
+ var _b = _a.payload, { callback } = _b, body = tslib.__rest(_b, ["callback"]);
3297
+ yield effects.put(actions.setRolesState({ saving: true }));
3298
+ try {
3299
+ const role = yield effects.call(restApi.api.roles.addRole, body);
3300
+ const roles = yield effects.call(restApi.api.roles.getRoles);
3301
+ yield effects.put(actions.loadRolesAndPermissions({ silentLoading: true }));
3302
+ yield effects.put(actions.setRolesState({ roles, saving: false }));
3303
+ callback === null || callback === void 0 ? void 0 : callback(role);
3304
+ }
3305
+ catch (e) {
3306
+ yield effects.put(actions.setRolesState({ error: e.message, saving: false }));
3307
+ callback === null || callback === void 0 ? void 0 : callback(null, e);
3308
+ }
3309
+ }
3310
+ function* deleteRole(_a) {
3311
+ var _b = _a.payload, { callback } = _b, body = tslib.__rest(_b, ["callback"]);
3312
+ yield effects.put(actions.setRolesState({ saving: true }));
3313
+ try {
3314
+ yield effects.call(restApi.api.roles.deleteRole, body);
3315
+ yield effects.put(actions.loadRolesAndPermissions({ silentLoading: true }));
3316
+ yield effects.put(actions.setRolesState({ saving: false }));
3317
+ callback === null || callback === void 0 ? void 0 : callback(true);
3318
+ }
3319
+ catch (e) {
3320
+ yield effects.put(actions.setRolesState({ error: e.message, saving: false }));
3321
+ callback === null || callback === void 0 ? void 0 : callback(false, e);
3322
+ }
3323
+ }
3324
+ function* updateRole(_a) {
3325
+ var _b = _a.payload, { callback } = _b, body = tslib.__rest(_b, ["callback"]);
3326
+ yield effects.put(actions.setRolesState({ saving: true }));
3327
+ try {
3328
+ const role = yield effects.call(restApi.api.roles.updateRole, body);
3329
+ yield effects.put(actions.loadRolesAndPermissions({ silentLoading: true }));
3330
+ yield effects.put(actions.setRolesState({ saving: false }));
3331
+ callback === null || callback === void 0 ? void 0 : callback(role);
3332
+ }
3333
+ catch (e) {
3334
+ yield effects.put(actions.setRolesState({ error: e.message, saving: false }));
3335
+ callback === null || callback === void 0 ? void 0 : callback(null, e);
3336
+ }
3337
+ }
3338
+ function* attachPermissionsToRole(_a) {
3339
+ var _b = _a.payload, { callback } = _b, body = tslib.__rest(_b, ["callback"]);
3340
+ yield effects.put(actions.setRolesState({ saving: true }));
3341
+ try {
3342
+ const role = yield effects.call(restApi.api.roles.attachPermissionsToRole, body);
3343
+ yield effects.put(actions.loadRolesAndPermissions({ silentLoading: true }));
3344
+ yield effects.put(actions.setRolesState({ saving: false }));
3345
+ callback === null || callback === void 0 ? void 0 : callback(role);
3346
+ }
3347
+ catch (e) {
3348
+ yield effects.put(actions.setRolesState({ error: e.message, saving: false }));
3349
+ callback === null || callback === void 0 ? void 0 : callback(null, e);
3350
+ }
3351
+ }
3352
+ function* attachPermissionToRoles(_a) {
3353
+ var _b = _a.payload, { callback } = _b, body = tslib.__rest(_b, ["callback"]);
3354
+ yield effects.put(actions.setRolesState({ saving: true }));
3355
+ try {
3356
+ const permission = yield effects.call(restApi.api.roles.attachPermissionToRoles, body);
3357
+ yield effects.put(actions.loadRolesAndPermissions({ silentLoading: true }));
3358
+ yield effects.put(actions.setRolesState({ saving: false }));
3359
+ callback === null || callback === void 0 ? void 0 : callback(permission);
3360
+ }
3361
+ catch (e) {
3362
+ yield effects.put(actions.setRolesState({ error: e.message, saving: false }));
3363
+ callback === null || callback === void 0 ? void 0 : callback(null, e);
3364
+ }
3365
+ }
3366
+ function* rolesSagas() {
3367
+ yield effects.takeLeading(actions.loadRolesAndPermissions, loadRolesAndPermissions);
3368
+ yield effects.takeEvery(actions.addRole, addRole);
3369
+ yield effects.takeEvery(actions.deleteRole, deleteRole);
3370
+ yield effects.takeEvery(actions.updateRole, updateRole);
3371
+ yield effects.takeEvery(actions.attachPermissionsToRole, attachPermissionsToRole);
3372
+ yield effects.takeEvery(actions.attachPermissionToRoles, attachPermissionToRoles);
3373
+ }
3374
+
3375
+ function* resetPhoneNumber(_a) {
3376
+ var _b = _a.payload, { callback } = _b, body = tslib.__rest(_b, ["callback"]);
3377
+ yield effects.put(actions.setResetPhoneNumberState({ loading: true }));
3378
+ try {
3379
+ const res = yield effects.call(restApi.api.auth.resetPhoneNumber, body);
3380
+ yield effects.put(actions.setResetPhoneNumberState({ loading: false, error: undefined, resetPhoneNumberToken: res.resetPhoneNumberToken, step: exports.ResetPhoneNumberStep.VerifyResetPhoneNumber }));
3381
+ yield effects.put(actions.setLoginState({ email: body.email }));
3382
+ }
3383
+ catch (e) {
3384
+ yield effects.put(actions.setResetPhoneNumberState({ loading: false, error: e.message }));
3385
+ callback === null || callback === void 0 ? void 0 : callback(null, e);
3386
+ }
3387
+ }
3388
+ function* verifyResetPhoneNumber(_a) {
3389
+ var _b = _a.payload, { callback } = _b, body = tslib.__rest(_b, ["callback"]);
3390
+ yield effects.put(actions.setResetPhoneNumberState({ loading: true }));
3391
+ try {
3392
+ const res = yield effects.call(restApi.api.auth.verifyResetPhoneNumber, body);
3393
+ yield effects.put(actions.setResetPhoneNumberState({ loading: false, error: undefined, changePhoneNumberToken: res.changePhoneNumberToken, step: exports.ResetPhoneNumberStep.ChangePhoneNumber }));
3394
+ callback === null || callback === void 0 ? void 0 : callback(true);
3395
+ }
3396
+ catch (e) {
3397
+ yield effects.put(actions.setResetPhoneNumberState({ loading: false, error: e.message }));
3398
+ callback === null || callback === void 0 ? void 0 : callback(null, e);
3399
+ }
3400
+ }
3401
+ function* changePhoneNumber(_a) {
3402
+ var _b = _a.payload, { callback } = _b, body = tslib.__rest(_b, ["callback"]);
3403
+ yield effects.put(actions.setResetPhoneNumberState({ loading: true }));
3404
+ try {
3405
+ const { onRedirectTo, routes } = yield effects.select(({ auth: { onRedirectTo, routes } }) => ({ onRedirectTo, routes }));
3406
+ yield effects.call(restApi.api.auth.changePhoneNumber, { phoneNumber: body.phoneNumber, changePhoneNumberToken: body.changePhoneNumberToken });
3407
+ yield effects.put(actions.setLoginState({ step: exports.LoginStep.loginWithSmsOtc }));
3408
+ yield effects.put(actions.passwordlessPreLogin({
3409
+ type: restApi.AuthStrategyEnum.SmsCode,
3410
+ email: body.email,
3411
+ recaptchaToken: body.recaptchaToken,
3412
+ }));
3413
+ onRedirectTo(routes.loginUrl);
3414
+ yield effects.put(actions.setResetPhoneNumberState({ loading: false }));
3415
+ callback === null || callback === void 0 ? void 0 : callback(true);
3416
+ }
3417
+ catch (e) {
3418
+ yield effects.put(actions.setResetPhoneNumberState({ loading: false, error: e.message }));
3419
+ callback === null || callback === void 0 ? void 0 : callback(null, e);
3420
+ }
3421
+ }
3422
+ function* resetPhoneNumberSagas() {
3423
+ yield effects.takeLeading(actions.resetPhoneNumber, resetPhoneNumber);
3424
+ yield effects.takeLeading(actions.verifyResetPhoneNumber, verifyResetPhoneNumber);
3425
+ yield effects.takeLeading(actions.changePhoneNumber, changePhoneNumber);
3426
+ }
3427
+
3428
+ function* sagas() {
3429
+ yield effects.all([
3430
+ effects.call(loginSagas),
3431
+ effects.call(activateSagas),
3432
+ effects.call(acceptInvitationSagas),
3433
+ effects.call(forgotPasswordSagas),
3434
+ effects.call(resetPhoneNumberSagas),
3435
+ effects.call(ssoSagas$1),
3436
+ effects.call(ssoSagas),
3437
+ effects.call(profileSagas),
3438
+ effects.call(mfaSagas),
3439
+ effects.call(teamSagas),
3440
+ effects.call(socialLoginsSaga),
3441
+ effects.call(signUpSaga),
3442
+ effects.call(apiTokensSaga),
3443
+ effects.call(securityPolicySagas),
3444
+ effects.call(accountSettingsSaga),
3445
+ effects.call(tenantsSagas),
3446
+ effects.call(rolesSagas),
3447
+ ]);
3448
+ }
3449
+ function* mockSagas() {
3450
+ yield effects.all([
3451
+ effects.call(loginSagasMock),
3452
+ // call(activateSagas),
3453
+ // call(acceptInvitationSagas),
3454
+ // call(forgotPasswordSagas),
3455
+ // call(socialLoginsSaga),
3456
+ // call(signUpSaga),
3457
+ effects.call(ssoSagasMock),
3458
+ effects.call(profileSagasMock),
3459
+ effects.call(mfaSagasMock),
3460
+ effects.call(teamSagasMock),
3461
+ effects.call(apiTokensSagaMock),
3462
+ effects.call(securityPolicySagasMock),
3463
+ effects.call(accountSettingsSagaMock),
3464
+ effects.call(tenantsSagasMock),
3465
+ ]);
3466
+ }
3467
+
3468
+ // export store
3469
+ var authStore = {
3470
+ sagas,
3471
+ mockSagas,
3472
+ storeName: constants.authStoreName,
3473
+ initialState: initialState$1,
3474
+ reducer,
3475
+ actions,
3476
+ };
3477
+
3478
+ const initialState = {
3479
+ context: undefined,
3480
+ };
3481
+ const { reducer: rootReducer } = toolkit.createSlice({
3482
+ name: 'root',
3483
+ initialState,
3484
+ reducers: {
3485
+ setContext: {
3486
+ prepare: (context) => ({ payload: context }),
3487
+ reducer: (state, { payload }) => {
3488
+ restApi.ContextHolder.setContext(payload);
3489
+ return Object.assign(Object.assign({}, state), { context: payload });
3490
+ },
3491
+ },
3492
+ },
3493
+ });
3494
+ const createFronteggStore = (rootInitialState, storeHolder, previewMode = false, authInitialState, overrideInitialState, builderMode = false) => {
3495
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
3496
+ const isSSR = typeof window === 'undefined';
3497
+ let holder = storeHolder;
3498
+ if (isSSR && storeHolder == null) {
3499
+ throw Error('createFronteggStore(initState, storeHolder) failed, storeHolder must not be null in Server-Side rendering');
3500
+ }
3501
+ if (!holder) {
3502
+ holder = window;
3503
+ }
3504
+ if (!holder.store) {
3505
+ if (!previewMode && !builderMode) {
3506
+ restApi.ContextHolder.setContext(rootInitialState.context);
3507
+ }
3508
+ const sagaMiddleware = createSagaMiddleware__default['default']();
3509
+ const middleware = [
3510
+ ...toolkit.getDefaultMiddleware({ thunk: false, immutableCheck: false, serializableCheck: false }),
3511
+ sagaMiddleware,
3512
+ ];
3513
+ holder.store = toolkit.configureStore({
3514
+ middleware,
3515
+ preloadedState: {
3516
+ root: Object.assign(Object.assign({}, rootInitialState), { previewMode }),
3517
+ [authStore.storeName]: Object.assign(Object.assign(Object.assign(Object.assign({}, authStore.initialState), authInitialState), ((_a = overrideInitialState === null || overrideInitialState === void 0 ? void 0 : overrideInitialState.auth) !== null && _a !== void 0 ? _a : {})), { routes: Object.assign(Object.assign(Object.assign({}, authStore.initialState.routes), ((_b = authInitialState === null || authInitialState === void 0 ? void 0 : authInitialState.routes) !== null && _b !== void 0 ? _b : {})), ((_d = (_c = overrideInitialState === null || overrideInitialState === void 0 ? void 0 : overrideInitialState.auth) === null || _c === void 0 ? void 0 : _c.routes) !== null && _d !== void 0 ? _d : {})) }),
3518
+ [audits_index['default'].storeName]: Object.assign(Object.assign(Object.assign({}, audits_index['default'].initialState), ((_e = overrideInitialState === null || overrideInitialState === void 0 ? void 0 : overrideInitialState.auditLogs) !== null && _e !== void 0 ? _e : {})), { auditLogsState: Object.assign(Object.assign({}, audits_index['default'].initialState.auditLogsState), ((_g = (_f = overrideInitialState === null || overrideInitialState === void 0 ? void 0 : overrideInitialState.auditLogs) === null || _f === void 0 ? void 0 : _f.auditLogsState) !== null && _g !== void 0 ? _g : {})), auditsMetadataState: Object.assign(Object.assign({}, audits_index['default'].initialState.auditsMetadataState), ((_j = (_h = overrideInitialState === null || overrideInitialState === void 0 ? void 0 : overrideInitialState.auditLogs) === null || _h === void 0 ? void 0 : _h.auditsMetadataState) !== null && _j !== void 0 ? _j : {})) }),
3519
+ [saga.storeName]: Object.assign(Object.assign({}, saga.initialState), ((_k = overrideInitialState === null || overrideInitialState === void 0 ? void 0 : overrideInitialState.audits) !== null && _k !== void 0 ? _k : {})),
3520
+ [connectivity_index['default'].storeName]: connectivity_index['default'].initialState,
3521
+ [subscriptions_index['default'].storeName]: subscriptions_index['default'].initialState,
3522
+ [vendor_index.vendorStore.storeName]: vendor_index.vendorStore.initialState,
3523
+ },
3524
+ reducer: toolkit.combineReducers({
3525
+ root: rootReducer,
3526
+ [authStore.storeName]: authStore.reducer,
3527
+ [audits_index['default'].storeName]: audits_index['default'].reducer,
3528
+ [saga.storeName]: saga.reducer,
3529
+ [connectivity_index['default'].storeName]: connectivity_index['default'].reducer,
3530
+ [subscriptions_index['default'].storeName]: subscriptions_index['default'].reducer,
3531
+ [vendor_index.vendorStore.storeName]: vendor_index.vendorStore.reducer,
3532
+ }),
3533
+ });
3534
+ const rootSaga = function* () {
3535
+ yield effects.all([
3536
+ effects.call(authStore.sagas),
3537
+ effects.call(audits_index['default'].sagas),
3538
+ effects.call(saga.sagas),
3539
+ effects.call(connectivity_index['default'].sagas),
3540
+ effects.call(subscriptions_index['default'].sagas),
3541
+ effects.call(vendor_index.vendorStore.sagas),
3542
+ ]);
3543
+ };
3544
+ const rootMockSaga = function* () {
3545
+ yield effects.all([effects.call(authStore.mockSagas), effects.call(audits_index['default'].mockSagas), effects.call(subscriptions_index['default'].mockSagas)]);
3546
+ };
3547
+ if (previewMode) {
3548
+ holder.store.destroy = sagaMiddleware.run(rootMockSaga).cancel;
3549
+ holder.store.dispatch(actions.requestAuthorize(true));
3550
+ }
3551
+ else {
3552
+ holder.store.destroy = sagaMiddleware.run(rootSaga).cancel;
3553
+ }
3554
+ }
3555
+ return holder.store;
3556
+ };
3557
+
3558
+ exports.acceptInvitationState = acceptInvitationState;
3559
+ exports.accountSettingsState = accountSettingsState;
3560
+ exports.actions = actions;
3561
+ exports.actions$1 = actions$g;
3562
+ exports.actions$10 = actions$7;
3563
+ exports.actions$11 = actions$6;
3564
+ exports.actions$12 = actions$5;
3565
+ exports.actions$13 = actions$4;
3566
+ exports.actions$14 = actions$3;
3567
+ exports.actions$15 = actions$2;
3568
+ exports.actions$16 = actions$1;
3569
+ exports.actions$2 = actions$f;
3570
+ exports.actions$3 = actions$e;
3571
+ exports.actions$4 = actions$d;
3572
+ exports.actions$5 = actions$c;
3573
+ exports.actions$6 = actions$b;
3574
+ exports.actions$7 = actions$9;
3575
+ exports.actions$8 = actions$a;
3576
+ exports.actions$9 = actions$8;
3577
+ exports.activateState = activateState;
3578
+ exports.apiTokensState = apiTokensState;
3579
+ exports.authStore = authStore;
3580
+ exports.createFronteggStore = createFronteggStore;
3581
+ exports.forgotPasswordState = forgotPasswordState;
3582
+ exports.initialState = initialState$1;
3583
+ exports.loginState = loginState;
3584
+ exports.mfaState = mfaState;
3585
+ exports.mockSagas = mockSagas;
3586
+ exports.profileState = profileState;
3587
+ exports.reducer = reducer;
3588
+ exports.reducers = reducers$f;
3589
+ exports.reducers$1 = reducers$e;
3590
+ exports.reducers$10 = reducers$5;
3591
+ exports.reducers$11 = reducers$4;
3592
+ exports.reducers$12 = reducers$3;
3593
+ exports.reducers$13 = reducers$2;
3594
+ exports.reducers$14 = reducers$1;
3595
+ exports.reducers$15 = reducers;
3596
+ exports.reducers$2 = reducers$d;
3597
+ exports.reducers$3 = reducers$c;
3598
+ exports.reducers$4 = reducers$b;
3599
+ exports.reducers$5 = reducers$a;
3600
+ exports.reducers$6 = reducers$8;
3601
+ exports.reducers$7 = reducers$9;
3602
+ exports.reducers$8 = reducers$7;
3603
+ exports.reducers$9 = reducers$6;
3604
+ exports.resetPhoneNumberState = resetPhoneNumberState;
3605
+ exports.rolesState = rolesState;
3606
+ exports.sagas = sagas;
3607
+ exports.securityPolicyState = securityPolicyState;
3608
+ exports.signUpState = signUpState;
3609
+ exports.socialLoginState = socialLoginState;
3610
+ exports.ssoState = ssoState;
3611
+ exports.teamState = teamState;
3612
+ exports.tenantsState = tenantsState;