@aws-amplify/auth 5.6.0 → 5.6.1-api-v6.4d00072.0

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