@aws-amplify/auth 5.6.4-user-agent-backup.c6dfb36.0 → 5.6.4

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