@or-sdk/auth 0.27.1 → 0.28.0-beta.2379.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.
package/src/Auth.ts CHANGED
@@ -1,11 +1,10 @@
1
1
  import axios from 'axios';
2
- import { Settings } from '@or-sdk/settings';
3
2
  import { SdkApi } from '@or-sdk/sdk-api';
3
+ import { Token } from '@or-sdk/base';
4
4
  import {
5
5
  AuthConfig,
6
6
  AuthResponse,
7
7
  Domain,
8
- HeadersObj,
9
8
  MultiUserLoginUserArgs,
10
9
  MultiUserResponse,
11
10
  MultiUserUpdateTwoFactorArgs,
@@ -14,6 +13,7 @@ import {
14
13
  SaveUserArgs,
15
14
  SignInArgs,
16
15
  User,
16
+ MultiUser,
17
17
  } from './types';
18
18
  import { generateFingerPrint, NoRightsError } from './utils';
19
19
  import { isNode } from 'browser-or-node';
@@ -41,7 +41,10 @@ export class Auth {
41
41
  private readonly cookiePollingInterval: number;
42
42
  public readonly expireInShort: number;
43
43
  public readonly expireInLong: number;
44
- private readonly _token?: string;
44
+ private _multiUser?: MultiUser;
45
+ private isRefreshingMultiUser = false;
46
+ private isRefreshingUser = false;
47
+ private readonly _multiUserToken?: Token;
45
48
  private loggedIn = false;
46
49
  private monitorCookieTimeout?: ReturnType<typeof setTimeout>;
47
50
 
@@ -60,7 +63,7 @@ export class Auth {
60
63
  expireInLong,
61
64
  allowIframe,
62
65
  authUiUrl,
63
- token,
66
+ multiUserToken,
64
67
  } = params;
65
68
 
66
69
  this.discoveryUrl = discoveryUrl;
@@ -86,7 +89,7 @@ export class Auth {
86
89
  this.expireInShort = expireInShort ? +expireInShort : defaultExpireInShort;
87
90
  this.expireInLong = expireInLong ? +expireInLong : defaultExpireInLong;
88
91
 
89
- this._token = token;
92
+ this._multiUserToken = multiUserToken;
90
93
  }
91
94
 
92
95
  public get domain(): Domain {
@@ -166,17 +169,6 @@ export class Auth {
166
169
  sameSite: this.allowIframe ? 'none' : 'lax',
167
170
  ...this.domain,
168
171
  });
169
- // Should be deleted after migration
170
- this.cookie.set(this.deprecatedCookieName, user, {
171
- path: '/',
172
- expires: nextExpiration,
173
- ...this.domain,
174
- });
175
- this.cookie.set(this.deprecatedUserExpireCookieName, expireIn, {
176
- path: '/',
177
- expires: nextExpiration,
178
- ...this.domain,
179
- });
180
172
  }
181
173
 
182
174
  /**
@@ -185,15 +177,24 @@ export class Auth {
185
177
  * instance.saveMultiUser(user, expiration);
186
178
  * ```
187
179
  */
188
- public saveMultiUser(user: User, expiration: number): void {
189
- this.cookie.set(this.multiUserCookieName!, user, {
190
- path: '/',
191
- expires: this._getNextExpiration(expiration),
192
- secure: true,
193
- ...this.domain,
180
+ public async saveMultiUser(user?: User, expireLong?: boolean) {
181
+ const sdkApi = new SdkApi({
182
+ token: user?.token || '',
183
+ discoveryUrl: this.discoveryUrl,
184
+ sdkUrl: this.sdkUrl,
194
185
  });
195
- }
196
186
 
187
+ const data = await sdkApi.makeRequest<MultiUser>({
188
+ method: 'get',
189
+ withCredentials: true,
190
+ params: {
191
+ expireLong,
192
+ },
193
+ route: '/multi-user/token',
194
+ });
195
+ this._multiUser = data;
196
+ return data;
197
+ }
197
198
  /**
198
199
  * Update cookie expiration
199
200
  * ```typescript
@@ -201,15 +202,21 @@ export class Auth {
201
202
  * ```
202
203
  */
203
204
  public updateCookieExpiration(): void {
204
- const user = this._getUser;
205
- const expire = this.getUserExpire();
206
- if (user) {
205
+ const user = this._getUser as any;
206
+ if (this._multiUser)
207
+ if (user?.expire < Date.now() + 1000 * 60)
208
+ this.refreshUserToken()
209
+ .catch(() => {
210
+ this.removeCookies();
211
+ this._multiUser = undefined;
212
+ });
213
+ if ((this._multiUser as any)?.expire < Date.now() + 1000 * 60) this.refreshMultiUserToken();
214
+
215
+ // user without mult
216
+ if (user && !user.multiUserId) {
217
+ const expire = this.getUserExpire();
207
218
  this._saveCookies(user, expire);
208
219
  }
209
- const multiUser = this.cookie.get(this.multiUserCookieName!);
210
- if (multiUser) {
211
- this.saveMultiUser(multiUser, expire);
212
- }
213
220
  }
214
221
 
215
222
  private _validateGuest(role: string, allowGuestLoginOverride = false): void {
@@ -228,26 +235,7 @@ export class Auth {
228
235
  * ```
229
236
  */
230
237
  public async saveUser({ long, user }: SaveUserArgs): Promise<void> {
231
- const key = long ? 'cookieExpirationLong' : 'cookieExpirationShort';
232
- const settingsApi = new Settings({
233
- token: user.token!,
234
- discoveryUrl: this.discoveryUrl,
235
- sdkUrl: this.sdkUrl,
236
- });
237
-
238
- let cookieExpirationDuration;
239
- try {
240
- cookieExpirationDuration = await settingsApi.getMergedSettings({ key });
241
- } catch (error) {
242
- // eslint-disable-next-line no-console
243
- console.log('Unable to fetch settingCookiesExpire from user Settings: ', error);
244
- }
245
-
246
- if (!cookieExpirationDuration) {
247
- cookieExpirationDuration = long ? this.expireInLong : this.expireInShort;
248
- }
249
-
250
- this._saveCookies(user, cookieExpirationDuration);
238
+ this._saveCookies(user, long ? this.expireInLong : this.expireInShort);
251
239
  }
252
240
 
253
241
  /**
@@ -282,6 +270,7 @@ export class Auth {
282
270
  verificationCode,
283
271
  fingerPrint,
284
272
  rememberTwoFactor,
273
+ expireLong: long,
285
274
  ... userToken ? { userToken } : {},
286
275
  };
287
276
 
@@ -295,13 +284,14 @@ export class Auth {
295
284
  method: 'POST',
296
285
  route: '/auth/token',
297
286
  data: options,
287
+ withCredentials: true,
298
288
  });
299
289
 
300
290
  this._validateGuest(user.role!, allowGuestLogin);
301
291
 
302
292
  if (!user.twoFactorCheck && !user.captchaCheck) {
303
293
  if (user.tokenType === 'multi-user') {
304
- this.saveMultiUser(user, long ? this.expireInLong : this.expireInShort);
294
+ this._multiUser = user;
305
295
  } else {
306
296
  await this.saveUser({
307
297
  long,
@@ -396,17 +386,6 @@ export class Auth {
396
386
  return user;
397
387
  }
398
388
 
399
- public get multiUserHeaders(): HeadersObj {
400
- const { token = '' } = this.cookie.get(this.multiUserCookieName!) || {};
401
- return { headers: { Authorization: token } };
402
- }
403
-
404
- private get token(): string {
405
- return this._token
406
- ? this._token
407
- : this.multiUserHeaders.headers.Authorization;
408
- }
409
-
410
389
  /**
411
390
  * Remove cookies
412
391
  * ```typescript
@@ -467,18 +446,18 @@ export class Auth {
467
446
  route: '/auth/fingerprint-token',
468
447
  }));
469
448
  }
470
- if (this.token) {
471
- const sdkApi = new SdkApi({
472
- token: this.token,
473
- discoveryUrl: this.discoveryUrl,
474
- sdkUrl: this.sdkUrl,
475
- });
476
449
 
477
- promises.push(sdkApi.makeRequest<void>({
478
- method: 'DELETE',
479
- route: '/multi-user/fingerprint-token',
480
- }));
481
- }
450
+ const sdkApi = new SdkApi({
451
+ token: '',
452
+ discoveryUrl: this.discoveryUrl,
453
+ sdkUrl: this.sdkUrl,
454
+ });
455
+
456
+ promises.push(sdkApi.makeRequest<void>({
457
+ method: 'DELETE',
458
+ route: '/multi-user/fingerprint-token',
459
+ withCredentials: true,
460
+ }));
482
461
  await Promise.all(promises);
483
462
  } catch (error) {
484
463
  // eslint-disable-next-line no-console
@@ -494,14 +473,16 @@ export class Auth {
494
473
  * ```
495
474
  */
496
475
  public async validateUser(allowGuestLogin = false, shouldNotSaveCookies = false,): Promise<User> {
497
- this._checkDeprecatedCookies();
498
476
  const userParams = this._getUser;
499
477
 
500
478
  if (!userParams) {
501
479
  return Promise.reject(new Error('No cached user params are available'));
502
480
  }
481
+ let user: any;
503
482
 
504
- const user = await this._validateToken(userParams.token!, allowGuestLogin);
483
+ if (userParams.expire < Date.now())
484
+ user = await this.refreshUserToken();
485
+ else user = await this._validateToken(userParams.token!, allowGuestLogin);
505
486
 
506
487
  if (!user.identityProvider && userParams.identityProvider) {
507
488
  user.identityProvider = userParams.identityProvider;
@@ -542,15 +523,15 @@ export class Auth {
542
523
  * ```
543
524
  */
544
525
  public async multiUserGetUsersList(): Promise<any> {
545
- if (!this.token) return false;
546
526
 
547
527
  const sdkApi = new SdkApi({
548
- token: this.token,
528
+ token: this.multiUserToken as string,
549
529
  discoveryUrl: this.discoveryUrl,
550
530
  sdkUrl: this.sdkUrl,
551
531
  });
552
532
 
553
533
  return sdkApi.makeRequest<any>({
534
+ withCredentials: true,
554
535
  method: 'GET',
555
536
  route: '/multi-user/list-users',
556
537
  });
@@ -568,12 +549,13 @@ export class Auth {
568
549
  */
569
550
  public async multiUserLoginUser({ accountId, id, long }: MultiUserLoginUserArgs): Promise<User> {
570
551
  const sdkApi = new SdkApi({
571
- token: this.token,
552
+ token: this.multiUserToken as string,
572
553
  discoveryUrl: this.discoveryUrl,
573
554
  sdkUrl: this.sdkUrl,
574
555
  });
575
556
 
576
557
  const user = await sdkApi.makeRequest<User>({
558
+ withCredentials: true,
577
559
  method: 'POST',
578
560
  route: '/multi-user/user-token',
579
561
  data: {
@@ -627,12 +609,13 @@ export class Auth {
627
609
  */
628
610
  public async multiUserGetProfile(): Promise<any> {
629
611
  const sdkApi = new SdkApi({
630
- token: this.token,
612
+ token: this.multiUserToken as string,
631
613
  discoveryUrl: this.discoveryUrl,
632
614
  sdkUrl: this.sdkUrl,
633
615
  });
634
616
 
635
617
  return sdkApi.makeRequest<any>({
618
+ withCredentials: true,
636
619
  method: 'GET',
637
620
  route: '/multi-user/profile',
638
621
  });
@@ -646,12 +629,13 @@ export class Auth {
646
629
  */
647
630
  public async multiUserSetProfile(profile: unknown): Promise<any> {
648
631
  const sdkApi = new SdkApi({
649
- token: this.token,
632
+ token: this.multiUserToken as string,
650
633
  discoveryUrl: this.discoveryUrl,
651
634
  sdkUrl: this.sdkUrl,
652
635
  });
653
636
 
654
637
  return sdkApi.makeRequest<any>({
638
+ withCredentials: true,
655
639
  method: 'POST',
656
640
  route: '/multi-user/profile',
657
641
  data: profile,
@@ -666,17 +650,19 @@ export class Auth {
666
650
  * @param token - Optional token to validate. If not provided, the method will use the token from the multiUserHeaders.
667
651
  */
668
652
  public async validateMultiUserToken(token?: string): Promise<any> {
669
- token = token || this.token;
670
653
  const sdkApi = new SdkApi({
671
- token: token,
654
+ token: token || this.multiUserToken as string,
672
655
  discoveryUrl: this.discoveryUrl,
673
656
  sdkUrl: this.sdkUrl,
674
657
  });
675
658
 
676
- return sdkApi.makeRequest<any>({
659
+ const data = await sdkApi.makeRequest<any>({
660
+ withCredentials: true,
677
661
  method: 'GET',
678
662
  route: '/multi-user/token',
679
663
  });
664
+ this._multiUser = data;
665
+ return data;
680
666
  }
681
667
 
682
668
  /**
@@ -691,12 +677,13 @@ export class Auth {
691
677
  */
692
678
  public async multiUserUploadIcon({ name, contentType, cacheControl = 'no-cache', file }: MultiUserUploadIconArgs): Promise<string> {
693
679
  const sdkApi = new SdkApi({
694
- token: this.token,
680
+ token: this.multiUserToken as string,
695
681
  discoveryUrl: this.discoveryUrl,
696
682
  sdkUrl: this.sdkUrl,
697
683
  });
698
684
 
699
685
  const data = await sdkApi.makeRequest<MultiUserUploadIconResponse>({
686
+ withCredentials: true,
700
687
  method: 'POST',
701
688
  route: '/multi-user/sign-upload-url',
702
689
  data: {
@@ -739,7 +726,7 @@ export class Auth {
739
726
  */
740
727
  public async confirmEmailChange({ token }: { token: string; }): Promise<any> {
741
728
  const sdkApi = new SdkApi({
742
- token: '',
729
+ token,
743
730
  discoveryUrl: this.discoveryUrl,
744
731
  sdkUrl: this.sdkUrl,
745
732
  });
@@ -766,7 +753,7 @@ export class Auth {
766
753
  */
767
754
  public async multiUserUpdateTwoFactor({ secret, enabled, codes, verificationCode }: MultiUserUpdateTwoFactorArgs): Promise<any> {
768
755
  const sdkApi = new SdkApi({
769
- token: this.token,
756
+ token: this.multiUserToken as string,
770
757
  discoveryUrl: this.discoveryUrl,
771
758
  sdkUrl: this.sdkUrl,
772
759
  });
@@ -774,6 +761,7 @@ export class Auth {
774
761
  return sdkApi.makeRequest<any>({
775
762
  method: 'PUT',
776
763
  route: '/multi-user/twofactor',
764
+ withCredentials: true,
777
765
  data: {
778
766
  secret,
779
767
  enabled,
@@ -783,4 +771,52 @@ export class Auth {
783
771
  });
784
772
  }
785
773
 
774
+ /**
775
+ * Regenerate user token to update expiration
776
+ * ```typescript
777
+ * const result = await instance.refreshUserToken();
778
+ * ```
779
+ */
780
+ async refreshUserToken(): Promise<User | undefined> {
781
+ this.isRefreshingUser = true;
782
+ try {
783
+ const user = this._getUser;
784
+ if (user)
785
+ return await this.multiUserLoginUser({
786
+ accountId: user.accountId,
787
+ id: user.userId,
788
+ long: this.getUserExpire() === this.expireInLong,
789
+ });
790
+ } catch (e: any) {
791
+ if (/No user token given/.test(e))
792
+ this.removeCookies();
793
+ }
794
+ finally {
795
+ this.isRefreshingUser = false;
796
+ }
797
+ }
798
+
799
+ /**
800
+ * Regenerate profile token to update expiration
801
+ * ```typescript
802
+ * const result = await instance.refreshMultiUserToken();
803
+ * ```
804
+ */
805
+ async refreshMultiUserToken(): Promise<MultiUser> {
806
+ this.isRefreshingMultiUser = true;
807
+ try {
808
+ return await this.saveMultiUser();
809
+ } finally {
810
+ this.isRefreshingMultiUser = false;
811
+ }
812
+ }
813
+
814
+ private get multiUserToken(): string | undefined {
815
+ if (typeof this._multiUserToken === 'string') {
816
+ return this._multiUserToken as string;
817
+ }
818
+ if (typeof this._multiUserToken === 'function') {
819
+ return (this._multiUserToken as Function)() as string;
820
+ }
821
+ }
786
822
  }
package/src/types.ts CHANGED
@@ -1,3 +1,5 @@
1
+ import { Token } from '@or-sdk/base';
2
+
1
3
  export type AuthConfig = {
2
4
  /**
3
5
  * Url of OneReach service discovery api
@@ -23,7 +25,8 @@ export type AuthConfig = {
23
25
  expireInLong?: number;
24
26
  allowIframe?: boolean;
25
27
 
26
- token?: string;
28
+ token?: Token;
29
+ multiUserToken?: Token;
27
30
  };
28
31
 
29
32
  export type Domain = {
@@ -41,6 +44,7 @@ export type User = {
41
44
  multiUserId?: string;
42
45
  identityProvider?: any;
43
46
  token?: string;
47
+ expire: number;
44
48
  twoFactorCheck?: boolean;
45
49
  };
46
50
 
@@ -106,3 +110,14 @@ export type MultiUserUpdateTwoFactorArgs = {
106
110
  codes?: any;
107
111
  verificationCode?: string;
108
112
  };
113
+
114
+ export type MultiUser = {
115
+ allow: boolean;
116
+ tokenType: string;
117
+ username: string;
118
+ userId: string;
119
+ role: string;
120
+ twoFactorEnabled: string;
121
+ identityProvider?: any;
122
+ expire: number;
123
+ };