@or-sdk/auth 0.21.2-auth.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.
Files changed (46) hide show
  1. package/dist/cjs/Auth.js +618 -0
  2. package/dist/cjs/Auth.js.map +1 -0
  3. package/dist/cjs/constants.js +2 -0
  4. package/dist/cjs/constants.js.map +1 -0
  5. package/dist/cjs/index.js +17 -0
  6. package/dist/cjs/index.js.map +1 -0
  7. package/dist/cjs/types.js +3 -0
  8. package/dist/cjs/types.js.map +1 -0
  9. package/dist/cjs/utils/NoRightsError.js +29 -0
  10. package/dist/cjs/utils/NoRightsError.js.map +1 -0
  11. package/dist/cjs/utils/generateFingerPrint.js +80 -0
  12. package/dist/cjs/utils/generateFingerPrint.js.map +1 -0
  13. package/dist/cjs/utils/index.js +11 -0
  14. package/dist/cjs/utils/index.js.map +1 -0
  15. package/dist/esm/Auth.js +450 -0
  16. package/dist/esm/Auth.js.map +1 -0
  17. package/dist/esm/constants.js +2 -0
  18. package/dist/esm/constants.js.map +1 -0
  19. package/dist/esm/index.js +3 -0
  20. package/dist/esm/index.js.map +1 -0
  21. package/dist/esm/types.js +2 -0
  22. package/dist/esm/types.js.map +1 -0
  23. package/dist/esm/utils/NoRightsError.js +8 -0
  24. package/dist/esm/utils/NoRightsError.js.map +1 -0
  25. package/dist/esm/utils/generateFingerPrint.js +40 -0
  26. package/dist/esm/utils/generateFingerPrint.js.map +1 -0
  27. package/dist/esm/utils/index.js +3 -0
  28. package/dist/esm/utils/index.js.map +1 -0
  29. package/dist/types/Auth.d.ts +56 -0
  30. package/dist/types/constants.d.ts +0 -0
  31. package/dist/types/index.d.ts +2 -0
  32. package/dist/types/types.d.ts +85 -0
  33. package/dist/types/utils/NoRightsError.d.ts +4 -0
  34. package/dist/types/utils/generateFingerPrint.d.ts +2 -0
  35. package/dist/types/utils/index.d.ts +2 -0
  36. package/package.json +40 -0
  37. package/src/Auth.ts +772 -0
  38. package/src/constants.ts +0 -0
  39. package/src/index.ts +2 -0
  40. package/src/types.ts +109 -0
  41. package/src/utils/NoRightsError.ts +9 -0
  42. package/src/utils/generateFingerPrint.ts +37 -0
  43. package/src/utils/index.ts +5 -0
  44. package/tsconfig.esm.json +9 -0
  45. package/tsconfig.json +7 -0
  46. package/tsconfig.types.json +9 -0
