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