@aws-amplify/auth 5.6.0 → 5.6.1-v5-auth-internals.3500229.2

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,2872 @@
1
+ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ import {
5
+ AuthOptions,
6
+ FederatedResponse,
7
+ SignUpParams,
8
+ FederatedUser,
9
+ ConfirmSignUpOptions,
10
+ SignOutOpts,
11
+ CurrentUserOpts,
12
+ GetPreferredMFAOpts,
13
+ SignInOpts,
14
+ isUsernamePasswordOpts,
15
+ isCognitoHostedOpts,
16
+ isFederatedSignInOptions,
17
+ isFederatedSignInOptionsCustom,
18
+ hasCustomState,
19
+ FederatedSignInOptionsCustom,
20
+ LegacyProvider,
21
+ FederatedSignInOptions,
22
+ AwsCognitoOAuthOpts,
23
+ ClientMetaData,
24
+ } from '../types';
25
+
26
+ import {
27
+ Amplify,
28
+ ConsoleLogger as Logger,
29
+ Credentials,
30
+ CustomUserAgentDetails,
31
+ Hub,
32
+ StorageHelper,
33
+ ICredentials,
34
+ Platform,
35
+ browserOrNode,
36
+ parseAWSExports,
37
+ UniversalStorage,
38
+ urlSafeDecode,
39
+ HubCallback,
40
+ } from '@aws-amplify/core';
41
+ import {
42
+ CookieStorage,
43
+ CognitoUserPool,
44
+ AuthenticationDetails,
45
+ ICognitoUserPoolData,
46
+ ICognitoUserData,
47
+ ISignUpResult,
48
+ CognitoUser,
49
+ MFAOption,
50
+ CognitoUserSession,
51
+ IAuthenticationCallback,
52
+ ICognitoUserAttributeData,
53
+ CognitoUserAttribute,
54
+ CognitoIdToken,
55
+ CognitoRefreshToken,
56
+ CognitoAccessToken,
57
+ NodeCallback,
58
+ CodeDeliveryDetails,
59
+ } from 'amazon-cognito-identity-js';
60
+ import {
61
+ addAuthCategoryToCognitoUserAgent,
62
+ addFrameworkToCognitoUserAgent,
63
+ } from 'amazon-cognito-identity-js/internals';
64
+
65
+ import { parse } from 'url';
66
+ import OAuth from '../OAuth/OAuth';
67
+ import { default as urlListener } from '../urlListener';
68
+ import { AuthError, NoUserPoolError } from '../Errors';
69
+ import {
70
+ AuthErrorTypes,
71
+ AutoSignInOptions,
72
+ CognitoHostedUIIdentityProvider,
73
+ IAuthDevice,
74
+ } from '../types/Auth';
75
+
76
+ const logger = new Logger('AuthClass');
77
+ const USER_ADMIN_SCOPE = 'aws.cognito.signin.user.admin';
78
+
79
+ // 10 sec, following this guide https://www.nngroup.com/articles/response-times-3-important-limits/
80
+ const OAUTH_FLOW_MS_TIMEOUT = 10 * 1000;
81
+
82
+ const AMPLIFY_SYMBOL = (
83
+ typeof Symbol !== 'undefined' && typeof Symbol.for === 'function'
84
+ ? Symbol.for('amplify_default')
85
+ : '@@amplify_default'
86
+ ) as Symbol;
87
+
88
+ const dispatchAuthEvent = (event: string, data: any, message: string) => {
89
+ Hub.dispatch('auth', { event, data, message }, 'Auth', AMPLIFY_SYMBOL);
90
+ };
91
+
92
+ // Cognito Documentation for max device
93
+ // tslint:disable-next-line:max-line-length
94
+ // https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ListDevices.html#API_ListDevices_RequestSyntax
95
+ const MAX_DEVICES = 60;
96
+
97
+ const MAX_AUTOSIGNIN_POLLING_MS = 3 * 60 * 1000;
98
+
99
+ /**
100
+ * Provide authentication steps
101
+ */
102
+ export class InternalAuthClass {
103
+ private _config: AuthOptions;
104
+ private userPool: CognitoUserPool = null;
105
+ private user: any = null;
106
+ private _oAuthHandler: OAuth;
107
+ private _storage;
108
+ private _storageSync;
109
+ private oAuthFlowInProgress: boolean = false;
110
+ private pendingSignIn: ReturnType<
111
+ InternalAuthClass['signInWithPassword']
112
+ > | null;
113
+ private autoSignInInitiated: boolean = false;
114
+ private inflightSessionPromise: Promise<CognitoUserSession> | null = null;
115
+ private inflightSessionPromiseCounter: number = 0;
116
+ Credentials = Credentials;
117
+
118
+ /**
119
+ * Initialize Auth with AWS configurations
120
+ * @param {Object} config - Configuration of the Auth
121
+ */
122
+ constructor(config: AuthOptions) {
123
+ this.configure(config);
124
+ this.currentCredentials = this.currentCredentials.bind(this);
125
+ this.currentUserCredentials = this.currentUserCredentials.bind(this);
126
+
127
+ Hub.listen('auth', ({ payload }) => {
128
+ const { event } = payload;
129
+ switch (event) {
130
+ case 'verify':
131
+ case 'signIn':
132
+ this._storage.setItem('amplify-signin-with-hostedUI', 'false');
133
+ break;
134
+ case 'signOut':
135
+ this._storage.removeItem('amplify-signin-with-hostedUI');
136
+ break;
137
+ case 'cognitoHostedUI':
138
+ this._storage.setItem('amplify-signin-with-hostedUI', 'true');
139
+ break;
140
+ }
141
+ });
142
+
143
+ addAuthCategoryToCognitoUserAgent();
144
+ addFrameworkToCognitoUserAgent(Platform.framework);
145
+ Platform.observeFrameworkChanges(() => {
146
+ addFrameworkToCognitoUserAgent(Platform.framework);
147
+ });
148
+ }
149
+
150
+ public getModuleName() {
151
+ return 'InternalAuth';
152
+ }
153
+
154
+ configure(config?) {
155
+ if (!config) return this._config || {};
156
+ logger.debug('configure Auth');
157
+ const conf = Object.assign(
158
+ {},
159
+ this._config,
160
+ parseAWSExports(config).Auth,
161
+ config
162
+ );
163
+ this._config = conf;
164
+ const {
165
+ userPoolId,
166
+ userPoolWebClientId,
167
+ cookieStorage,
168
+ oauth,
169
+ region,
170
+ identityPoolId,
171
+ mandatorySignIn,
172
+ refreshHandlers,
173
+ identityPoolRegion,
174
+ clientMetadata,
175
+ endpoint,
176
+ storage,
177
+ } = this._config;
178
+
179
+ if (!storage) {
180
+ // backward compatability
181
+ if (cookieStorage) this._storage = new CookieStorage(cookieStorage);
182
+ else {
183
+ this._storage = config.ssr
184
+ ? new UniversalStorage()
185
+ : new StorageHelper().getStorage();
186
+ }
187
+ } else {
188
+ if (!this._isValidAuthStorage(storage)) {
189
+ logger.error('The storage in the Auth config is not valid!');
190
+ throw new Error('Empty storage object');
191
+ }
192
+ this._storage = storage;
193
+ }
194
+
195
+ this._storageSync = Promise.resolve();
196
+ if (typeof this._storage['sync'] === 'function') {
197
+ this._storageSync = this._storage['sync']();
198
+ }
199
+
200
+ if (userPoolId) {
201
+ const userPoolData: ICognitoUserPoolData = {
202
+ UserPoolId: userPoolId,
203
+ ClientId: userPoolWebClientId,
204
+ endpoint,
205
+ };
206
+ userPoolData.Storage = this._storage;
207
+
208
+ this.userPool = new CognitoUserPool(
209
+ userPoolData,
210
+ this.wrapRefreshSessionCallback
211
+ );
212
+ }
213
+
214
+ this.Credentials.configure({
215
+ mandatorySignIn,
216
+ region,
217
+ userPoolId,
218
+ identityPoolId,
219
+ refreshHandlers,
220
+ storage: this._storage,
221
+ identityPoolRegion,
222
+ });
223
+
224
+ // initialize cognitoauth client if hosted ui options provided
225
+ // to keep backward compatibility:
226
+ const cognitoHostedUIConfig = oauth
227
+ ? isCognitoHostedOpts(this._config.oauth)
228
+ ? oauth
229
+ : (<any>oauth).awsCognito
230
+ : undefined;
231
+
232
+ if (cognitoHostedUIConfig) {
233
+ const cognitoAuthParams = Object.assign(
234
+ {
235
+ cognitoClientId: userPoolWebClientId,
236
+ UserPoolId: userPoolId,
237
+ domain: cognitoHostedUIConfig['domain'],
238
+ scopes: cognitoHostedUIConfig['scope'],
239
+ redirectSignIn: cognitoHostedUIConfig['redirectSignIn'],
240
+ redirectSignOut: cognitoHostedUIConfig['redirectSignOut'],
241
+ responseType: cognitoHostedUIConfig['responseType'],
242
+ Storage: this._storage,
243
+ urlOpener: cognitoHostedUIConfig['urlOpener'],
244
+ clientMetadata,
245
+ },
246
+ cognitoHostedUIConfig['options']
247
+ );
248
+
249
+ this._oAuthHandler = new OAuth({
250
+ scopes: cognitoAuthParams.scopes,
251
+ config: cognitoAuthParams,
252
+ cognitoClientId: cognitoAuthParams.cognitoClientId,
253
+ });
254
+
255
+ // **NOTE** - Remove this in a future major release as it is a breaking change
256
+ // Prevents _handleAuthResponse from being called multiple times in Expo
257
+ // See https://github.com/aws-amplify/amplify-js/issues/4388
258
+ const usedResponseUrls = {};
259
+ urlListener(({ url }) => {
260
+ if (usedResponseUrls[url]) {
261
+ return;
262
+ }
263
+
264
+ usedResponseUrls[url] = true;
265
+ this._handleAuthResponse(url);
266
+ });
267
+ }
268
+
269
+ dispatchAuthEvent(
270
+ 'configured',
271
+ null,
272
+ `The Auth category has been configured successfully`
273
+ );
274
+
275
+ if (
276
+ !this.autoSignInInitiated &&
277
+ typeof this._storage['getItem'] === 'function'
278
+ ) {
279
+ const pollingInitiated = this.isTrueStorageValue(
280
+ 'amplify-polling-started'
281
+ );
282
+ if (pollingInitiated) {
283
+ dispatchAuthEvent(
284
+ 'autoSignIn_failure',
285
+ null,
286
+ AuthErrorTypes.AutoSignInError
287
+ );
288
+ this._storage.removeItem('amplify-auto-sign-in');
289
+ }
290
+ this._storage.removeItem('amplify-polling-started');
291
+ }
292
+ return this._config;
293
+ }
294
+
295
+ wrapRefreshSessionCallback = (callback: NodeCallback.Any) => {
296
+ const wrapped: NodeCallback.Any = (error, data) => {
297
+ if (data) {
298
+ dispatchAuthEvent('tokenRefresh', undefined, `New token retrieved`);
299
+ } else {
300
+ dispatchAuthEvent(
301
+ 'tokenRefresh_failure',
302
+ error,
303
+ `Failed to retrieve new token`
304
+ );
305
+ }
306
+ return callback(error, data);
307
+ };
308
+ return wrapped;
309
+ } // prettier-ignore
310
+
311
+ /**
312
+ * Sign up with username, password and other attributes like phone, email
313
+ * @param {String | object} params - The user attributes used for signin
314
+ * @param {String[]} restOfAttrs - for the backward compatability
315
+ * @return - A promise resolves callback data if success
316
+ */
317
+ public signUp(
318
+ params: string | SignUpParams,
319
+ ...restOfAttrs: string[]
320
+ ): Promise<ISignUpResult> {
321
+ return this.internalSignUp(params, restOfAttrs);
322
+ }
323
+
324
+ public internalSignUp(
325
+ params: string | SignUpParams,
326
+ restOfAttrs?: string[],
327
+ customUserAgentDetails?: CustomUserAgentDetails
328
+ ): Promise<ISignUpResult> {
329
+ if (!this.userPool) {
330
+ return this.rejectNoUserPool();
331
+ }
332
+
333
+ let username: string = null;
334
+ let password: string = null;
335
+ const attributes: CognitoUserAttribute[] = [];
336
+ let validationData: CognitoUserAttribute[] = null;
337
+ let clientMetadata;
338
+ let autoSignIn: AutoSignInOptions = { enabled: false };
339
+ let autoSignInValidationData = {};
340
+ let autoSignInClientMetaData: ClientMetaData = {};
341
+
342
+ if (params && typeof params === 'string') {
343
+ username = params;
344
+ password = restOfAttrs ? restOfAttrs[0] : null;
345
+ const email: string = restOfAttrs ? restOfAttrs[1] : null;
346
+ const phone_number: string = restOfAttrs ? restOfAttrs[2] : null;
347
+
348
+ if (email)
349
+ attributes.push(
350
+ new CognitoUserAttribute({ Name: 'email', Value: email })
351
+ );
352
+
353
+ if (phone_number)
354
+ attributes.push(
355
+ new CognitoUserAttribute({
356
+ Name: 'phone_number',
357
+ Value: phone_number,
358
+ })
359
+ );
360
+ } else if (params && typeof params === 'object') {
361
+ username = params['username'];
362
+ password = params['password'];
363
+
364
+ if (params && params.clientMetadata) {
365
+ clientMetadata = params.clientMetadata;
366
+ } else if (this._config.clientMetadata) {
367
+ clientMetadata = this._config.clientMetadata;
368
+ }
369
+
370
+ const attrs = params['attributes'];
371
+ if (attrs) {
372
+ Object.keys(attrs).map(key => {
373
+ attributes.push(
374
+ new CognitoUserAttribute({ Name: key, Value: attrs[key] })
375
+ );
376
+ });
377
+ }
378
+
379
+ const validationDataObject = params['validationData'];
380
+ if (validationDataObject) {
381
+ validationData = [];
382
+ Object.keys(validationDataObject).map(key => {
383
+ validationData.push(
384
+ new CognitoUserAttribute({
385
+ Name: key,
386
+ Value: validationDataObject[key],
387
+ })
388
+ );
389
+ });
390
+ }
391
+
392
+ autoSignIn = params.autoSignIn ?? { enabled: false };
393
+ if (autoSignIn.enabled) {
394
+ this._storage.setItem('amplify-auto-sign-in', 'true');
395
+ autoSignInValidationData = autoSignIn.validationData ?? {};
396
+ autoSignInClientMetaData = autoSignIn.clientMetaData ?? {};
397
+ }
398
+ } else {
399
+ return this.rejectAuthError(AuthErrorTypes.SignUpError);
400
+ }
401
+
402
+ if (!username) {
403
+ return this.rejectAuthError(AuthErrorTypes.EmptyUsername);
404
+ }
405
+ if (!password) {
406
+ return this.rejectAuthError(AuthErrorTypes.EmptyPassword);
407
+ }
408
+
409
+ logger.debug('signUp attrs:', attributes);
410
+ logger.debug('signUp validation data:', validationData);
411
+
412
+ return new Promise((resolve, reject) => {
413
+ this.userPool.signUp(
414
+ username,
415
+ password,
416
+ attributes,
417
+ validationData,
418
+ (err, data) => {
419
+ if (err) {
420
+ dispatchAuthEvent(
421
+ 'signUp_failure',
422
+ err,
423
+ `${username} failed to signup`
424
+ );
425
+ reject(err);
426
+ } else {
427
+ dispatchAuthEvent(
428
+ 'signUp',
429
+ data,
430
+ `${username} has signed up successfully`
431
+ );
432
+ if (autoSignIn.enabled) {
433
+ this.handleAutoSignIn(
434
+ username,
435
+ password,
436
+ autoSignInValidationData,
437
+ autoSignInClientMetaData,
438
+ data
439
+ );
440
+ }
441
+ resolve(data);
442
+ }
443
+ },
444
+ clientMetadata
445
+ );
446
+ });
447
+ }
448
+
449
+ private handleAutoSignIn(
450
+ username: string,
451
+ password: string,
452
+ validationData: {},
453
+ clientMetadata: any,
454
+ data: any
455
+ ) {
456
+ this.autoSignInInitiated = true;
457
+ const authDetails = new AuthenticationDetails({
458
+ Username: username,
459
+ Password: password,
460
+ ValidationData: validationData,
461
+ ClientMetadata: clientMetadata,
462
+ });
463
+ if (data.userConfirmed) {
464
+ this.signInAfterUserConfirmed(authDetails);
465
+ } else if (this._config.signUpVerificationMethod === 'link') {
466
+ this.handleLinkAutoSignIn(authDetails);
467
+ } else {
468
+ this.handleCodeAutoSignIn(authDetails);
469
+ }
470
+ }
471
+
472
+ private handleCodeAutoSignIn(authDetails: AuthenticationDetails) {
473
+ const listenEvent = ({ payload }) => {
474
+ if (payload.event === 'confirmSignUp') {
475
+ this.signInAfterUserConfirmed(authDetails, listenEvent);
476
+ }
477
+ };
478
+ Hub.listen('auth', listenEvent);
479
+ }
480
+
481
+ private handleLinkAutoSignIn(authDetails: AuthenticationDetails) {
482
+ this._storage.setItem('amplify-polling-started', 'true');
483
+ const start = Date.now();
484
+ const autoSignInPollingIntervalId = setInterval(() => {
485
+ if (Date.now() - start > MAX_AUTOSIGNIN_POLLING_MS) {
486
+ clearInterval(autoSignInPollingIntervalId);
487
+ dispatchAuthEvent(
488
+ 'autoSignIn_failure',
489
+ null,
490
+ 'Please confirm your account and use your credentials to sign in.'
491
+ );
492
+ this._storage.removeItem('amplify-auto-sign-in');
493
+ } else {
494
+ this.signInAfterUserConfirmed(
495
+ authDetails,
496
+ null,
497
+ autoSignInPollingIntervalId
498
+ );
499
+ }
500
+ }, 5000);
501
+ }
502
+
503
+ private async signInAfterUserConfirmed(
504
+ authDetails: AuthenticationDetails,
505
+ listenEvent?: HubCallback,
506
+ autoSignInPollingIntervalId?: ReturnType<typeof setInterval>
507
+ ) {
508
+ const user = this.createCognitoUser(authDetails.getUsername());
509
+ try {
510
+ await user.authenticateUser(
511
+ authDetails,
512
+ this.authCallbacks(
513
+ user,
514
+ value => {
515
+ dispatchAuthEvent(
516
+ 'autoSignIn',
517
+ value,
518
+ `${authDetails.getUsername()} has signed in successfully`
519
+ );
520
+ if (listenEvent) {
521
+ Hub.remove('auth', listenEvent);
522
+ }
523
+ if (autoSignInPollingIntervalId) {
524
+ clearInterval(autoSignInPollingIntervalId);
525
+ this._storage.removeItem('amplify-polling-started');
526
+ }
527
+ this._storage.removeItem('amplify-auto-sign-in');
528
+ },
529
+ error => {
530
+ logger.error(error);
531
+ this._storage.removeItem('amplify-auto-sign-in');
532
+ }
533
+ )
534
+ );
535
+ } catch (error) {
536
+ logger.error(error);
537
+ }
538
+ }
539
+
540
+ /**
541
+ * Send the verification code to confirm sign up
542
+ * @param {String} username - The username to be confirmed
543
+ * @param {String} code - The verification code
544
+ * @param {ConfirmSignUpOptions} options - other options for confirm signup
545
+ * @return - A promise resolves callback data if success
546
+ */
547
+ public confirmSignUp(
548
+ username: string,
549
+ code: string,
550
+ options?: ConfirmSignUpOptions,
551
+ customUserAgentDetails?: CustomUserAgentDetails
552
+ ): Promise<any> {
553
+ if (!this.userPool) {
554
+ return this.rejectNoUserPool();
555
+ }
556
+ if (!username) {
557
+ return this.rejectAuthError(AuthErrorTypes.EmptyUsername);
558
+ }
559
+ if (!code) {
560
+ return this.rejectAuthError(AuthErrorTypes.EmptyCode);
561
+ }
562
+
563
+ const user = this.createCognitoUser(username);
564
+ const forceAliasCreation =
565
+ options && typeof options.forceAliasCreation === 'boolean'
566
+ ? options.forceAliasCreation
567
+ : true;
568
+
569
+ let clientMetadata;
570
+ if (options && options.clientMetadata) {
571
+ clientMetadata = options.clientMetadata;
572
+ } else if (this._config.clientMetadata) {
573
+ clientMetadata = this._config.clientMetadata;
574
+ }
575
+ return new Promise((resolve, reject) => {
576
+ user.confirmRegistration(
577
+ code,
578
+ forceAliasCreation,
579
+ (err, data) => {
580
+ if (err) {
581
+ reject(err);
582
+ } else {
583
+ dispatchAuthEvent(
584
+ 'confirmSignUp',
585
+ data,
586
+ `${username} has been confirmed successfully`
587
+ );
588
+ const autoSignIn = this.isTrueStorageValue('amplify-auto-sign-in');
589
+ if (autoSignIn && !this.autoSignInInitiated) {
590
+ dispatchAuthEvent(
591
+ 'autoSignIn_failure',
592
+ null,
593
+ AuthErrorTypes.AutoSignInError
594
+ );
595
+ this._storage.removeItem('amplify-auto-sign-in');
596
+ }
597
+ resolve(data);
598
+ }
599
+ },
600
+ clientMetadata
601
+ );
602
+ });
603
+ }
604
+
605
+ private isTrueStorageValue(value: string) {
606
+ const item = this._storage.getItem(value);
607
+ return item ? item === 'true' : false;
608
+ }
609
+
610
+ /**
611
+ * Resend the verification code
612
+ * @param {String} username - The username to be confirmed
613
+ * @param {ClientMetadata} clientMetadata - Metadata to be passed to Cognito Lambda triggers
614
+ * @return - A promise resolves code delivery details if successful
615
+ */
616
+ public resendSignUp(
617
+ username: string,
618
+ clientMetadata: ClientMetaData = this._config.clientMetadata,
619
+ customUserAgentDetails?: CustomUserAgentDetails
620
+ ): Promise<any> {
621
+ if (!this.userPool) {
622
+ return this.rejectNoUserPool();
623
+ }
624
+ if (!username) {
625
+ return this.rejectAuthError(AuthErrorTypes.EmptyUsername);
626
+ }
627
+
628
+ const user = this.createCognitoUser(username);
629
+ return new Promise((resolve, reject) => {
630
+ user.resendConfirmationCode((err, data) => {
631
+ if (err) {
632
+ reject(err);
633
+ } else {
634
+ resolve(data);
635
+ }
636
+ }, clientMetadata);
637
+ });
638
+ }
639
+
640
+ /**
641
+ * Sign in
642
+ * @param {String | SignInOpts} usernameOrSignInOpts - The username to be signed in or the sign in options
643
+ * @param {String} pw - The password of the username
644
+ * @param {ClientMetaData} clientMetadata - Client metadata for custom workflows
645
+ * @return - A promise resolves the CognitoUser
646
+ */
647
+ public signIn(
648
+ usernameOrSignInOpts: string | SignInOpts,
649
+ pw?: string,
650
+ clientMetadata: ClientMetaData = this._config.clientMetadata,
651
+ customUserAgentDetails?: CustomUserAgentDetails
652
+ ): Promise<CognitoUser | any> {
653
+ if (!this.userPool) {
654
+ return this.rejectNoUserPool();
655
+ }
656
+
657
+ let username = null;
658
+ let password = null;
659
+ let validationData = {};
660
+
661
+ // for backward compatibility
662
+ if (typeof usernameOrSignInOpts === 'string') {
663
+ username = usernameOrSignInOpts;
664
+ password = pw;
665
+ } else if (isUsernamePasswordOpts(usernameOrSignInOpts)) {
666
+ if (typeof pw !== 'undefined') {
667
+ logger.warn(
668
+ 'The password should be defined under the first parameter object!'
669
+ );
670
+ }
671
+ username = usernameOrSignInOpts.username;
672
+ password = usernameOrSignInOpts.password;
673
+ validationData = usernameOrSignInOpts.validationData;
674
+ } else {
675
+ return this.rejectAuthError(AuthErrorTypes.InvalidUsername);
676
+ }
677
+ if (!username) {
678
+ return this.rejectAuthError(AuthErrorTypes.EmptyUsername);
679
+ }
680
+ const authDetails = new AuthenticationDetails({
681
+ Username: username,
682
+ Password: password,
683
+ ValidationData: validationData,
684
+ ClientMetadata: clientMetadata,
685
+ });
686
+ if (password) {
687
+ return this.signInWithPassword(authDetails);
688
+ } else {
689
+ return this.signInWithoutPassword(authDetails);
690
+ }
691
+ }
692
+
693
+ /**
694
+ * Return an object with the authentication callbacks
695
+ * @param {CognitoUser} user - the cognito user object
696
+ * @param {} resolve - function called when resolving the current step
697
+ * @param {} reject - function called when rejecting the current step
698
+ * @return - an object with the callback methods for user authentication
699
+ */
700
+ private authCallbacks(
701
+ user: CognitoUser,
702
+ resolve: (value?: CognitoUser | any) => void,
703
+ reject: (value?: any) => void
704
+ ): IAuthenticationCallback {
705
+ const that = this;
706
+ return {
707
+ onSuccess: async session => {
708
+ logger.debug(session);
709
+ delete user['challengeName'];
710
+ delete user['challengeParam'];
711
+ try {
712
+ await this.Credentials.clear();
713
+ const cred = await this.Credentials.set(session, 'session');
714
+ logger.debug('succeed to get cognito credentials', cred);
715
+ } catch (e) {
716
+ logger.debug('cannot get cognito credentials', e);
717
+ } finally {
718
+ try {
719
+ // In order to get user attributes and MFA methods
720
+ // We need to trigger currentUserPoolUser again
721
+ const currentUser = await this.currentUserPoolUser();
722
+ that.user = currentUser;
723
+ dispatchAuthEvent(
724
+ 'signIn',
725
+ currentUser,
726
+ `A user ${user.getUsername()} has been signed in`
727
+ );
728
+ resolve(currentUser);
729
+ } catch (e) {
730
+ logger.error('Failed to get the signed in user', e);
731
+ reject(e);
732
+ }
733
+ }
734
+ },
735
+ onFailure: err => {
736
+ logger.debug('signIn failure', err);
737
+ dispatchAuthEvent(
738
+ 'signIn_failure',
739
+ err,
740
+ `${user.getUsername()} failed to signin`
741
+ );
742
+ reject(err);
743
+ },
744
+ customChallenge: challengeParam => {
745
+ logger.debug('signIn custom challenge answer required');
746
+ user['challengeName'] = 'CUSTOM_CHALLENGE';
747
+ user['challengeParam'] = challengeParam;
748
+ resolve(user);
749
+ },
750
+ mfaRequired: (challengeName, challengeParam) => {
751
+ logger.debug('signIn MFA required');
752
+ user['challengeName'] = challengeName;
753
+ user['challengeParam'] = challengeParam;
754
+ resolve(user);
755
+ },
756
+ mfaSetup: (challengeName, challengeParam) => {
757
+ logger.debug('signIn mfa setup', challengeName);
758
+ user['challengeName'] = challengeName;
759
+ user['challengeParam'] = challengeParam;
760
+ resolve(user);
761
+ },
762
+ newPasswordRequired: (userAttributes, requiredAttributes) => {
763
+ logger.debug('signIn new password');
764
+ user['challengeName'] = 'NEW_PASSWORD_REQUIRED';
765
+ user['challengeParam'] = {
766
+ userAttributes,
767
+ requiredAttributes,
768
+ };
769
+ resolve(user);
770
+ },
771
+ totpRequired: (challengeName, challengeParam) => {
772
+ logger.debug('signIn totpRequired');
773
+ user['challengeName'] = challengeName;
774
+ user['challengeParam'] = challengeParam;
775
+ resolve(user);
776
+ },
777
+ selectMFAType: (challengeName, challengeParam) => {
778
+ logger.debug('signIn selectMFAType', challengeName);
779
+ user['challengeName'] = challengeName;
780
+ user['challengeParam'] = challengeParam;
781
+ resolve(user);
782
+ },
783
+ };
784
+ }
785
+
786
+ /**
787
+ * Sign in with a password
788
+ * @private
789
+ * @param {AuthenticationDetails} authDetails - the user sign in data
790
+ * @return - A promise resolves the CognitoUser object if success or mfa required
791
+ */
792
+ private signInWithPassword(
793
+ authDetails: AuthenticationDetails
794
+ ): Promise<CognitoUser | any> {
795
+ if (this.pendingSignIn) {
796
+ throw new Error('Pending sign-in attempt already in progress');
797
+ }
798
+
799
+ const user = this.createCognitoUser(authDetails.getUsername());
800
+
801
+ this.pendingSignIn = new Promise((resolve, reject) => {
802
+ user.authenticateUser(
803
+ authDetails,
804
+ this.authCallbacks(
805
+ user,
806
+ value => {
807
+ this.pendingSignIn = null;
808
+ resolve(value);
809
+ },
810
+ error => {
811
+ this.pendingSignIn = null;
812
+ reject(error);
813
+ }
814
+ )
815
+ );
816
+ });
817
+
818
+ return this.pendingSignIn;
819
+ }
820
+
821
+ /**
822
+ * Sign in without a password
823
+ * @private
824
+ * @param {AuthenticationDetails} authDetails - the user sign in data
825
+ * @return - A promise resolves the CognitoUser object if success or mfa required
826
+ */
827
+ private signInWithoutPassword(
828
+ authDetails: AuthenticationDetails
829
+ ): Promise<CognitoUser | any> {
830
+ const user = this.createCognitoUser(authDetails.getUsername());
831
+ user.setAuthenticationFlowType('CUSTOM_AUTH');
832
+
833
+ return new Promise((resolve, reject) => {
834
+ user.initiateAuth(authDetails, this.authCallbacks(user, resolve, reject));
835
+ });
836
+ }
837
+
838
+ /**
839
+ * This was previously used by an authenticated user to get MFAOptions,
840
+ * but no longer returns a meaningful response. Refer to the documentation for
841
+ * how to setup and use MFA: https://docs.amplify.aws/lib/auth/mfa/q/platform/js
842
+ * @deprecated
843
+ * @param {CognitoUser} user - the current user
844
+ * @return - A promise resolves the current preferred mfa option if success
845
+ */
846
+ public getMFAOptions(
847
+ user: CognitoUser | any,
848
+ customUserAgentDetails?: CustomUserAgentDetails
849
+ ): Promise<MFAOption[]> {
850
+ return new Promise((res, rej) => {
851
+ user.getMFAOptions((err, mfaOptions) => {
852
+ if (err) {
853
+ logger.debug('get MFA Options failed', err);
854
+ rej(err);
855
+ return;
856
+ }
857
+ logger.debug('get MFA options success', mfaOptions);
858
+ res(mfaOptions);
859
+ return;
860
+ });
861
+ });
862
+ }
863
+
864
+ /**
865
+ * get preferred mfa method
866
+ * @param {CognitoUser} user - the current cognito user
867
+ * @param {GetPreferredMFAOpts} params - options for getting the current user preferred MFA
868
+ */
869
+ public getPreferredMFA(
870
+ user: CognitoUser | any,
871
+ params?: GetPreferredMFAOpts,
872
+ customUserAgentDetails?: CustomUserAgentDetails
873
+ ): Promise<string> {
874
+ const that = this;
875
+ return new Promise((res, rej) => {
876
+ const clientMetadata = this._config.clientMetadata; // TODO: verify behavior if this is override during signIn
877
+
878
+ const bypassCache = params ? params.bypassCache : false;
879
+ user.getUserData(
880
+ async (err, data) => {
881
+ if (err) {
882
+ logger.debug('getting preferred mfa failed', err);
883
+ if (this.isSessionInvalid(err)) {
884
+ try {
885
+ await this.cleanUpInvalidSession(user);
886
+ } catch (cleanUpError) {
887
+ rej(
888
+ new Error(
889
+ `Session is invalid due to: ${err.message} and failed to clean up invalid session: ${cleanUpError.message}`
890
+ )
891
+ );
892
+ return;
893
+ }
894
+ }
895
+ rej(err);
896
+ return;
897
+ }
898
+
899
+ const mfaType = that._getMfaTypeFromUserData(data);
900
+ if (!mfaType) {
901
+ rej('invalid MFA Type');
902
+ return;
903
+ } else {
904
+ res(mfaType);
905
+ return;
906
+ }
907
+ },
908
+ { bypassCache, clientMetadata }
909
+ );
910
+ });
911
+ }
912
+
913
+ private _getMfaTypeFromUserData(data) {
914
+ let ret = null;
915
+ const preferredMFA = data.PreferredMfaSetting;
916
+ // if the user has used Auth.setPreferredMFA() to setup the mfa type
917
+ // then the "PreferredMfaSetting" would exist in the response
918
+ if (preferredMFA) {
919
+ ret = preferredMFA;
920
+ } else {
921
+ // if mfaList exists but empty, then its noMFA
922
+ const mfaList = data.UserMFASettingList;
923
+ if (!mfaList) {
924
+ // if SMS was enabled by using Auth.enableSMS(),
925
+ // the response would contain MFAOptions
926
+ // as for now Cognito only supports for SMS, so we will say it is 'SMS_MFA'
927
+ // if it does not exist, then it should be NOMFA
928
+ const MFAOptions = data.MFAOptions;
929
+ if (MFAOptions) {
930
+ ret = 'SMS_MFA';
931
+ } else {
932
+ ret = 'NOMFA';
933
+ }
934
+ } else if (mfaList.length === 0) {
935
+ ret = 'NOMFA';
936
+ } else {
937
+ logger.debug('invalid case for getPreferredMFA', data);
938
+ }
939
+ }
940
+ return ret;
941
+ }
942
+
943
+ private _getUserData(user, params) {
944
+ return new Promise((res, rej) => {
945
+ user.getUserData(async (err, data) => {
946
+ if (err) {
947
+ logger.debug('getting user data failed', err);
948
+ if (this.isSessionInvalid(err)) {
949
+ try {
950
+ await this.cleanUpInvalidSession(user);
951
+ } catch (cleanUpError) {
952
+ rej(
953
+ new Error(
954
+ `Session is invalid due to: ${err.message} and failed to clean up invalid session: ${cleanUpError.message}`
955
+ )
956
+ );
957
+ return;
958
+ }
959
+ }
960
+ rej(err);
961
+ return;
962
+ } else {
963
+ res(data);
964
+ }
965
+ }, params);
966
+ });
967
+ }
968
+
969
+ /**
970
+ * set preferred MFA method
971
+ * @param {CognitoUser} user - the current Cognito user
972
+ * @param {string} mfaMethod - preferred mfa method
973
+ * @return - A promise resolve if success
974
+ */
975
+ public async setPreferredMFA(
976
+ user: CognitoUser | any,
977
+ mfaMethod: 'TOTP' | 'SMS' | 'NOMFA' | 'SMS_MFA' | 'SOFTWARE_TOKEN_MFA',
978
+ customUserAgentDetails?: CustomUserAgentDetails
979
+ ): Promise<string> {
980
+ const clientMetadata = this._config.clientMetadata; // TODO: verify behavior if this is override during signIn
981
+
982
+ const userData = await this._getUserData(user, {
983
+ bypassCache: true,
984
+ clientMetadata,
985
+ });
986
+ let smsMfaSettings = null;
987
+ let totpMfaSettings = null;
988
+
989
+ switch (mfaMethod) {
990
+ case 'TOTP':
991
+ case 'SOFTWARE_TOKEN_MFA':
992
+ totpMfaSettings = {
993
+ PreferredMfa: true,
994
+ Enabled: true,
995
+ };
996
+ break;
997
+ case 'SMS':
998
+ case 'SMS_MFA':
999
+ smsMfaSettings = {
1000
+ PreferredMfa: true,
1001
+ Enabled: true,
1002
+ };
1003
+ break;
1004
+ case 'NOMFA':
1005
+ const mfaList = userData['UserMFASettingList'];
1006
+ const currentMFAType = await this._getMfaTypeFromUserData(userData);
1007
+ if (currentMFAType === 'NOMFA') {
1008
+ return Promise.resolve('No change for mfa type');
1009
+ } else if (currentMFAType === 'SMS_MFA') {
1010
+ smsMfaSettings = {
1011
+ PreferredMfa: false,
1012
+ Enabled: false,
1013
+ };
1014
+ } else if (currentMFAType === 'SOFTWARE_TOKEN_MFA') {
1015
+ totpMfaSettings = {
1016
+ PreferredMfa: false,
1017
+ Enabled: false,
1018
+ };
1019
+ } else {
1020
+ return this.rejectAuthError(AuthErrorTypes.InvalidMFA);
1021
+ }
1022
+ // if there is a UserMFASettingList in the response
1023
+ // we need to disable every mfa type in that list
1024
+ if (mfaList && mfaList.length !== 0) {
1025
+ // to disable SMS or TOTP if exists in that list
1026
+ mfaList.forEach(mfaType => {
1027
+ if (mfaType === 'SMS_MFA') {
1028
+ smsMfaSettings = {
1029
+ PreferredMfa: false,
1030
+ Enabled: false,
1031
+ };
1032
+ } else if (mfaType === 'SOFTWARE_TOKEN_MFA') {
1033
+ totpMfaSettings = {
1034
+ PreferredMfa: false,
1035
+ Enabled: false,
1036
+ };
1037
+ }
1038
+ });
1039
+ }
1040
+ break;
1041
+ default:
1042
+ logger.debug('no validmfa method provided');
1043
+ return this.rejectAuthError(AuthErrorTypes.NoMFA);
1044
+ }
1045
+
1046
+ const that = this;
1047
+ return new Promise<string>((res, rej) => {
1048
+ user.setUserMfaPreference(
1049
+ smsMfaSettings,
1050
+ totpMfaSettings,
1051
+ (err, result) => {
1052
+ if (err) {
1053
+ logger.debug('Set user mfa preference error', err);
1054
+ return rej(err);
1055
+ }
1056
+ logger.debug('Set user mfa success', result);
1057
+ logger.debug('Caching the latest user data into local');
1058
+ // cache the latest result into user data
1059
+ user.getUserData(
1060
+ async (err, data) => {
1061
+ if (err) {
1062
+ logger.debug('getting user data failed', err);
1063
+ if (this.isSessionInvalid(err)) {
1064
+ try {
1065
+ await this.cleanUpInvalidSession(user);
1066
+ } catch (cleanUpError) {
1067
+ rej(
1068
+ new Error(
1069
+ `Session is invalid due to: ${err.message} and failed to clean up invalid session: ${cleanUpError.message}`
1070
+ )
1071
+ );
1072
+ return;
1073
+ }
1074
+ }
1075
+ return rej(err);
1076
+ } else {
1077
+ return res(result);
1078
+ }
1079
+ },
1080
+ {
1081
+ bypassCache: true,
1082
+ clientMetadata,
1083
+ }
1084
+ );
1085
+ }
1086
+ );
1087
+ });
1088
+ }
1089
+
1090
+ /**
1091
+ * disable SMS
1092
+ * @deprecated
1093
+ * @param {CognitoUser} user - the current user
1094
+ * @return - A promise resolves is success
1095
+ */
1096
+ public disableSMS(
1097
+ user: CognitoUser,
1098
+ customUserAgentDetails?: CustomUserAgentDetails
1099
+ ): Promise<string> {
1100
+ return new Promise((res, rej) => {
1101
+ user.disableMFA((err, data) => {
1102
+ if (err) {
1103
+ logger.debug('disable mfa failed', err);
1104
+ rej(err);
1105
+ return;
1106
+ }
1107
+ logger.debug('disable mfa succeed', data);
1108
+ res(data);
1109
+ return;
1110
+ });
1111
+ });
1112
+ }
1113
+
1114
+ /**
1115
+ * enable SMS
1116
+ * @deprecated
1117
+ * @param {CognitoUser} user - the current user
1118
+ * @return - A promise resolves is success
1119
+ */
1120
+ public enableSMS(
1121
+ user: CognitoUser,
1122
+ customUserAgentDetails?: CustomUserAgentDetails
1123
+ ): Promise<string> {
1124
+ return new Promise((res, rej) => {
1125
+ user.enableMFA((err, data) => {
1126
+ if (err) {
1127
+ logger.debug('enable mfa failed', err);
1128
+ rej(err);
1129
+ return;
1130
+ }
1131
+ logger.debug('enable mfa succeed', data);
1132
+ res(data);
1133
+ return;
1134
+ });
1135
+ });
1136
+ }
1137
+
1138
+ /**
1139
+ * Setup TOTP
1140
+ * @param {CognitoUser} user - the current user
1141
+ * @return - A promise resolves with the secret code if success
1142
+ */
1143
+ public setupTOTP(
1144
+ user: CognitoUser | any,
1145
+ customUserAgentDetails?: CustomUserAgentDetails
1146
+ ): Promise<string> {
1147
+ return new Promise((res, rej) => {
1148
+ user.associateSoftwareToken({
1149
+ onFailure: err => {
1150
+ logger.debug('associateSoftwareToken failed', err);
1151
+ rej(err);
1152
+ return;
1153
+ },
1154
+ associateSecretCode: secretCode => {
1155
+ logger.debug('associateSoftwareToken success', secretCode);
1156
+ res(secretCode);
1157
+ return;
1158
+ },
1159
+ });
1160
+ });
1161
+ }
1162
+
1163
+ /**
1164
+ * verify TOTP setup
1165
+ * @param {CognitoUser} user - the current user
1166
+ * @param {string} challengeAnswer - challenge answer
1167
+ * @return - A promise resolves is success
1168
+ */
1169
+ public verifyTotpToken(
1170
+ user: CognitoUser | any,
1171
+ challengeAnswer: string,
1172
+ customUserAgentDetails?: CustomUserAgentDetails
1173
+ ): Promise<CognitoUserSession> {
1174
+ logger.debug('verification totp token', user, challengeAnswer);
1175
+
1176
+ let signInUserSession;
1177
+ if (user && typeof user.getSignInUserSession === 'function') {
1178
+ signInUserSession = (user as CognitoUser).getSignInUserSession();
1179
+ }
1180
+ const isLoggedIn = signInUserSession?.isValid();
1181
+
1182
+ return new Promise((res, rej) => {
1183
+ user.verifySoftwareToken(challengeAnswer, 'My TOTP device', {
1184
+ onFailure: err => {
1185
+ logger.debug('verifyTotpToken failed', err);
1186
+ rej(err);
1187
+ return;
1188
+ },
1189
+ onSuccess: data => {
1190
+ if (!isLoggedIn) {
1191
+ dispatchAuthEvent(
1192
+ 'signIn',
1193
+ user,
1194
+ `A user ${user.getUsername()} has been signed in`
1195
+ );
1196
+ }
1197
+ dispatchAuthEvent(
1198
+ 'verify',
1199
+ user,
1200
+ `A user ${user.getUsername()} has been verified`
1201
+ );
1202
+ logger.debug('verifyTotpToken success', data);
1203
+ res(data);
1204
+ return;
1205
+ },
1206
+ });
1207
+ });
1208
+ }
1209
+
1210
+ /**
1211
+ * Send MFA code to confirm sign in
1212
+ * @param {Object} user - The CognitoUser object
1213
+ * @param {String} code - The confirmation code
1214
+ */
1215
+ public confirmSignIn(
1216
+ user: CognitoUser | any,
1217
+ code: string,
1218
+ mfaType?: 'SMS_MFA' | 'SOFTWARE_TOKEN_MFA' | null,
1219
+ clientMetadata: ClientMetaData = this._config.clientMetadata,
1220
+ customUserAgentDetails?: CustomUserAgentDetails
1221
+ ): Promise<CognitoUser | any> {
1222
+ if (!code) {
1223
+ return this.rejectAuthError(AuthErrorTypes.EmptyCode);
1224
+ }
1225
+
1226
+ const that = this;
1227
+ return new Promise((resolve, reject) => {
1228
+ user.sendMFACode(
1229
+ code,
1230
+ {
1231
+ onSuccess: async session => {
1232
+ logger.debug(session);
1233
+ try {
1234
+ await this.Credentials.clear();
1235
+ const cred = await this.Credentials.set(session, 'session');
1236
+ logger.debug('succeed to get cognito credentials', cred);
1237
+ } catch (e) {
1238
+ logger.debug('cannot get cognito credentials', e);
1239
+ } finally {
1240
+ that.user = user;
1241
+ try {
1242
+ const currentUser = await this.currentUserPoolUser();
1243
+ user.attributes = currentUser.attributes;
1244
+ } catch (e) {
1245
+ logger.debug('cannot get updated Cognito User', e);
1246
+ }
1247
+ dispatchAuthEvent(
1248
+ 'signIn',
1249
+ user,
1250
+ `A user ${user.getUsername()} has been signed in`
1251
+ );
1252
+ resolve(user);
1253
+ }
1254
+ },
1255
+ onFailure: err => {
1256
+ logger.debug('confirm signIn failure', err);
1257
+ reject(err);
1258
+ },
1259
+ },
1260
+ mfaType,
1261
+ clientMetadata
1262
+ );
1263
+ });
1264
+ }
1265
+
1266
+ public completeNewPassword(
1267
+ user: CognitoUser | any,
1268
+ password: string,
1269
+ requiredAttributes: any = {},
1270
+ clientMetadata: ClientMetaData = this._config.clientMetadata,
1271
+ customUserAgentDetails?: CustomUserAgentDetails
1272
+ ): Promise<CognitoUser | any> {
1273
+ if (!password) {
1274
+ return this.rejectAuthError(AuthErrorTypes.EmptyPassword);
1275
+ }
1276
+
1277
+ const that = this;
1278
+ return new Promise((resolve, reject) => {
1279
+ user.completeNewPasswordChallenge(
1280
+ password,
1281
+ requiredAttributes,
1282
+ {
1283
+ onSuccess: async session => {
1284
+ logger.debug(session);
1285
+ try {
1286
+ await this.Credentials.clear();
1287
+ const cred = await this.Credentials.set(session, 'session');
1288
+ logger.debug('succeed to get cognito credentials', cred);
1289
+ } catch (e) {
1290
+ logger.debug('cannot get cognito credentials', e);
1291
+ } finally {
1292
+ that.user = user;
1293
+ dispatchAuthEvent(
1294
+ 'signIn',
1295
+ user,
1296
+ `A user ${user.getUsername()} has been signed in`
1297
+ );
1298
+ resolve(user);
1299
+ }
1300
+ },
1301
+ onFailure: err => {
1302
+ logger.debug('completeNewPassword failure', err);
1303
+ dispatchAuthEvent(
1304
+ 'completeNewPassword_failure',
1305
+ err,
1306
+ `${this.user} failed to complete the new password flow`
1307
+ );
1308
+ reject(err);
1309
+ },
1310
+ mfaRequired: (challengeName, challengeParam) => {
1311
+ logger.debug('signIn MFA required');
1312
+ user['challengeName'] = challengeName;
1313
+ user['challengeParam'] = challengeParam;
1314
+ resolve(user);
1315
+ },
1316
+ mfaSetup: (challengeName, challengeParam) => {
1317
+ logger.debug('signIn mfa setup', challengeName);
1318
+ user['challengeName'] = challengeName;
1319
+ user['challengeParam'] = challengeParam;
1320
+ resolve(user);
1321
+ },
1322
+ totpRequired: (challengeName, challengeParam) => {
1323
+ logger.debug('signIn mfa setup', challengeName);
1324
+ user['challengeName'] = challengeName;
1325
+ user['challengeParam'] = challengeParam;
1326
+ resolve(user);
1327
+ },
1328
+ },
1329
+ clientMetadata
1330
+ );
1331
+ });
1332
+ }
1333
+
1334
+ /**
1335
+ * Send the answer to a custom challenge
1336
+ * @param {CognitoUser} user - The CognitoUser object
1337
+ * @param {String} challengeResponses - The confirmation code
1338
+ */
1339
+ public sendCustomChallengeAnswer(
1340
+ user: CognitoUser | any,
1341
+ challengeResponses: string,
1342
+ clientMetadata: ClientMetaData = this._config.clientMetadata,
1343
+ customUserAgentDetails?: CustomUserAgentDetails
1344
+ ): Promise<CognitoUser | any> {
1345
+ if (!this.userPool) {
1346
+ return this.rejectNoUserPool();
1347
+ }
1348
+ if (!challengeResponses) {
1349
+ return this.rejectAuthError(AuthErrorTypes.EmptyChallengeResponse);
1350
+ }
1351
+
1352
+ const that = this;
1353
+ return new Promise((resolve, reject) => {
1354
+ user.sendCustomChallengeAnswer(
1355
+ challengeResponses,
1356
+ this.authCallbacks(user, resolve, reject),
1357
+ clientMetadata
1358
+ );
1359
+ });
1360
+ }
1361
+
1362
+ /**
1363
+ * Delete an authenticated users' attributes
1364
+ * @param {CognitoUser} - The currently logged in user object
1365
+ * @return {Promise}
1366
+ **/
1367
+ public deleteUserAttributes(
1368
+ user: CognitoUser | any,
1369
+ attributeNames: string[],
1370
+ customUserAgentDetails?: CustomUserAgentDetails
1371
+ ) {
1372
+ const that = this;
1373
+ return new Promise((resolve, reject) => {
1374
+ that.userSession(user).then(session => {
1375
+ user.deleteAttributes(attributeNames, (err, result) => {
1376
+ if (err) {
1377
+ return reject(err);
1378
+ } else {
1379
+ return resolve(result);
1380
+ }
1381
+ });
1382
+ });
1383
+ });
1384
+ }
1385
+
1386
+ /**
1387
+ * Delete the current authenticated user
1388
+ * @return {Promise}
1389
+ **/
1390
+ // TODO: Check return type void
1391
+ public async deleteUser(
1392
+ customUserAgentDetails?: CustomUserAgentDetails
1393
+ ): Promise<string | void> {
1394
+ try {
1395
+ await this._storageSync;
1396
+ } catch (e) {
1397
+ logger.debug('Failed to sync cache info into memory', e);
1398
+ throw new Error(e);
1399
+ }
1400
+
1401
+ const isSignedInHostedUI =
1402
+ this._oAuthHandler &&
1403
+ this._storage.getItem('amplify-signin-with-hostedUI') === 'true';
1404
+
1405
+ return new Promise(async (res, rej) => {
1406
+ if (this.userPool) {
1407
+ const user = this.userPool.getCurrentUser();
1408
+
1409
+ if (!user) {
1410
+ logger.debug('Failed to get user from user pool');
1411
+ return rej(new Error('No current user.'));
1412
+ } else {
1413
+ user.getSession(async (err, session) => {
1414
+ if (err) {
1415
+ logger.debug('Failed to get the user session', err);
1416
+ if (this.isSessionInvalid(err)) {
1417
+ try {
1418
+ await this.cleanUpInvalidSession(user);
1419
+ } catch (cleanUpError) {
1420
+ rej(
1421
+ new Error(
1422
+ `Session is invalid due to: ${err.message} and failed to clean up invalid session: ${cleanUpError.message}`
1423
+ )
1424
+ );
1425
+ return;
1426
+ }
1427
+ }
1428
+ return rej(err);
1429
+ } else {
1430
+ user.deleteUser((err, result: string) => {
1431
+ if (err) {
1432
+ rej(err);
1433
+ } else {
1434
+ dispatchAuthEvent(
1435
+ 'userDeleted',
1436
+ result,
1437
+ 'The authenticated user has been deleted.'
1438
+ );
1439
+ user.signOut();
1440
+ this.user = null;
1441
+ try {
1442
+ this.cleanCachedItems(); // clean aws credentials
1443
+ } catch (e) {
1444
+ // TODO: change to rejects in refactor
1445
+ logger.debug('failed to clear cached items');
1446
+ }
1447
+
1448
+ if (isSignedInHostedUI) {
1449
+ this.oAuthSignOutRedirect(res, rej);
1450
+ } else {
1451
+ dispatchAuthEvent(
1452
+ 'signOut',
1453
+ this.user,
1454
+ `A user has been signed out`
1455
+ );
1456
+ res(result);
1457
+ }
1458
+ }
1459
+ });
1460
+ }
1461
+ });
1462
+ }
1463
+ } else {
1464
+ logger.debug('no Congito User pool');
1465
+ rej(new Error('Cognito User pool does not exist'));
1466
+ }
1467
+ });
1468
+ }
1469
+
1470
+ /**
1471
+ * Update an authenticated users' attributes
1472
+ * @param {CognitoUser} - The currently logged in user object
1473
+ * @return {Promise}
1474
+ **/
1475
+ public updateUserAttributes(
1476
+ user: CognitoUser | any,
1477
+ attributes: object,
1478
+ clientMetadata: ClientMetaData = this._config.clientMetadata,
1479
+ customUserAgentDetails?: CustomUserAgentDetails
1480
+ ): Promise<string> {
1481
+ const attributeList: ICognitoUserAttributeData[] = [];
1482
+ const that = this;
1483
+ return new Promise((resolve, reject) => {
1484
+ that.userSession(user).then(session => {
1485
+ for (const key in attributes) {
1486
+ if (key !== 'sub' && key.indexOf('_verified') < 0) {
1487
+ const attr: ICognitoUserAttributeData = {
1488
+ Name: key,
1489
+ Value: attributes[key],
1490
+ };
1491
+ attributeList.push(attr);
1492
+ }
1493
+ }
1494
+ user.updateAttributes(
1495
+ attributeList,
1496
+ (err, result, details) => {
1497
+ if (err) {
1498
+ dispatchAuthEvent(
1499
+ 'updateUserAttributes_failure',
1500
+ err,
1501
+ 'Failed to update attributes'
1502
+ );
1503
+ return reject(err);
1504
+ } else {
1505
+ const attrs = this.createUpdateAttributesResultList(
1506
+ attributes as Record<string, string>,
1507
+ details?.CodeDeliveryDetailsList
1508
+ );
1509
+ dispatchAuthEvent(
1510
+ 'updateUserAttributes',
1511
+ attrs,
1512
+ 'Attributes successfully updated'
1513
+ );
1514
+ return resolve(result);
1515
+ }
1516
+ },
1517
+ clientMetadata
1518
+ );
1519
+ });
1520
+ });
1521
+ }
1522
+
1523
+ private createUpdateAttributesResultList(
1524
+ attributes: Record<string, string>,
1525
+ codeDeliveryDetailsList?: CodeDeliveryDetails[]
1526
+ ): Record<string, string> {
1527
+ const attrs = {};
1528
+ Object.keys(attributes).forEach(key => {
1529
+ attrs[key] = {
1530
+ isUpdated: true,
1531
+ };
1532
+ const codeDeliveryDetails = codeDeliveryDetailsList?.find(
1533
+ value => value.AttributeName === key
1534
+ );
1535
+ if (codeDeliveryDetails) {
1536
+ attrs[key].isUpdated = false;
1537
+ attrs[key].codeDeliveryDetails = codeDeliveryDetails;
1538
+ }
1539
+ });
1540
+ return attrs;
1541
+ }
1542
+
1543
+ /**
1544
+ * Return user attributes
1545
+ * @param {Object} user - The CognitoUser object
1546
+ * @return - A promise resolves to user attributes if success
1547
+ */
1548
+ public userAttributes(
1549
+ user: CognitoUser | any,
1550
+ customUserAgentDetails?: CustomUserAgentDetails
1551
+ ): Promise<CognitoUserAttribute[]> {
1552
+ return new Promise((resolve, reject) => {
1553
+ this.userSession(user).then(session => {
1554
+ user.getUserAttributes((err, attributes) => {
1555
+ if (err) {
1556
+ reject(err);
1557
+ } else {
1558
+ resolve(attributes);
1559
+ }
1560
+ });
1561
+ });
1562
+ });
1563
+ }
1564
+
1565
+ public verifiedContact(
1566
+ user: CognitoUser | any,
1567
+ customUserAgentDetails?: CustomUserAgentDetails
1568
+ ) {
1569
+ const that = this;
1570
+ return this.userAttributes(user).then(attributes => {
1571
+ const attrs = that.attributesToObject(attributes);
1572
+ const unverified = {};
1573
+ const verified = {};
1574
+ if (attrs['email']) {
1575
+ if (attrs['email_verified']) {
1576
+ verified['email'] = attrs['email'];
1577
+ } else {
1578
+ unverified['email'] = attrs['email'];
1579
+ }
1580
+ }
1581
+ if (attrs['phone_number']) {
1582
+ if (attrs['phone_number_verified']) {
1583
+ verified['phone_number'] = attrs['phone_number'];
1584
+ } else {
1585
+ unverified['phone_number'] = attrs['phone_number'];
1586
+ }
1587
+ }
1588
+ return {
1589
+ verified,
1590
+ unverified,
1591
+ };
1592
+ });
1593
+ }
1594
+
1595
+ private isErrorWithMessage(err: any): err is { message: string } {
1596
+ return (
1597
+ typeof err === 'object' &&
1598
+ Object.prototype.hasOwnProperty.call(err, 'message')
1599
+ );
1600
+ }
1601
+
1602
+ // Session revoked by another app
1603
+ private isTokenRevokedError(
1604
+ err: any
1605
+ ): err is { message: 'Access Token has been revoked' } {
1606
+ return (
1607
+ this.isErrorWithMessage(err) &&
1608
+ err.message === 'Access Token has been revoked'
1609
+ );
1610
+ }
1611
+
1612
+ private isRefreshTokenRevokedError(
1613
+ err: any
1614
+ ): err is { message: 'Refresh Token has been revoked' } {
1615
+ return (
1616
+ this.isErrorWithMessage(err) &&
1617
+ err.message === 'Refresh Token has been revoked'
1618
+ );
1619
+ }
1620
+
1621
+ private isUserDisabledError(
1622
+ err: any
1623
+ ): err is { message: 'User is disabled.' } {
1624
+ return this.isErrorWithMessage(err) && err.message === 'User is disabled.';
1625
+ }
1626
+
1627
+ private isUserDoesNotExistError(
1628
+ err: any
1629
+ ): err is { message: 'User does not exist.' } {
1630
+ return (
1631
+ this.isErrorWithMessage(err) && err.message === 'User does not exist.'
1632
+ );
1633
+ }
1634
+
1635
+ private isRefreshTokenExpiredError(
1636
+ err: any
1637
+ ): err is { message: 'Refresh Token has expired' } {
1638
+ return (
1639
+ this.isErrorWithMessage(err) &&
1640
+ err.message === 'Refresh Token has expired'
1641
+ );
1642
+ }
1643
+
1644
+ private isPasswordResetRequiredError(
1645
+ err: any
1646
+ ): err is { message: 'Password reset required for the user' } {
1647
+ return (
1648
+ this.isErrorWithMessage(err) &&
1649
+ err.message === 'Password reset required for the user'
1650
+ );
1651
+ }
1652
+
1653
+ private isSignedInHostedUI() {
1654
+ return (
1655
+ this._oAuthHandler &&
1656
+ this._storage.getItem('amplify-signin-with-hostedUI') === 'true'
1657
+ );
1658
+ }
1659
+
1660
+ private isSessionInvalid(err: any) {
1661
+ return (
1662
+ this.isUserDisabledError(err) ||
1663
+ this.isUserDoesNotExistError(err) ||
1664
+ this.isTokenRevokedError(err) ||
1665
+ this.isRefreshTokenRevokedError(err) ||
1666
+ this.isRefreshTokenExpiredError(err) ||
1667
+ this.isPasswordResetRequiredError(err)
1668
+ );
1669
+ }
1670
+
1671
+ private async cleanUpInvalidSession(user: CognitoUser) {
1672
+ user.signOut();
1673
+ this.user = null;
1674
+ try {
1675
+ await this.cleanCachedItems(); // clean aws credentials
1676
+ } catch (e) {
1677
+ logger.debug('failed to clear cached items');
1678
+ }
1679
+ if (this.isSignedInHostedUI()) {
1680
+ return new Promise((res, rej) => {
1681
+ this.oAuthSignOutRedirect(res, rej);
1682
+ });
1683
+ } else {
1684
+ dispatchAuthEvent('signOut', this.user, `A user has been signed out`);
1685
+ }
1686
+ }
1687
+
1688
+ /**
1689
+ * Get current authenticated user
1690
+ * @return - A promise resolves to current authenticated CognitoUser if success
1691
+ */
1692
+ public currentUserPoolUser(
1693
+ params?: CurrentUserOpts,
1694
+ customUserAgentDetails?: CustomUserAgentDetails
1695
+ ): Promise<CognitoUser | any> {
1696
+ if (!this.userPool) {
1697
+ return this.rejectNoUserPool();
1698
+ }
1699
+
1700
+ return new Promise((res, rej) => {
1701
+ this._storageSync
1702
+ .then(async () => {
1703
+ if (this.isOAuthInProgress()) {
1704
+ logger.debug('OAuth signIn in progress, waiting for resolution...');
1705
+
1706
+ await new Promise(res => {
1707
+ const timeoutId = setTimeout(() => {
1708
+ logger.debug('OAuth signIn in progress timeout');
1709
+
1710
+ Hub.remove('auth', hostedUISignCallback);
1711
+
1712
+ res();
1713
+ }, OAUTH_FLOW_MS_TIMEOUT);
1714
+
1715
+ Hub.listen('auth', hostedUISignCallback);
1716
+
1717
+ function hostedUISignCallback({ payload }) {
1718
+ const { event } = payload;
1719
+
1720
+ if (
1721
+ event === 'cognitoHostedUI' ||
1722
+ event === 'cognitoHostedUI_failure'
1723
+ ) {
1724
+ logger.debug(`OAuth signIn resolved: ${event}`);
1725
+ clearTimeout(timeoutId);
1726
+
1727
+ Hub.remove('auth', hostedUISignCallback);
1728
+
1729
+ res();
1730
+ }
1731
+ }
1732
+ });
1733
+ }
1734
+
1735
+ const user = this.userPool.getCurrentUser();
1736
+
1737
+ if (!user) {
1738
+ logger.debug('Failed to get user from user pool');
1739
+ rej('No current user');
1740
+ return;
1741
+ }
1742
+
1743
+ // refresh the session if the session expired.
1744
+ try {
1745
+ const session = await this._userSession(user);
1746
+
1747
+ // get user data from Cognito
1748
+ const bypassCache = params ? params.bypassCache : false;
1749
+
1750
+ if (bypassCache) {
1751
+ await this.Credentials.clear();
1752
+ }
1753
+
1754
+ const clientMetadata = this._config.clientMetadata;
1755
+
1756
+ // validate the token's scope first before calling this function
1757
+ const { scope = '' } = session.getAccessToken().decodePayload();
1758
+ if (scope.split(' ').includes(USER_ADMIN_SCOPE)) {
1759
+ user.getUserData(
1760
+ async (err, data) => {
1761
+ if (err) {
1762
+ logger.debug('getting user data failed', err);
1763
+ if (this.isSessionInvalid(err)) {
1764
+ try {
1765
+ await this.cleanUpInvalidSession(user);
1766
+ } catch (cleanUpError) {
1767
+ rej(
1768
+ new Error(
1769
+ `Session is invalid due to: ${err.message} and failed to clean up invalid session: ${cleanUpError.message}`
1770
+ )
1771
+ );
1772
+ return;
1773
+ }
1774
+ rej(err);
1775
+ } else {
1776
+ res(user);
1777
+ }
1778
+ return;
1779
+ }
1780
+ const preferredMFA = data.PreferredMfaSetting || 'NOMFA';
1781
+ const attributeList = [];
1782
+
1783
+ for (let i = 0; i < data.UserAttributes.length; i++) {
1784
+ const attribute = {
1785
+ Name: data.UserAttributes[i].Name,
1786
+ Value: data.UserAttributes[i].Value,
1787
+ };
1788
+ const userAttribute = new CognitoUserAttribute(attribute);
1789
+ attributeList.push(userAttribute);
1790
+ }
1791
+
1792
+ const attributes = this.attributesToObject(attributeList);
1793
+ Object.assign(user, { attributes, preferredMFA });
1794
+ return res(user);
1795
+ },
1796
+ { bypassCache, clientMetadata }
1797
+ );
1798
+ } else {
1799
+ logger.debug(
1800
+ `Unable to get the user data because the ${USER_ADMIN_SCOPE} ` +
1801
+ `is not in the scopes of the access token`
1802
+ );
1803
+ return res(user);
1804
+ }
1805
+ } catch (err) {
1806
+ rej(err);
1807
+ }
1808
+ })
1809
+ .catch(e => {
1810
+ logger.debug('Failed to sync cache info into memory', e);
1811
+ return rej(e);
1812
+ });
1813
+ });
1814
+ }
1815
+
1816
+ private isOAuthInProgress(): boolean {
1817
+ return this.oAuthFlowInProgress;
1818
+ }
1819
+
1820
+ /**
1821
+ * Get current authenticated user
1822
+ * @param {CurrentUserOpts} - options for getting the current user
1823
+ * @return - A promise resolves to current authenticated CognitoUser if success
1824
+ */
1825
+ public async currentAuthenticatedUser(
1826
+ params?: CurrentUserOpts,
1827
+ customUserAgentDetails?: CustomUserAgentDetails
1828
+ ): Promise<CognitoUser | any> {
1829
+ logger.debug('getting current authenticated user');
1830
+ let federatedUser = null;
1831
+ try {
1832
+ await this._storageSync;
1833
+ } catch (e) {
1834
+ logger.debug('Failed to sync cache info into memory', e);
1835
+ throw e;
1836
+ }
1837
+
1838
+ try {
1839
+ const federatedInfo = JSON.parse(
1840
+ this._storage.getItem('aws-amplify-federatedInfo')
1841
+ );
1842
+ if (federatedInfo) {
1843
+ federatedUser = {
1844
+ ...federatedInfo.user,
1845
+ token: federatedInfo.token,
1846
+ };
1847
+ }
1848
+ } catch (e) {
1849
+ logger.debug('cannot load federated user from auth storage');
1850
+ }
1851
+
1852
+ if (federatedUser) {
1853
+ this.user = federatedUser;
1854
+ logger.debug('get current authenticated federated user', this.user);
1855
+ return this.user;
1856
+ } else {
1857
+ logger.debug('get current authenticated userpool user');
1858
+ let user = null;
1859
+ try {
1860
+ user = await this.currentUserPoolUser(params);
1861
+ } catch (e) {
1862
+ if (e === 'No userPool') {
1863
+ logger.error(
1864
+ 'Cannot get the current user because the user pool is missing. ' +
1865
+ 'Please make sure the Auth module is configured with a valid Cognito User Pool ID'
1866
+ );
1867
+ }
1868
+ logger.debug('The user is not authenticated by the error', e);
1869
+ return Promise.reject('The user is not authenticated');
1870
+ }
1871
+ this.user = user;
1872
+ return this.user;
1873
+ }
1874
+ }
1875
+
1876
+ /**
1877
+ * Get current user's session
1878
+ * @return - A promise resolves to session object if success
1879
+ */
1880
+ public currentSession(
1881
+ customUserAgentDetails?: CustomUserAgentDetails
1882
+ ): Promise<CognitoUserSession> {
1883
+ const that = this;
1884
+ logger.debug('Getting current session');
1885
+ // Purposely not calling the reject method here because we don't need a console error
1886
+ if (!this.userPool) {
1887
+ return Promise.reject(new Error('No User Pool in the configuration.'));
1888
+ }
1889
+
1890
+ return new Promise((res, rej) => {
1891
+ that
1892
+ .currentUserPoolUser()
1893
+ .then(user => {
1894
+ that
1895
+ .userSession(user)
1896
+ .then(session => {
1897
+ res(session);
1898
+ return;
1899
+ })
1900
+ .catch(e => {
1901
+ logger.debug('Failed to get the current session', e);
1902
+ rej(e);
1903
+ return;
1904
+ });
1905
+ })
1906
+ .catch(e => {
1907
+ logger.debug('Failed to get the current user', e);
1908
+ rej(e);
1909
+ return;
1910
+ });
1911
+ });
1912
+ }
1913
+
1914
+ private async _userSession(user?: CognitoUser): Promise<CognitoUserSession> {
1915
+ if (!user) {
1916
+ logger.debug('the user is null');
1917
+ return this.rejectAuthError(AuthErrorTypes.NoUserSession);
1918
+ }
1919
+ const clientMetadata = this._config.clientMetadata;
1920
+ // Debouncing the concurrent userSession calls by caching the promise.
1921
+ // This solution assumes users will always call this function with the same CognitoUser instance.
1922
+ if (this.inflightSessionPromiseCounter === 0) {
1923
+ this.inflightSessionPromise = new Promise<CognitoUserSession>(
1924
+ (res, rej) => {
1925
+ user.getSession(
1926
+ async (err, session) => {
1927
+ if (err) {
1928
+ logger.debug('Failed to get the session from user', user);
1929
+ if (this.isSessionInvalid(err)) {
1930
+ try {
1931
+ await this.cleanUpInvalidSession(user);
1932
+ } catch (cleanUpError) {
1933
+ rej(
1934
+ new Error(
1935
+ `Session is invalid due to: ${err.message} and failed to clean up invalid session: ${cleanUpError.message}`
1936
+ )
1937
+ );
1938
+ return;
1939
+ }
1940
+ }
1941
+ rej(err);
1942
+ return;
1943
+ } else {
1944
+ logger.debug('Succeed to get the user session', session);
1945
+ res(session);
1946
+ return;
1947
+ }
1948
+ },
1949
+ { clientMetadata }
1950
+ );
1951
+ }
1952
+ );
1953
+ }
1954
+ this.inflightSessionPromiseCounter++;
1955
+
1956
+ try {
1957
+ const userSession = await this.inflightSessionPromise;
1958
+ // Set private member. Avoid user.setSignInUserSession() to prevent excessive localstorage refresh.
1959
+ // @ts-ignore
1960
+ user.signInUserSession = userSession;
1961
+ return userSession!;
1962
+ } finally {
1963
+ this.inflightSessionPromiseCounter--;
1964
+ }
1965
+ }
1966
+
1967
+ /**
1968
+ * Get the corresponding user session
1969
+ * @param {Object} user - The CognitoUser object
1970
+ * @return - A promise resolves to the session
1971
+ */
1972
+ public userSession(
1973
+ user,
1974
+ customUserAgentDetails?: CustomUserAgentDetails
1975
+ ): Promise<CognitoUserSession> {
1976
+ return this._userSession(user);
1977
+ }
1978
+
1979
+ /**
1980
+ * Get authenticated credentials of current user.
1981
+ * @return - A promise resolves to be current user's credentials
1982
+ */
1983
+ public async currentUserCredentials(
1984
+ customUserAgentDetails?: CustomUserAgentDetails
1985
+ ): Promise<ICredentials> {
1986
+ logger.debug('Getting current user credentials');
1987
+
1988
+ try {
1989
+ await this._storageSync;
1990
+ } catch (e) {
1991
+ logger.debug('Failed to sync cache info into memory', e);
1992
+ throw e;
1993
+ }
1994
+
1995
+ // first to check whether there is federation info in the auth storage
1996
+ let federatedInfo = null;
1997
+ try {
1998
+ federatedInfo = JSON.parse(
1999
+ this._storage.getItem('aws-amplify-federatedInfo')
2000
+ );
2001
+ } catch (e) {
2002
+ logger.debug('failed to get or parse item aws-amplify-federatedInfo', e);
2003
+ }
2004
+
2005
+ if (federatedInfo) {
2006
+ // refresh the jwt token here if necessary
2007
+ return this.Credentials.refreshFederatedToken(federatedInfo);
2008
+ } else {
2009
+ return this.currentSession()
2010
+ .then(session => {
2011
+ logger.debug('getting session success', session);
2012
+ return this.Credentials.set(session, 'session');
2013
+ })
2014
+ .catch(() => {
2015
+ logger.debug('getting guest credentials');
2016
+ return this.Credentials.set(null, 'guest');
2017
+ });
2018
+ }
2019
+ }
2020
+
2021
+ public currentCredentials(
2022
+ customUserAgentDetails?: CustomUserAgentDetails
2023
+ ): Promise<ICredentials> {
2024
+ logger.debug('getting current credentials');
2025
+ return this.Credentials.get();
2026
+ }
2027
+
2028
+ /**
2029
+ * Initiate an attribute confirmation request
2030
+ * @param {Object} user - The CognitoUser
2031
+ * @param {Object} attr - The attributes to be verified
2032
+ * @return - A promise resolves to callback data if success
2033
+ */
2034
+ public verifyUserAttribute(
2035
+ user: CognitoUser | any,
2036
+ attr: string,
2037
+ clientMetadata: ClientMetaData = this._config.clientMetadata,
2038
+ customUserAgentDetails?: CustomUserAgentDetails
2039
+ ): Promise<void> {
2040
+ return new Promise((resolve, reject) => {
2041
+ user.getAttributeVerificationCode(
2042
+ attr,
2043
+ {
2044
+ onSuccess(success) {
2045
+ return resolve(success);
2046
+ },
2047
+ onFailure(err) {
2048
+ return reject(err);
2049
+ },
2050
+ },
2051
+ clientMetadata
2052
+ );
2053
+ });
2054
+ }
2055
+
2056
+ /**
2057
+ * Confirm an attribute using a confirmation code
2058
+ * @param {Object} user - The CognitoUser
2059
+ * @param {Object} attr - The attribute to be verified
2060
+ * @param {String} code - The confirmation code
2061
+ * @return - A promise resolves to callback data if success
2062
+ */
2063
+ public verifyUserAttributeSubmit(
2064
+ user: CognitoUser | any,
2065
+ attr: string,
2066
+ code: string,
2067
+ customUserAgentDetails?: CustomUserAgentDetails
2068
+ ): Promise<string> {
2069
+ if (!code) {
2070
+ return this.rejectAuthError(AuthErrorTypes.EmptyCode);
2071
+ }
2072
+
2073
+ return new Promise((resolve, reject) => {
2074
+ user.verifyAttribute(attr, code, {
2075
+ onSuccess(data) {
2076
+ resolve(data);
2077
+ return;
2078
+ },
2079
+ onFailure(err) {
2080
+ reject(err);
2081
+ return;
2082
+ },
2083
+ });
2084
+ });
2085
+ }
2086
+
2087
+ public verifyCurrentUserAttribute(
2088
+ attr: string,
2089
+ customUserAgentDetails?: CustomUserAgentDetails
2090
+ ): Promise<void> {
2091
+ const that = this;
2092
+ return that
2093
+ .currentUserPoolUser()
2094
+ .then(user => that.verifyUserAttribute(user, attr));
2095
+ }
2096
+
2097
+ /**
2098
+ * Confirm current user's attribute using a confirmation code
2099
+ * @param {Object} attr - The attribute to be verified
2100
+ * @param {String} code - The confirmation code
2101
+ * @return - A promise resolves to callback data if success
2102
+ */
2103
+ verifyCurrentUserAttributeSubmit(
2104
+ attr: string,
2105
+ code: string,
2106
+ customUserAgentDetails?: CustomUserAgentDetails
2107
+ ): Promise<string> {
2108
+ const that = this;
2109
+ return that
2110
+ .currentUserPoolUser()
2111
+ .then(user => that.verifyUserAttributeSubmit(user, attr, code));
2112
+ }
2113
+
2114
+ private async cognitoIdentitySignOut(
2115
+ opts: SignOutOpts,
2116
+ user: CognitoUser | any
2117
+ ) {
2118
+ try {
2119
+ await this._storageSync;
2120
+ } catch (e) {
2121
+ logger.debug('Failed to sync cache info into memory', e);
2122
+ throw e;
2123
+ }
2124
+
2125
+ const isSignedInHostedUI =
2126
+ this._oAuthHandler &&
2127
+ this._storage.getItem('amplify-signin-with-hostedUI') === 'true';
2128
+
2129
+ return new Promise((res, rej) => {
2130
+ if (opts && opts.global) {
2131
+ logger.debug('user global sign out', user);
2132
+ // in order to use global signout
2133
+ // we must validate the user as an authenticated user by using getSession
2134
+ const clientMetadata = this._config.clientMetadata; // TODO: verify behavior if this is override during signIn
2135
+
2136
+ user.getSession(
2137
+ async (err, result) => {
2138
+ if (err) {
2139
+ logger.debug('failed to get the user session', err);
2140
+ if (this.isSessionInvalid(err)) {
2141
+ try {
2142
+ await this.cleanUpInvalidSession(user);
2143
+ } catch (cleanUpError) {
2144
+ rej(
2145
+ new Error(
2146
+ `Session is invalid due to: ${err.message} and failed to clean up invalid session: ${cleanUpError.message}`
2147
+ )
2148
+ );
2149
+ return;
2150
+ }
2151
+ }
2152
+ return rej(err);
2153
+ }
2154
+ user.globalSignOut({
2155
+ onSuccess: data => {
2156
+ logger.debug('global sign out success');
2157
+ if (isSignedInHostedUI) {
2158
+ this.oAuthSignOutRedirect(res, rej);
2159
+ } else {
2160
+ return res();
2161
+ }
2162
+ },
2163
+ onFailure: err => {
2164
+ logger.debug('global sign out failed', err);
2165
+ return rej(err);
2166
+ },
2167
+ });
2168
+ },
2169
+ { clientMetadata }
2170
+ );
2171
+ } else {
2172
+ logger.debug('user sign out', user);
2173
+ user.signOut(() => {
2174
+ if (isSignedInHostedUI) {
2175
+ this.oAuthSignOutRedirect(res, rej);
2176
+ } else {
2177
+ return res();
2178
+ }
2179
+ });
2180
+ }
2181
+ });
2182
+ }
2183
+
2184
+ private oAuthSignOutRedirect(
2185
+ resolve: () => void,
2186
+ reject: (reason?: any) => void
2187
+ ) {
2188
+ const { isBrowser } = browserOrNode();
2189
+
2190
+ if (isBrowser) {
2191
+ this.oAuthSignOutRedirectOrReject(reject);
2192
+ } else {
2193
+ this.oAuthSignOutAndResolve(resolve);
2194
+ }
2195
+ }
2196
+
2197
+ private oAuthSignOutAndResolve(resolve: () => void) {
2198
+ this._oAuthHandler.signOut();
2199
+ resolve();
2200
+ }
2201
+
2202
+ private oAuthSignOutRedirectOrReject(reject: (reason?: any) => void) {
2203
+ this._oAuthHandler.signOut(); // this method redirects url
2204
+
2205
+ // App should be redirected to another url otherwise it will reject
2206
+ setTimeout(() => reject(Error('Signout timeout fail')), 3000);
2207
+ }
2208
+
2209
+ /**
2210
+ * Sign out method
2211
+ * @
2212
+ * @return - A promise resolved if success
2213
+ */
2214
+ public async signOut(
2215
+ opts?: SignOutOpts,
2216
+ customUserAgentDetails?: CustomUserAgentDetails
2217
+ ): Promise<any> {
2218
+ try {
2219
+ await this.cleanCachedItems();
2220
+ } catch (e) {
2221
+ logger.debug('failed to clear cached items');
2222
+ }
2223
+
2224
+ if (this.userPool) {
2225
+ const user = this.userPool.getCurrentUser();
2226
+ if (user) {
2227
+ await this.cognitoIdentitySignOut(opts, user);
2228
+ } else {
2229
+ logger.debug('no current Cognito user');
2230
+ }
2231
+ } else {
2232
+ logger.debug('no Cognito User pool');
2233
+ }
2234
+
2235
+ /**
2236
+ * Note for future refactor - no reliable way to get username with
2237
+ * Cognito User Pools vs Identity when federating with Social Providers
2238
+ * This is why we need a well structured session object that can be inspected
2239
+ * and information passed back in the message below for Hub dispatch
2240
+ */
2241
+ dispatchAuthEvent('signOut', this.user, `A user has been signed out`);
2242
+ this.user = null;
2243
+ }
2244
+
2245
+ private async cleanCachedItems() {
2246
+ // clear cognito cached item
2247
+ await this.Credentials.clear();
2248
+ }
2249
+
2250
+ /**
2251
+ * Change a password for an authenticated user
2252
+ * @param {Object} user - The CognitoUser object
2253
+ * @param {String} oldPassword - the current password
2254
+ * @param {String} newPassword - the requested new password
2255
+ * @return - A promise resolves if success
2256
+ */
2257
+ public changePassword(
2258
+ user: CognitoUser | any,
2259
+ oldPassword: string,
2260
+ newPassword: string,
2261
+ clientMetadata: ClientMetaData = this._config.clientMetadata,
2262
+ customUserAgentDetails?: CustomUserAgentDetails
2263
+ ): Promise<'SUCCESS'> {
2264
+ return new Promise((resolve, reject) => {
2265
+ this.userSession(user).then(session => {
2266
+ user.changePassword(
2267
+ oldPassword,
2268
+ newPassword,
2269
+ (err, data) => {
2270
+ if (err) {
2271
+ logger.debug('change password failure', err);
2272
+ return reject(err);
2273
+ } else {
2274
+ return resolve(data);
2275
+ }
2276
+ },
2277
+ clientMetadata
2278
+ );
2279
+ });
2280
+ });
2281
+ }
2282
+
2283
+ /**
2284
+ * Initiate a forgot password request
2285
+ * @param {String} username - the username to change password
2286
+ * @return - A promise resolves if success
2287
+ */
2288
+ public forgotPassword(
2289
+ username: string,
2290
+ clientMetadata: ClientMetaData = this._config.clientMetadata,
2291
+ customUserAgentDetails?: CustomUserAgentDetails
2292
+ ): Promise<any> {
2293
+ if (!this.userPool) {
2294
+ return this.rejectNoUserPool();
2295
+ }
2296
+ if (!username) {
2297
+ return this.rejectAuthError(AuthErrorTypes.EmptyUsername);
2298
+ }
2299
+
2300
+ const user = this.createCognitoUser(username);
2301
+ return new Promise((resolve, reject) => {
2302
+ user.forgotPassword(
2303
+ {
2304
+ onSuccess: () => {
2305
+ resolve();
2306
+ return;
2307
+ },
2308
+ onFailure: err => {
2309
+ logger.debug('forgot password failure', err);
2310
+ dispatchAuthEvent(
2311
+ 'forgotPassword_failure',
2312
+ err,
2313
+ `${username} forgotPassword failed`
2314
+ );
2315
+ reject(err);
2316
+ return;
2317
+ },
2318
+ inputVerificationCode: data => {
2319
+ dispatchAuthEvent(
2320
+ 'forgotPassword',
2321
+ user,
2322
+ `${username} has initiated forgot password flow`
2323
+ );
2324
+ resolve(data);
2325
+ return;
2326
+ },
2327
+ },
2328
+ clientMetadata
2329
+ );
2330
+ });
2331
+ }
2332
+
2333
+ /**
2334
+ * Confirm a new password using a confirmation Code
2335
+ * @param {String} username - The username
2336
+ * @param {String} code - The confirmation code
2337
+ * @param {String} password - The new password
2338
+ * @return - A promise that resolves if success
2339
+ */
2340
+ public forgotPasswordSubmit(
2341
+ username: string,
2342
+ code: string,
2343
+ password: string,
2344
+ clientMetadata: ClientMetaData = this._config.clientMetadata,
2345
+ customUserAgentDetails?: CustomUserAgentDetails
2346
+ ): Promise<string> {
2347
+ if (!this.userPool) {
2348
+ return this.rejectNoUserPool();
2349
+ }
2350
+ if (!username) {
2351
+ return this.rejectAuthError(AuthErrorTypes.EmptyUsername);
2352
+ }
2353
+ if (!code) {
2354
+ return this.rejectAuthError(AuthErrorTypes.EmptyCode);
2355
+ }
2356
+ if (!password) {
2357
+ return this.rejectAuthError(AuthErrorTypes.EmptyPassword);
2358
+ }
2359
+
2360
+ const user = this.createCognitoUser(username);
2361
+ return new Promise((resolve, reject) => {
2362
+ user.confirmPassword(
2363
+ code,
2364
+ password,
2365
+ {
2366
+ onSuccess: success => {
2367
+ dispatchAuthEvent(
2368
+ 'forgotPasswordSubmit',
2369
+ user,
2370
+ `${username} forgotPasswordSubmit successful`
2371
+ );
2372
+ resolve(success);
2373
+ return;
2374
+ },
2375
+ onFailure: err => {
2376
+ dispatchAuthEvent(
2377
+ 'forgotPasswordSubmit_failure',
2378
+ err,
2379
+ `${username} forgotPasswordSubmit failed`
2380
+ );
2381
+ reject(err);
2382
+ return;
2383
+ },
2384
+ },
2385
+ clientMetadata
2386
+ );
2387
+ });
2388
+ }
2389
+
2390
+ /**
2391
+ * Get user information
2392
+ * @async
2393
+ * @return {Object }- current User's information
2394
+ */
2395
+ public async currentUserInfo(
2396
+ customUserAgentDetails?: CustomUserAgentDetails
2397
+ ) {
2398
+ const source = this.Credentials.getCredSource();
2399
+
2400
+ if (!source || source === 'aws' || source === 'userPool') {
2401
+ const user = await this.currentUserPoolUser().catch(err =>
2402
+ logger.error(err)
2403
+ );
2404
+ if (!user) {
2405
+ return null;
2406
+ }
2407
+
2408
+ try {
2409
+ const attributes = await this.userAttributes(user);
2410
+ const userAttrs: object = this.attributesToObject(attributes);
2411
+ let credentials = null;
2412
+ try {
2413
+ credentials = await this.currentCredentials();
2414
+ } catch (e) {
2415
+ logger.debug(
2416
+ 'Failed to retrieve credentials while getting current user info',
2417
+ e
2418
+ );
2419
+ }
2420
+
2421
+ const info = {
2422
+ id: credentials ? credentials.identityId : undefined,
2423
+ username: user.getUsername(),
2424
+ attributes: userAttrs,
2425
+ };
2426
+ return info;
2427
+ } catch (err) {
2428
+ logger.error('currentUserInfo error', err);
2429
+ return {};
2430
+ }
2431
+ }
2432
+
2433
+ if (source === 'federated') {
2434
+ const user = this.user;
2435
+ return user ? user : {};
2436
+ }
2437
+ }
2438
+
2439
+ public async federatedSignIn(
2440
+ providerOrOptions:
2441
+ | LegacyProvider
2442
+ | FederatedSignInOptions
2443
+ | FederatedSignInOptionsCustom,
2444
+ response?: FederatedResponse,
2445
+ user?: FederatedUser,
2446
+ customUserAgentDetails?: CustomUserAgentDetails
2447
+ ): Promise<ICredentials> {
2448
+ if (!this._config.identityPoolId && !this._config.userPoolId) {
2449
+ throw new Error(
2450
+ `Federation requires either a User Pool or Identity Pool in config`
2451
+ );
2452
+ }
2453
+
2454
+ // Ensure backwards compatability
2455
+ if (typeof providerOrOptions === 'undefined') {
2456
+ if (this._config.identityPoolId && !this._config.userPoolId) {
2457
+ throw new Error(
2458
+ `Federation with Identity Pools requires tokens passed as arguments`
2459
+ );
2460
+ }
2461
+ }
2462
+
2463
+ if (
2464
+ isFederatedSignInOptions(providerOrOptions) ||
2465
+ isFederatedSignInOptionsCustom(providerOrOptions) ||
2466
+ hasCustomState(providerOrOptions) ||
2467
+ typeof providerOrOptions === 'undefined'
2468
+ ) {
2469
+ const options = providerOrOptions || {
2470
+ provider: CognitoHostedUIIdentityProvider.Cognito,
2471
+ };
2472
+ const provider = isFederatedSignInOptions(options)
2473
+ ? options.provider
2474
+ : (options as FederatedSignInOptionsCustom).customProvider;
2475
+
2476
+ const customState = isFederatedSignInOptions(options)
2477
+ ? options.customState
2478
+ : (options as FederatedSignInOptionsCustom).customState;
2479
+
2480
+ if (this._config.userPoolId) {
2481
+ const client_id = isCognitoHostedOpts(this._config.oauth)
2482
+ ? this._config.userPoolWebClientId
2483
+ : this._config.oauth.clientID;
2484
+ /*Note: Invenstigate automatically adding trailing slash */
2485
+ const redirect_uri = isCognitoHostedOpts(this._config.oauth)
2486
+ ? this._config.oauth.redirectSignIn
2487
+ : this._config.oauth.redirectUri;
2488
+
2489
+ this._oAuthHandler.oauthSignIn(
2490
+ this._config.oauth.responseType,
2491
+ this._config.oauth.domain,
2492
+ redirect_uri,
2493
+ client_id,
2494
+ provider,
2495
+ customState
2496
+ );
2497
+ }
2498
+ } else {
2499
+ const provider = providerOrOptions;
2500
+ // To check if the user is already logged in
2501
+ try {
2502
+ const loggedInUser = JSON.stringify(
2503
+ JSON.parse(this._storage.getItem('aws-amplify-federatedInfo')).user
2504
+ );
2505
+ if (loggedInUser) {
2506
+ logger.warn(`There is already a signed in user: ${loggedInUser} in your app.
2507
+ You should not call Auth.federatedSignIn method again as it may cause unexpected behavior.`);
2508
+ }
2509
+ } catch (e) {}
2510
+
2511
+ const { token, identity_id, expires_at } = response;
2512
+ // Because this.Credentials.set would update the user info with identity id
2513
+ // So we need to retrieve the user again.
2514
+ const credentials = await this.Credentials.set(
2515
+ { provider, token, identity_id, user, expires_at },
2516
+ 'federation'
2517
+ );
2518
+ const currentUser = await this.currentAuthenticatedUser();
2519
+ dispatchAuthEvent(
2520
+ 'signIn',
2521
+ currentUser,
2522
+ `A user ${currentUser.username} has been signed in`
2523
+ );
2524
+ logger.debug('federated sign in credentials', credentials);
2525
+ return credentials;
2526
+ }
2527
+ }
2528
+
2529
+ /**
2530
+ * Used to complete the OAuth flow with or without the Cognito Hosted UI
2531
+ * @param {String} URL - optional parameter for customers to pass in the response URL
2532
+ */
2533
+ private async _handleAuthResponse(
2534
+ URL?: string,
2535
+ customUserAgentDetails?: CustomUserAgentDetails
2536
+ ) {
2537
+ if (this.oAuthFlowInProgress) {
2538
+ logger.debug(`Skipping URL ${URL} current flow in progress`);
2539
+ return;
2540
+ }
2541
+
2542
+ try {
2543
+ this.oAuthFlowInProgress = true;
2544
+ if (!this._config.userPoolId) {
2545
+ throw new Error(
2546
+ `OAuth responses require a User Pool defined in config`
2547
+ );
2548
+ }
2549
+
2550
+ dispatchAuthEvent(
2551
+ 'parsingCallbackUrl',
2552
+ { url: URL },
2553
+ `The callback url is being parsed`
2554
+ );
2555
+
2556
+ const currentUrl =
2557
+ URL || (browserOrNode().isBrowser ? window.location.href : '');
2558
+
2559
+ const hasCodeOrError = !!(parse(currentUrl).query || '')
2560
+ .split('&')
2561
+ .map(entry => entry.split('='))
2562
+ .find(([k]) => k === 'code' || k === 'error');
2563
+
2564
+ const hasTokenOrError = !!(parse(currentUrl).hash || '#')
2565
+ .substr(1)
2566
+ .split('&')
2567
+ .map(entry => entry.split('='))
2568
+ .find(([k]) => k === 'access_token' || k === 'error');
2569
+
2570
+ if (hasCodeOrError || hasTokenOrError) {
2571
+ this._storage.setItem('amplify-redirected-from-hosted-ui', 'true');
2572
+ try {
2573
+ const { accessToken, idToken, refreshToken, state } =
2574
+ await this._oAuthHandler.handleAuthResponse(currentUrl);
2575
+ const session = new CognitoUserSession({
2576
+ IdToken: new CognitoIdToken({ IdToken: idToken }),
2577
+ RefreshToken: new CognitoRefreshToken({
2578
+ RefreshToken: refreshToken,
2579
+ }),
2580
+ AccessToken: new CognitoAccessToken({
2581
+ AccessToken: accessToken,
2582
+ }),
2583
+ });
2584
+
2585
+ let credentials;
2586
+ // Get AWS Credentials & store if Identity Pool is defined
2587
+ if (this._config.identityPoolId) {
2588
+ credentials = await this.Credentials.set(session, 'session');
2589
+ logger.debug('AWS credentials', credentials);
2590
+ }
2591
+
2592
+ /*
2593
+ Prior to the request we do sign the custom state along with the state we set. This check will verify
2594
+ if there is a dash indicated when setting custom state from the request. If a dash is contained
2595
+ then there is custom state present on the state string.
2596
+ */
2597
+ const isCustomStateIncluded = /-/.test(state);
2598
+
2599
+ /*
2600
+ The following is to create a user for the Cognito Identity SDK to store the tokens
2601
+ When we remove this SDK later that logic will have to be centralized in our new version
2602
+ */
2603
+ //#region
2604
+ const currentUser = this.createCognitoUser(
2605
+ session.getIdToken().decodePayload()['cognito:username']
2606
+ );
2607
+
2608
+ // This calls cacheTokens() in Cognito SDK
2609
+ currentUser.setSignInUserSession(session);
2610
+
2611
+ if (window && typeof window.history !== 'undefined') {
2612
+ window.history.replaceState(
2613
+ {},
2614
+ null,
2615
+ (this._config.oauth as AwsCognitoOAuthOpts).redirectSignIn
2616
+ );
2617
+ }
2618
+
2619
+ dispatchAuthEvent(
2620
+ 'signIn',
2621
+ currentUser,
2622
+ `A user ${currentUser.getUsername()} has been signed in`
2623
+ );
2624
+ dispatchAuthEvent(
2625
+ 'cognitoHostedUI',
2626
+ currentUser,
2627
+ `A user ${currentUser.getUsername()} has been signed in via Cognito Hosted UI`
2628
+ );
2629
+
2630
+ if (isCustomStateIncluded) {
2631
+ const customState = state.split('-').splice(1).join('-');
2632
+
2633
+ dispatchAuthEvent(
2634
+ 'customOAuthState',
2635
+ urlSafeDecode(customState),
2636
+ `State for user ${currentUser.getUsername()}`
2637
+ );
2638
+ }
2639
+ //#endregion
2640
+
2641
+ return credentials;
2642
+ } catch (err) {
2643
+ logger.debug('Error in cognito hosted auth response', err);
2644
+
2645
+ // Just like a successful handling of `?code`, replace the window history to "dispose" of the `code`.
2646
+ // Otherwise, reloading the page will throw errors as the `code` has already been spent.
2647
+ if (window && typeof window.history !== 'undefined') {
2648
+ window.history.replaceState(
2649
+ {},
2650
+ null,
2651
+ (this._config.oauth as AwsCognitoOAuthOpts).redirectSignIn
2652
+ );
2653
+ }
2654
+
2655
+ dispatchAuthEvent(
2656
+ 'signIn_failure',
2657
+ err,
2658
+ `The OAuth response flow failed`
2659
+ );
2660
+ dispatchAuthEvent(
2661
+ 'cognitoHostedUI_failure',
2662
+ err,
2663
+ `A failure occurred when returning to the Cognito Hosted UI`
2664
+ );
2665
+ dispatchAuthEvent(
2666
+ 'customState_failure',
2667
+ err,
2668
+ `A failure occurred when returning state`
2669
+ );
2670
+ }
2671
+ }
2672
+ } finally {
2673
+ this.oAuthFlowInProgress = false;
2674
+ }
2675
+ }
2676
+
2677
+ /**
2678
+ * Compact version of credentials
2679
+ * @param {Object} credentials
2680
+ * @return {Object} - Credentials
2681
+ */
2682
+ public essentialCredentials(
2683
+ credentials,
2684
+ customUserAgentDetails?: CustomUserAgentDetails
2685
+ ): ICredentials {
2686
+ return {
2687
+ accessKeyId: credentials.accessKeyId,
2688
+ sessionToken: credentials.sessionToken,
2689
+ secretAccessKey: credentials.secretAccessKey,
2690
+ identityId: credentials.identityId,
2691
+ authenticated: credentials.authenticated,
2692
+ };
2693
+ }
2694
+
2695
+ private attributesToObject(attributes) {
2696
+ const obj = {};
2697
+ if (attributes) {
2698
+ attributes.map(attribute => {
2699
+ if (
2700
+ attribute.Name === 'email_verified' ||
2701
+ attribute.Name === 'phone_number_verified'
2702
+ ) {
2703
+ obj[attribute.Name] =
2704
+ this.isTruthyString(attribute.Value) || attribute.Value === true;
2705
+ } else {
2706
+ obj[attribute.Name] = attribute.Value;
2707
+ }
2708
+ });
2709
+ }
2710
+ return obj;
2711
+ }
2712
+
2713
+ private isTruthyString(value: any): boolean {
2714
+ return (
2715
+ typeof value.toLowerCase === 'function' && value.toLowerCase() === 'true'
2716
+ );
2717
+ }
2718
+
2719
+ private createCognitoUser(username: string): CognitoUser {
2720
+ const userData: ICognitoUserData = {
2721
+ Username: username,
2722
+ Pool: this.userPool,
2723
+ };
2724
+ userData.Storage = this._storage;
2725
+
2726
+ const { authenticationFlowType } = this._config;
2727
+
2728
+ const user = new CognitoUser(userData);
2729
+ if (authenticationFlowType) {
2730
+ user.setAuthenticationFlowType(authenticationFlowType);
2731
+ }
2732
+ return user;
2733
+ }
2734
+
2735
+ private _isValidAuthStorage(obj) {
2736
+ // We need to check if the obj has the functions of Storage
2737
+ return (
2738
+ !!obj &&
2739
+ typeof obj.getItem === 'function' &&
2740
+ typeof obj.setItem === 'function' &&
2741
+ typeof obj.removeItem === 'function' &&
2742
+ typeof obj.clear === 'function'
2743
+ );
2744
+ }
2745
+
2746
+ private noUserPoolErrorHandler(config: AuthOptions): AuthErrorTypes {
2747
+ if (config) {
2748
+ if (!config.userPoolId || !config.identityPoolId) {
2749
+ return AuthErrorTypes.MissingAuthConfig;
2750
+ }
2751
+ }
2752
+ return AuthErrorTypes.NoConfig;
2753
+ }
2754
+
2755
+ private rejectAuthError(type: AuthErrorTypes): Promise<never> {
2756
+ return Promise.reject(new AuthError(type));
2757
+ }
2758
+
2759
+ private rejectNoUserPool(): Promise<never> {
2760
+ const type = this.noUserPoolErrorHandler(this._config);
2761
+ return Promise.reject(new NoUserPoolError(type));
2762
+ }
2763
+
2764
+ public async rememberDevice(
2765
+ customUserAgentDetails?: CustomUserAgentDetails
2766
+ ): Promise<string | AuthError> {
2767
+ let currUser;
2768
+
2769
+ try {
2770
+ currUser = await this.currentUserPoolUser();
2771
+ } catch (error) {
2772
+ logger.debug('The user is not authenticated by the error', error);
2773
+ return Promise.reject('The user is not authenticated');
2774
+ }
2775
+
2776
+ currUser.getCachedDeviceKeyAndPassword();
2777
+ return new Promise((res, rej) => {
2778
+ currUser.setDeviceStatusRemembered({
2779
+ onSuccess: data => {
2780
+ res(data);
2781
+ },
2782
+ onFailure: err => {
2783
+ if (err.code === 'InvalidParameterException') {
2784
+ rej(new AuthError(AuthErrorTypes.DeviceConfig));
2785
+ } else if (err.code === 'NetworkError') {
2786
+ rej(new AuthError(AuthErrorTypes.NetworkError));
2787
+ } else {
2788
+ rej(err);
2789
+ }
2790
+ },
2791
+ });
2792
+ });
2793
+ }
2794
+
2795
+ public async forgetDevice(
2796
+ customUserAgentDetails?: CustomUserAgentDetails
2797
+ ): Promise<void> {
2798
+ let currUser;
2799
+
2800
+ try {
2801
+ currUser = await this.currentUserPoolUser();
2802
+ } catch (error) {
2803
+ logger.debug('The user is not authenticated by the error', error);
2804
+ return Promise.reject('The user is not authenticated');
2805
+ }
2806
+
2807
+ currUser.getCachedDeviceKeyAndPassword();
2808
+ return new Promise((res, rej) => {
2809
+ currUser.forgetDevice({
2810
+ onSuccess: data => {
2811
+ res(data);
2812
+ },
2813
+ onFailure: err => {
2814
+ if (err.code === 'InvalidParameterException') {
2815
+ rej(new AuthError(AuthErrorTypes.DeviceConfig));
2816
+ } else if (err.code === 'NetworkError') {
2817
+ rej(new AuthError(AuthErrorTypes.NetworkError));
2818
+ } else {
2819
+ rej(err);
2820
+ }
2821
+ },
2822
+ });
2823
+ });
2824
+ }
2825
+
2826
+ public async fetchDevices(
2827
+ customUserAgentDetails?: CustomUserAgentDetails
2828
+ ): Promise<IAuthDevice[]> {
2829
+ let currUser;
2830
+
2831
+ try {
2832
+ currUser = await this.currentUserPoolUser();
2833
+ } catch (error) {
2834
+ logger.debug('The user is not authenticated by the error', error);
2835
+ throw new Error('The user is not authenticated');
2836
+ }
2837
+
2838
+ currUser.getCachedDeviceKeyAndPassword();
2839
+ return new Promise((res, rej) => {
2840
+ const cb = {
2841
+ onSuccess(data) {
2842
+ const deviceList: IAuthDevice[] = data.Devices.map(device => {
2843
+ const deviceName =
2844
+ device.DeviceAttributes.find(
2845
+ ({ Name }) => Name === 'device_name'
2846
+ ) || {};
2847
+
2848
+ const deviceInfo: IAuthDevice = {
2849
+ id: device.DeviceKey,
2850
+ name: deviceName.Value,
2851
+ };
2852
+ return deviceInfo;
2853
+ });
2854
+ res(deviceList);
2855
+ },
2856
+ onFailure: err => {
2857
+ if (err.code === 'InvalidParameterException') {
2858
+ rej(new AuthError(AuthErrorTypes.DeviceConfig));
2859
+ } else if (err.code === 'NetworkError') {
2860
+ rej(new AuthError(AuthErrorTypes.NetworkError));
2861
+ } else {
2862
+ rej(err);
2863
+ }
2864
+ },
2865
+ };
2866
+ currUser.listDevices(MAX_DEVICES, null, cb);
2867
+ });
2868
+ }
2869
+ }
2870
+
2871
+ export const InternalAuth = new InternalAuthClass(null);
2872
+ Amplify.register(InternalAuth);