package/src/Auth.ts ADDED
@@ -0,0 +1,772 @@
1
+ import axios from 'axios';
2
+ import { Settings } from '@or-sdk/settings';
3
+ import { SdkApi } from '@or-sdk/sdk-api';
4
+ import {
5
+ AuthConfig,
6
+ AuthResponse,
7
+ Domain, HeadersObj, MultiUserLoginUserArgs,
8
+ MultiUserResponse, MultiUserUpdateTwoFactorArgs, MultiUserUploadIconArgs,
9
+ MultiUserUploadIconResponse, SaveUserArgs, SignInArgs,
10
+ User,
11
+ } from './types';
12
+ import { generateFingerPrint, NoRightsError } from './utils';
13
+ import { isNode } from 'browser-or-node';
14
+ import Cookie from 'universal-cookie';
15
+ import _ from 'lodash';
16
+
17
+ const defaultCookiePollingInterval = 500; // 0.5 second
18
+ const defaultExpireInShort = 3600000; // 1 hour
19
+ const defaultExpireInLong = 30758400000;
20
+
21
+ /**
22
+ * OneReach Auth service client
23
+ * ## Installation:
24
+ * ```
25
+ * $ npm i @or-sdk/auth
26
+ * ```
27
+ */
28
+ export class Auth {
29
+ private readonly discoveryUrl?: string;
30
+ private readonly sdkUrl?: string;
31
+ private readonly cookieDomain?: string;
32
+ private readonly cookie: Cookie;
33
+ private readonly userCookieName: string;
34
+ private readonly allowGuestLogin: boolean;
35
+ private readonly allowIframe?: boolean;
36
+ private readonly deprecatedCookieName: string;
37
+ private readonly deprecatedUserExpireCookieName: string;
38
+ private readonly deprecatedDomain: Domain;
39
+ private readonly multiUserCookieName?: string;
40
+ private readonly userExpireCookieName: string;
41
+ private readonly cookiePollingInterval: number;
42
+ private readonly expireInShort: number;
43
+ private readonly expireInLong: number;
44
+ private loggedIn = false;
45
+ private monitorCookieTimeout?: ReturnType<typeof setTimeout>;
46
+
47
+ /**
48
+ * ```typescript
49
+ * import { Auth } from '@or-sdk/auth'
50
+ * const auth = new Auth({
51
+ * discoveryUrl: 'http://example.nlu/endpoint',
52
+ * cookieDomain: '.domain.onereach.ai',
53
+ * allowGuestLogin: false,
54
+ * userCookieName: 'user-cookie-name',
55
+ * userExpireCookieName: 'user-expire-cookie-name',
56
+ * cookiePrefix: 'cookie-prefix',
57
+ * multiUserCookieName: 'multi-user-cookie-name',
58
+ * cookiePollingInterval: 500,
59
+ * expireInShort: 3600000,
60
+ * expireInLong: 30758400000,
61
+ * allowIframe: false,
62
+ * });
63
+ * ```
64
+ */
65
+ constructor(params: AuthConfig) {
66
+ const {
67
+ discoveryUrl, sdkUrl, cookieDomain, allowGuestLogin, userCookieName, userExpireCookieName, cookiePrefix,
68
+ multiUserCookieName, cookiePollingInterval, expireInShort, expireInLong, allowIframe,
69
+ } = params;
70
+
71
+ this.discoveryUrl = discoveryUrl;
72
+ this.sdkUrl = sdkUrl;
73
+
74
+ this.cookie = new Cookie();
75
+
76
+ this.cookieDomain = cookieDomain;
77
+ this.allowGuestLogin = Boolean(allowGuestLogin);
78
+ this.allowIframe = allowIframe;
79
+
80
+ // should be used for feature migration only. Should be deleted after all feature migrations happened!
81
+ this.deprecatedCookieName = userCookieName || 'user';
82
+ this.deprecatedUserExpireCookieName = userExpireCookieName || 'user_expire';
83
+ this.deprecatedDomain = { domain: '.onereach.ai' };
84
+
85
+ this.userCookieName = cookiePrefix ? cookiePrefix : `${userCookieName}_new`;
86
+ this.multiUserCookieName = multiUserCookieName;
87
+ this.userExpireCookieName = `${this.userCookieName}_expire`;
88
+
89
+ this.cookiePollingInterval = cookiePollingInterval || defaultCookiePollingInterval;
90
+ this.expireInShort = expireInShort ? +expireInShort : defaultExpireInShort;
91
+ this.expireInLong = expireInLong ? +expireInLong : defaultExpireInLong;
92
+ }
93
+
94
+ public get domain(): Domain {
95
+ return this.cookieDomain ? { domain: this.cookieDomain } : {};
96
+ }
97
+
98
+ private get _getUser(): User | null {
99
+ return this.cookie.get(this.userCookieName) || null;
100
+ }
101
+
102
+ /**
103
+ * Get user expire
104
+ * ```typescript
105
+ * const result = instance.getUserExpire();
106
+ * ```
107
+ */
108
+ public getUserExpire(cookieName?: string): number {
109
+ const expireCookie = this.cookie.get(cookieName || this.userExpireCookieName);
110
+ return expireCookie ? parseInt(expireCookie, 10) : this.expireInShort;
111
+ }
112
+
113
+ private _getNextExpiration(expireIn: number): Date {
114
+ return new Date(Date.now() + expireIn);
115
+ }
116
+
117
+ /**
118
+ * Stop cookie monitor
119
+ * ```typescript
120
+ * instance.stopCookieMonitor();
121
+ * ```
122
+ */
123
+ public stopCookieMonitor(): void {
124
+ if (window) {
125
+ clearTimeout(Number(this.monitorCookieTimeout));
126
+ }
127
+ }
128
+
129
+ /**
130
+ * Start cookie monitor
131
+ * ```typescript
132
+ * instance.monitorCookie(logoutCallback, loginCallback);
133
+ * ```
134
+ */
135
+ public monitorCookie(logoutCallback?: () => void, loginCallback?: (user: User) => void): void {
136
+ // just in case monitorCookie called multiple times in a row
137
+ // we only need one running constantly
138
+ this.stopCookieMonitor();
139
+ this.monitorCookieTimeout = setTimeout(() => {
140
+ const user = this._getUser;
141
+ if (user) {
142
+ if (!this.loggedIn) {
143
+ this.loggedIn = true;
144
+ }
145
+ if (_.isFunction(loginCallback)) { loginCallback(user); }
146
+ } else if (this.loggedIn) {
147
+ this.loggedIn = false;
148
+ if (_.isFunction(logoutCallback)) { logoutCallback(); }
149
+ }
150
+
151
+ this.monitorCookie(logoutCallback, loginCallback);
152
+ }, this.cookiePollingInterval);
153
+ }
154
+
155
+ private _saveCookies(user: User, expireIn: number): void {
156
+ const nextExpiration = this._getNextExpiration(expireIn);
157
+ this.cookie.set(this.userCookieName, user, {
158
+ path: '/',
159
+ expires: nextExpiration,
160
+ secure: true,
161
+ sameSite: this.allowIframe ? 'none' : 'lax',
162
+ ...this.domain,
163
+ });
164
+ this.cookie.set(this.userExpireCookieName, expireIn, {
165
+ path: '/',
166
+ expires: nextExpiration,
167
+ secure: true,
168
+ sameSite: this.allowIframe ? 'none' : 'lax',
169
+ ...this.domain,
170
+ });
171
+ // Should be deleted after migration
172
+ this.cookie.set(this.deprecatedCookieName, user, {
173
+ path: '/',
174
+ expires: nextExpiration,
175
+ ...this.domain,
176
+ });
177
+ this.cookie.set(this.deprecatedUserExpireCookieName, expireIn, {
178
+ path: '/',
179
+ expires: nextExpiration,
180
+ ...this.domain,
181
+ });
182
+ }
183
+
184
+ /**
185
+ * Save multi-user
186
+ * ```typescript
187
+ * instance.saveMultiUser(user, expiration);
188
+ * ```
189
+ */
190
+ public saveMultiUser(user: User, expiration: number): void {
191
+ this.cookie.set(this.multiUserCookieName!, user, {
192
+ path: '/',
193
+ expires: this._getNextExpiration(expiration),
194
+ secure: true,
195
+ ...this.domain,
196
+ });
197
+ }
198
+
199
+ /**
200
+ * Update cookie expiration
201
+ * ```typescript
202
+ * instance.updateCookieExpiration();
203
+ * ```
204
+ */
205
+ public updateCookieExpiration(): void {
206
+ const user = this._getUser;
207
+ const expire = this.getUserExpire();
208
+ if (user) {
209
+ this._saveCookies(user, expire);
210
+ }
211
+ const multiUser = this.cookie.get(this.multiUserCookieName!);
212
+ if (multiUser) {
213
+ this.saveMultiUser(multiUser, expire);
214
+ }
215
+ }
216
+
217
+ private _validateGuest(role: string, allowGuestLoginOverride = false): void {
218
+ if (!(this.allowGuestLogin || allowGuestLoginOverride) && _.toLower(role) === 'guest') {
219
+ throw new NoRightsError('Authorization for guests is not allowed');
220
+ }
221
+ }
222
+
223
+ /**
224
+ * Save user
225
+ * ```typescript
226
+ * await instance.saveUser({
227
+ * long: true,
228
+ * user: user
229
+ * });
230
+ * ```
231
+ */
232
+ public async saveUser({ long, user }: SaveUserArgs): Promise<void> {
233
+ const key = long ? 'cookieExpirationLong' : 'cookieExpirationShort';
234
+ const settingsApi = new Settings({
235
+ token: user.token!,
236
+ discoveryUrl: this.discoveryUrl,
237
+ sdkUrl: this.sdkUrl,
238
+ });
239
+
240
+ let cookieExpirationDuration;
241
+ try {
242
+ cookieExpirationDuration = await settingsApi.getMergedSettings({ key });
243
+ } catch (error) {
244
+ // eslint-disable-next-line no-console
245
+ console.log('Unable to fetch settingCookiesExpire from user Settings: ', error);
246
+ }
247
+
248
+ if (!cookieExpirationDuration) {
249
+ cookieExpirationDuration = long ? this.expireInLong : this.expireInShort;
250
+ }
251
+
252
+ this._saveCookies(user, cookieExpirationDuration);
253
+ }
254
+
255
+ /**
256
+ * Sign in
257
+ * ```typescript
258
+ * const user = await instance.signIn({
259
+ * credentials: {
260
+ * username: 'username',
261
+ * password: 'password'
262
+ * },
263
+ * long: true,
264
+ * captchaToken: 'captchaToken'
265
+ * });
266
+ * ```
267
+ */
268
+ public async signIn({
269
+ credentials,
270
+ long,
271
+ allowGuestLogin = false,
272
+ captchaToken,
273
+ isCaptchaV2Checkbox,
274
+ verificationCode,
275
+ userToken,
276
+ rememberTwoFactor,
277
+ }: SignInArgs): Promise<User> {
278
+ const fingerPrint = await generateFingerPrint();
279
+
280
+ const options = {
281
+ ...credentials,
282
+ captchaToken,
283
+ isCaptchaV2Checkbox,
284
+ verificationCode,
285
+ fingerPrint,
286
+ rememberTwoFactor,
287
+ ... userToken ? { userToken } : {},
288
+ };
289
+
290
+ const sdkApi = new SdkApi({
291
+ token: '',
292
+ discoveryUrl: this.discoveryUrl,
293
+ sdkUrl: this.sdkUrl,
294
+ });
295
+
296
+ const user = await sdkApi.makeRequest<AuthResponse>({
297
+ method: 'POST',
298
+ route: '/auth/token',
299
+ data: options,
300
+ });
301
+
302
+ this._validateGuest(user.role!, allowGuestLogin);
303
+
304
+ if (!user.twoFactorCheck && !user.captchaCheck) {
305
+ if (user.tokenType === 'multi-user') {
306
+ this.saveMultiUser(user, long ? this.expireInLong : this.expireInShort);
307
+ } else {
308
+ await this.saveUser({
309
+ long,
310
+ user,
311
+ });
312
+ }
313
+ }
314
+
315
+ return user;
316
+ }
317
+
318
+ private _checkDeprecatedCookies(): void {
319
+ const user = this.cookie.get(this.deprecatedCookieName);
320
+ if (user) {
321
+ const deprecatedUserExpireValue = this.getUserExpire(this.deprecatedUserExpireCookieName);
322
+ const nextExpiration = this._getNextExpiration(deprecatedUserExpireValue);
323
+ this.cookie.set(this.userCookieName, user, {
324
+ path: '/',
325
+ expires: nextExpiration,
326
+ secure: true,
327
+ ...this.domain,
328
+ });
329
+ this.cookie.set(this.userExpireCookieName, deprecatedUserExpireValue, {
330
+ path: '/',
331
+ expires: nextExpiration,
332
+ secure: true,
333
+ ...this.domain,
334
+ });
335
+ }
336
+ }
337
+
338
+ private async _validateToken(token: string, allowGuestLogin = false): Promise<User> {
339
+ const sdkApi = new SdkApi({
340
+ token,
341
+ discoveryUrl: this.discoveryUrl,
342
+ sdkUrl: this.sdkUrl,
343
+ });
344
+
345
+ const user = await sdkApi.makeRequest<User>({
346
+ method: 'GET',
347
+ route: '/auth/token',
348
+ });
349
+
350
+ this._validateGuest(user.role, allowGuestLogin);
351
+
352
+ return user;
353
+ }
354
+
355
+ /**
356
+ * Sign in with token
357
+ * ```typescript
358
+ * const user = await instance.signInWithToken({
359
+ * token: 'token'
360
+ * });
361
+ * ```
362
+ */
363
+ public async signInWithToken(
364
+ token: string | { token: string; allowGuestLogin?: boolean; shouldNotSaveCookies?: boolean; },
365
+ allowGuestLogin = false,
366
+ shouldNotSaveCookies = false
367
+ ): Promise<User> {
368
+ let userInfo = {};
369
+ if (_.isObject(token)) {
370
+ allowGuestLogin = _.get(token, 'allowGuestLogin', false);
371
+ shouldNotSaveCookies = _.get(token, 'shouldNotSaveCookies', false);
372
+ userInfo = _.get(token, 'userInfo', {});
373
+ token = token.token;
374
+ }
375
+
376
+ if (!token) {
377
+ return Promise.reject(new Error('No token given'));
378
+ }
379
+
380
+ this._checkDeprecatedCookies();
381
+
382
+ const user = await this._validateToken(token, allowGuestLogin);
383
+
384
+ _.assign(user, { token });
385
+
386
+ const allow = _.get(user, 'allow', false);
387
+ if (!allow) {
388
+ throw Error('Invalid Token');
389
+ }
390
+
391
+ if (!shouldNotSaveCookies) {
392
+ this._saveCookies({
393
+ ...userInfo,
394
+ ...user,
395
+ }, this.getUserExpire());
396
+ }
397
+
398
+ return user;
399
+ }
400
+
401
+ public get multiUserHeaders(): HeadersObj {
402
+ const { token = '' } = this.cookie.get(this.multiUserCookieName!) || {};
403
+ return { headers: { Authorization: token } };
404
+ }
405
+
406
+ /**
407
+ * Remove cookies
408
+ * ```typescript
409
+ * instance.removeCookies();
410
+ * ```
411
+ */
412
+ public removeCookies(): void {
413
+ this.cookie.remove(this.userExpireCookieName, {
414
+ path: '/',
415
+ ...this.domain,
416
+ });
417
+ this.cookie.remove(this.userCookieName, {
418
+ path: '/',
419
+ ...this.domain,
420
+ });
421
+ this.cookie.remove(this.multiUserCookieName!, {
422
+ path: '/',
423
+ ...this.domain,
424
+ });
425
+ // should be removed after feature migration only.
426
+ this.cookie.remove(this.deprecatedCookieName, {
427
+ path: '/',
428
+ ...this.domain,
429
+ });
430
+ this.cookie.remove(this.deprecatedUserExpireCookieName, {
431
+ path: '/',
432
+ ...this.domain,
433
+ });
434
+ this.cookie.remove(this.deprecatedCookieName, {
435
+ path: '/',
436
+ ...this.domain,
437
+ });
438
+ this.cookie.remove(this.deprecatedUserExpireCookieName, {
439
+ path: '/',
440
+ ...this.domain,
441
+ });
442
+ }
443
+
444
+ /**
445
+ * Sign out
446
+ * ```typescript
447
+ * await instance.signOut('token');
448
+ * ```
449
+ */
450
+ public async signOut(token: string): Promise<void> {
451
+ // TODO add {secure : true}
452
+ try {
453
+ const promises = [];
454
+ if (token) {
455
+ const sdkApi = new SdkApi({
456
+ token,
457
+ discoveryUrl: this.discoveryUrl,
458
+ sdkUrl: this.sdkUrl,
459
+ });
460
+
461
+ promises.push(sdkApi.makeRequest<void>({
462
+ method: 'DELETE',
463
+ route: '/auth/fingerprint-token',
464
+ }));
465
+ }
466
+ if (this.multiUserHeaders.headers.Authorization) {
467
+
468
+ const sdkApi = new SdkApi({
469
+ token: this.multiUserHeaders.headers.Authorization,
470
+ discoveryUrl: this.discoveryUrl,
471
+ sdkUrl: this.sdkUrl,
472
+ });
473
+
474
+ promises.push(sdkApi.makeRequest<void>({
475
+ method: 'DELETE',
476
+ route: '/multi-user/fingerprint-token',
477
+ }));
478
+ }
479
+ await Promise.all(promises);
480
+ } catch (error) {
481
+ // eslint-disable-next-line no-console
482
+ console.log('Logout failed: ', error);
483
+ }
484
+ this.removeCookies();
485
+ }
486
+
487
+ /**
488
+ * Validate user
489
+ * ```typescript
490
+ * const user = await instance.validateUser();
491
+ * ```
492
+ */
493
+ public async validateUser(allowGuestLogin = false): Promise<User> {
494
+ this._checkDeprecatedCookies();
495
+ const userParams = this._getUser;
496
+
497
+ if (!userParams) {
498
+ return Promise.reject(new Error('No cached user params are available'));
499
+ }
500
+
501
+ const user = await this._validateToken(userParams.token!, allowGuestLogin);
502
+
503
+ if (!user.identityProvider && userParams.identityProvider) {
504
+ user.identityProvider = userParams.identityProvider;
505
+ }
506
+ _.assign(user, { token: userParams.token });
507
+
508
+ const allow = _.get(user, 'allow', false);
509
+ if (!allow) {
510
+ throw Error('Invalid Token');
511
+ }
512
+
513
+ return user;
514
+ }
515
+
516
+ /**
517
+ * Check existence of a user cookie
518
+ * ```typescript
519
+ * const result = instance.hasUserParams();
520
+ * ```
521
+ */
522
+ public hasUserParams(): boolean {
523
+ return Boolean(this._getUser);
524
+ }
525
+
526
+ /**
527
+ * Get users list of a multi-user
528
+ * ```typescript
529
+ * const result = await instance.multiUserGetUsersList();
530
+ * ```
531
+ */
532
+ public async multiUserGetUsersList(): Promise<any> {
533
+ if (!this.multiUserHeaders.headers.Authorization) return false;
534
+
535
+ const sdkApi = new SdkApi({
536
+ token: this.multiUserHeaders.headers.Authorization,
537
+ discoveryUrl: this.discoveryUrl,
538
+ sdkUrl: this.sdkUrl,
539
+ });
540
+
541
+ return sdkApi.makeRequest<any>({
542
+ method: 'GET',
543
+ route: '/multi-user/list-users',
544
+ });
545
+ }
546
+
547
+ /**
548
+ * Log in user of a multi-user
549
+ * ```typescript
550
+ * const result = await instance.multiUserLoginUser({
551
+ * accountId: 'account-id',
552
+ * id: 'id',
553
+ * long: true
554
+ * });
555
+ * ```
556
+ */
557
+ public async multiUserLoginUser({ accountId, id, long }: MultiUserLoginUserArgs): Promise<User> {
558
+ const sdkApi = new SdkApi({
559
+ token: this.multiUserHeaders.headers.Authorization,
560
+ discoveryUrl: this.discoveryUrl,
561
+ sdkUrl: this.sdkUrl,
562
+ });
563
+
564
+ const user = await sdkApi.makeRequest<User>({
565
+ method: 'POST',
566
+ route: '/multi-user/user-token',
567
+ data: {
568
+ accountId,
569
+ id,
570
+ },
571
+ });
572
+
573
+ await this.saveUser({
574
+ long,
575
+ user,
576
+ });
577
+
578
+ return user;
579
+ }
580
+
581
+ /**
582
+ * Get username for lock screen
583
+ * ```typescript
584
+ * const username = await instance.getUserNameForLockScreen(user);
585
+ * ```
586
+ */
587
+ public async getUserNameForLockScreen(user: User): Promise<string> {
588
+ const multiUserCookie = this.cookie.get(this.multiUserCookieName!) || {};
589
+ if (multiUserCookie.username) return multiUserCookie.username;
590
+
591
+ const { multiUserId, username, token } = user;
592
+ if (multiUserId) {
593
+ const sdkApi = new SdkApi({
594
+ token: token!,
595
+ discoveryUrl: this.discoveryUrl,
596
+ sdkUrl: this.sdkUrl,
597
+ });
598
+
599
+ const { username } = await sdkApi.makeRequest<MultiUserResponse>({
600
+ method: 'GET',
601
+ route: '/user/multi-user',
602
+ });
603
+
604
+ return username;
605
+
606
+ }
607
+ return username;
608
+ }
609
+
610
+ /**
611
+ * Get profile for multi-user
612
+ * ```typescript
613
+ * const result = await instance.multiUserGetProfile();
614
+ * ```
615
+ */
616
+ public async multiUserGetProfile(): Promise<any> {
617
+ const sdkApi = new SdkApi({
618
+ token: this.multiUserHeaders.headers.Authorization,
619
+ discoveryUrl: this.discoveryUrl,
620
+ sdkUrl: this.sdkUrl,
621
+ });
622
+
623
+ return sdkApi.makeRequest<any>({
624
+ method: 'GET',
625
+ route: '/multi-user/profile',
626
+ });
627
+ }
628
+
629
+ /**
630
+ * Set profile for multi-user
631
+ * ```typescript
632
+ * const knowledgeModels = await instance.multiUserSetProfile(profile);
633
+ * ```
634
+ */
635
+ public async multiUserSetProfile(profile: unknown): Promise<any> {
636
+ const sdkApi = new SdkApi({
637
+ token: this.multiUserHeaders.headers.Authorization,
638
+ discoveryUrl: this.discoveryUrl,
639
+ sdkUrl: this.sdkUrl,
640
+ });
641
+
642
+ return sdkApi.makeRequest<any>({
643
+ method: 'POST',
644
+ route: '/multi-user/profile',
645
+ data: profile,
646
+ });
647
+ }
648
+
649
+ /**
650
+ * Validate multi-user token
651
+ * ```typescript
652
+ * const result = await instance.validateMultiUserToken();
653
+ * ```
654
+ */
655
+ public async validateMultiUserToken(): Promise<any> {
656
+ const sdkApi = new SdkApi({
657
+ token: this.multiUserHeaders.headers.Authorization,
658
+ discoveryUrl: this.discoveryUrl,
659
+ sdkUrl: this.sdkUrl,
660
+ });
661
+
662
+ return sdkApi.makeRequest<any>({
663
+ method: 'GET',
664
+ route: '/multi-user/token',
665
+ });
666
+ }
667
+
668
+ /**
669
+ * Upload icon for multi-user
670
+ * ```typescript
671
+ * const downloadUrl = await instance.multiUserUploadIcon({
672
+ * name: 'name',
673
+ * contentType: 'content-type',
674
+ * file: file
675
+ * });
676
+ * ```
677
+ */
678
+ public async multiUserUploadIcon({ name, contentType, cacheControl = 'no-cache', file }: MultiUserUploadIconArgs): Promise<string> {
679
+ const sdkApi = new SdkApi({
680
+ token: this.multiUserHeaders.headers.Authorization,
681
+ discoveryUrl: this.discoveryUrl,
682
+ sdkUrl: this.sdkUrl,
683
+ });
684
+
685
+ const data = await sdkApi.makeRequest<MultiUserUploadIconResponse>({
686
+ method: 'POST',
687
+ route: '/multi-user/sign-upload-url',
688
+ data: {
689
+ name,
690
+ contentType,
691
+ cacheControl,
692
+ },
693
+ });
694
+
695
+ const FormDataLib = isNode ? require('form-data') : FormData;
696
+ const formData = new FormDataLib();
697
+
698
+ _.forEach(data.uploadParams.fields, (value, key) => {
699
+ formData.append(key, value);
700
+ });
701
+
702
+ formData.append('cache-control', cacheControl);
703
+ formData.append('content-type', contentType);
704
+ formData.append('File', file, name);
705
+
706
+ if (isNode) {
707
+ await new Promise<void>((resolve, reject) => {
708
+ formData.submit(data.uploadParams.url, (error: any) => {
709
+ if (error) return reject(error);
710
+ resolve();
711
+ });
712
+ });
713
+ } else {
714
+ await axios.post(data.uploadParams.url, formData);
715
+ }
716
+
717
+ return data.downloadUrl;
718
+ }
719
+
720
+ /**
721
+ * Confirm email change
722
+ * ```typescript
723
+ * const result = await instance.confirmEmailChange({ token: 'token' });
724
+ * ```
725
+ */
726
+ public async confirmEmailChange({ token }: { token: string; }): Promise<any> {
727
+ const sdkApi = new SdkApi({
728
+ token: '',
729
+ discoveryUrl: this.discoveryUrl,
730
+ sdkUrl: this.sdkUrl,
731
+ });
732
+
733
+ return sdkApi.makeRequest<any>({
734
+ method: 'POST',
735
+ route: '/multi-user/change-email-finish',
736
+ data: {
737
+ token,
738
+ },
739
+ });
740
+ }
741
+
742
+ /**
743
+ * Update 2fa for multi-user
744
+ * ```typescript
745
+ * const result = await instance.multiUserUpdateTwoFactor({
746
+ * secret: 'secret',
747
+ * enabled: true,
748
+ * codes: codes,
749
+ * verificationCode: 'verification-code'
750
+ * });
751
+ * ```
752
+ */
753
+ public async multiUserUpdateTwoFactor({ secret, enabled, codes, verificationCode }: MultiUserUpdateTwoFactorArgs): Promise<any> {
754
+ const sdkApi = new SdkApi({
755
+ token: this.multiUserHeaders.headers.Authorization,
756
+ discoveryUrl: this.discoveryUrl,
757
+ sdkUrl: this.sdkUrl,
758
+ });
759
+
760
+ return sdkApi.makeRequest<any>({
761
+ method: 'POST',
762
+ route: '/multi-user/twofactor',
763
+ data: {
764
+ secret,
765
+ enabled,
766
+ codes,
767
+ verificationCode,
768
+ },
769
+ });
770
+ }
771
+
772
+ }