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

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