UNPKG

69.6 kBJavaScriptView Raw
1"use strict";
2
3exports.__esModule = true;
4exports["default"] = void 0;
5
6var _buffer = require("buffer");
7
8var _core = _interopRequireDefault(require("crypto-js/core"));
9
10var _libTypedarrays = _interopRequireDefault(require("crypto-js/lib-typedarrays"));
11
12var _encBase = _interopRequireDefault(require("crypto-js/enc-base64"));
13
14var _hmacSha = _interopRequireDefault(require("crypto-js/hmac-sha256"));
15
16var _BigInteger = _interopRequireDefault(require("./BigInteger"));
17
18var _AuthenticationHelper = _interopRequireDefault(require("./AuthenticationHelper"));
19
20var _CognitoAccessToken = _interopRequireDefault(require("./CognitoAccessToken"));
21
22var _CognitoIdToken = _interopRequireDefault(require("./CognitoIdToken"));
23
24var _CognitoRefreshToken = _interopRequireDefault(require("./CognitoRefreshToken"));
25
26var _CognitoUserSession = _interopRequireDefault(require("./CognitoUserSession"));
27
28var _DateHelper = _interopRequireDefault(require("./DateHelper"));
29
30var _CognitoUserAttribute = _interopRequireDefault(require("./CognitoUserAttribute"));
31
32var _StorageHelper = _interopRequireDefault(require("./StorageHelper"));
33
34function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
35
36/*!
37 * Copyright 2016 Amazon.com,
38 * Inc. or its affiliates. All Rights Reserved.
39 *
40 * Licensed under the Amazon Software License (the "License").
41 * You may not use this file except in compliance with the
42 * License. A copy of the License is located at
43 *
44 * http://aws.amazon.com/asl/
45 *
46 * or in the "license" file accompanying this file. This file is
47 * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
48 * CONDITIONS OF ANY KIND, express or implied. See the License
49 * for the specific language governing permissions and
50 * limitations under the License.
51 */
52// necessary for crypto js
53
54/**
55 * @callback nodeCallback
56 * @template T result
57 * @param {*} err The operation failure reason, or null.
58 * @param {T} result The operation result.
59 */
60
61/**
62 * @callback onFailure
63 * @param {*} err Failure reason.
64 */
65
66/**
67 * @callback onSuccess
68 * @template T result
69 * @param {T} result The operation result.
70 */
71
72/**
73 * @callback mfaRequired
74 * @param {*} details MFA challenge details.
75 */
76
77/**
78 * @callback customChallenge
79 * @param {*} details Custom challenge details.
80 */
81
82/**
83 * @callback inputVerificationCode
84 * @param {*} data Server response.
85 */
86
87/**
88 * @callback authSuccess
89 * @param {CognitoUserSession} session The new session.
90 * @param {bool=} userConfirmationNecessary User must be confirmed.
91 */
92var isBrowser = typeof navigator !== 'undefined';
93var userAgent = isBrowser ? navigator.userAgent : 'nodejs';
94/** @class */
95
96var CognitoUser = /*#__PURE__*/function () {
97 /**
98 * Constructs a new CognitoUser object
99 * @param {object} data Creation options
100 * @param {string} data.Username The user's username.
101 * @param {CognitoUserPool} data.Pool Pool containing the user.
102 * @param {object} data.Storage Optional storage object.
103 */
104 function CognitoUser(data) {
105 if (data == null || data.Username == null || data.Pool == null) {
106 throw new Error('Username and pool information are required.');
107 }
108
109 this.username = data.Username || '';
110 this.pool = data.Pool;
111 this.Session = null;
112 this.client = data.Pool.client;
113 this.signInUserSession = null;
114 this.authenticationFlowType = 'USER_SRP_AUTH';
115 this.storage = data.Storage || new _StorageHelper["default"]().getStorage();
116 this.keyPrefix = "CognitoIdentityServiceProvider." + this.pool.getClientId();
117 this.userDataKey = this.keyPrefix + "." + this.username + ".userData";
118 }
119 /**
120 * Sets the session for this user
121 * @param {CognitoUserSession} signInUserSession the session
122 * @returns {void}
123 */
124
125
126 var _proto = CognitoUser.prototype;
127
128 _proto.setSignInUserSession = function setSignInUserSession(signInUserSession) {
129 this.clearCachedUserData();
130 this.signInUserSession = signInUserSession;
131 this.cacheTokens();
132 }
133 /**
134 * @returns {CognitoUserSession} the current session for this user
135 */
136 ;
137
138 _proto.getSignInUserSession = function getSignInUserSession() {
139 return this.signInUserSession;
140 }
141 /**
142 * @returns {string} the user's username
143 */
144 ;
145
146 _proto.getUsername = function getUsername() {
147 return this.username;
148 }
149 /**
150 * @returns {String} the authentication flow type
151 */
152 ;
153
154 _proto.getAuthenticationFlowType = function getAuthenticationFlowType() {
155 return this.authenticationFlowType;
156 }
157 /**
158 * sets authentication flow type
159 * @param {string} authenticationFlowType New value.
160 * @returns {void}
161 */
162 ;
163
164 _proto.setAuthenticationFlowType = function setAuthenticationFlowType(authenticationFlowType) {
165 this.authenticationFlowType = authenticationFlowType;
166 }
167 /**
168 * This is used for authenticating the user through the custom authentication flow.
169 * @param {AuthenticationDetails} authDetails Contains the authentication data
170 * @param {object} callback Result callback map.
171 * @param {onFailure} callback.onFailure Called on any error.
172 * @param {customChallenge} callback.customChallenge Custom challenge
173 * response required to continue.
174 * @param {authSuccess} callback.onSuccess Called on success with the new session.
175 * @returns {void}
176 */
177 ;
178
179 _proto.initiateAuth = function initiateAuth(authDetails, callback) {
180 var _this = this;
181
182 var authParameters = authDetails.getAuthParameters();
183 authParameters.USERNAME = this.username;
184 var clientMetaData = Object.keys(authDetails.getValidationData()).length !== 0 ? authDetails.getValidationData() : authDetails.getClientMetadata();
185 var jsonReq = {
186 AuthFlow: 'CUSTOM_AUTH',
187 ClientId: this.pool.getClientId(),
188 AuthParameters: authParameters,
189 ClientMetadata: clientMetaData
190 };
191
192 if (this.getUserContextData()) {
193 jsonReq.UserContextData = this.getUserContextData();
194 }
195
196 this.client.request('InitiateAuth', jsonReq, function (err, data) {
197 if (err) {
198 return callback.onFailure(err);
199 }
200
201 var challengeName = data.ChallengeName;
202 var challengeParameters = data.ChallengeParameters;
203
204 if (challengeName === 'CUSTOM_CHALLENGE') {
205 _this.Session = data.Session;
206 return callback.customChallenge(challengeParameters);
207 }
208
209 _this.signInUserSession = _this.getCognitoUserSession(data.AuthenticationResult);
210
211 _this.cacheTokens();
212
213 return callback.onSuccess(_this.signInUserSession);
214 });
215 }
216 /**
217 * This is used for authenticating the user.
218 * stuff
219 * @param {AuthenticationDetails} authDetails Contains the authentication data
220 * @param {object} callback Result callback map.
221 * @param {onFailure} callback.onFailure Called on any error.
222 * @param {newPasswordRequired} callback.newPasswordRequired new
223 * password and any required attributes are required to continue
224 * @param {mfaRequired} callback.mfaRequired MFA code
225 * required to continue.
226 * @param {customChallenge} callback.customChallenge Custom challenge
227 * response required to continue.
228 * @param {authSuccess} callback.onSuccess Called on success with the new session.
229 * @returns {void}
230 */
231 ;
232
233 _proto.authenticateUser = function authenticateUser(authDetails, callback) {
234 if (this.authenticationFlowType === 'USER_PASSWORD_AUTH') {
235 return this.authenticateUserPlainUsernamePassword(authDetails, callback);
236 } else if (this.authenticationFlowType === 'USER_SRP_AUTH' || this.authenticationFlowType === 'CUSTOM_AUTH') {
237 return this.authenticateUserDefaultAuth(authDetails, callback);
238 }
239
240 return callback.onFailure(new Error('Authentication flow type is invalid.'));
241 }
242 /**
243 * PRIVATE ONLY: This is an internal only method and should not
244 * be directly called by the consumers.
245 * It calls the AuthenticationHelper for SRP related
246 * stuff
247 * @param {AuthenticationDetails} authDetails Contains the authentication data
248 * @param {object} callback Result callback map.
249 * @param {onFailure} callback.onFailure Called on any error.
250 * @param {newPasswordRequired} callback.newPasswordRequired new
251 * password and any required attributes are required to continue
252 * @param {mfaRequired} callback.mfaRequired MFA code
253 * required to continue.
254 * @param {customChallenge} callback.customChallenge Custom challenge
255 * response required to continue.
256 * @param {authSuccess} callback.onSuccess Called on success with the new session.
257 * @returns {void}
258 */
259 ;
260
261 _proto.authenticateUserDefaultAuth = function authenticateUserDefaultAuth(authDetails, callback) {
262 var _this2 = this;
263
264 var authenticationHelper = new _AuthenticationHelper["default"](this.pool.getUserPoolId().split('_')[1]);
265 var dateHelper = new _DateHelper["default"]();
266 var serverBValue;
267 var salt;
268 var authParameters = {};
269
270 if (this.deviceKey != null) {
271 authParameters.DEVICE_KEY = this.deviceKey;
272 }
273
274 authParameters.USERNAME = this.username;
275 authenticationHelper.getLargeAValue(function (errOnAValue, aValue) {
276 // getLargeAValue callback start
277 if (errOnAValue) {
278 callback.onFailure(errOnAValue);
279 }
280
281 authParameters.SRP_A = aValue.toString(16);
282
283 if (_this2.authenticationFlowType === 'CUSTOM_AUTH') {
284 authParameters.CHALLENGE_NAME = 'SRP_A';
285 }
286
287 var clientMetaData = Object.keys(authDetails.getValidationData()).length !== 0 ? authDetails.getValidationData() : authDetails.getClientMetadata();
288 var jsonReq = {
289 AuthFlow: _this2.authenticationFlowType,
290 ClientId: _this2.pool.getClientId(),
291 AuthParameters: authParameters,
292 ClientMetadata: clientMetaData
293 };
294
295 if (_this2.getUserContextData(_this2.username)) {
296 jsonReq.UserContextData = _this2.getUserContextData(_this2.username);
297 }
298
299 _this2.client.request('InitiateAuth', jsonReq, function (err, data) {
300 if (err) {
301 return callback.onFailure(err);
302 }
303
304 var challengeParameters = data.ChallengeParameters;
305 _this2.username = challengeParameters.USER_ID_FOR_SRP;
306 serverBValue = new _BigInteger["default"](challengeParameters.SRP_B, 16);
307 salt = new _BigInteger["default"](challengeParameters.SALT, 16);
308
309 _this2.getCachedDeviceKeyAndPassword();
310
311 authenticationHelper.getPasswordAuthenticationKey(_this2.username, authDetails.getPassword(), serverBValue, salt, function (errOnHkdf, hkdf) {
312 // getPasswordAuthenticationKey callback start
313 if (errOnHkdf) {
314 callback.onFailure(errOnHkdf);
315 }
316
317 var dateNow = dateHelper.getNowString();
318
319 var message = _core["default"].lib.WordArray.create(_buffer.Buffer.concat([_buffer.Buffer.from(_this2.pool.getUserPoolId().split('_')[1], 'utf8'), _buffer.Buffer.from(_this2.username, 'utf8'), _buffer.Buffer.from(challengeParameters.SECRET_BLOCK, 'base64'), _buffer.Buffer.from(dateNow, 'utf8')]));
320
321 var key = _core["default"].lib.WordArray.create(hkdf);
322
323 var signatureString = _encBase["default"].stringify((0, _hmacSha["default"])(message, key));
324
325 var challengeResponses = {};
326 challengeResponses.USERNAME = _this2.username;
327 challengeResponses.PASSWORD_CLAIM_SECRET_BLOCK = challengeParameters.SECRET_BLOCK;
328 challengeResponses.TIMESTAMP = dateNow;
329 challengeResponses.PASSWORD_CLAIM_SIGNATURE = signatureString;
330
331 if (_this2.deviceKey != null) {
332 challengeResponses.DEVICE_KEY = _this2.deviceKey;
333 }
334
335 var respondToAuthChallenge = function respondToAuthChallenge(challenge, challengeCallback) {
336 return _this2.client.request('RespondToAuthChallenge', challenge, function (errChallenge, dataChallenge) {
337 if (errChallenge && errChallenge.code === 'ResourceNotFoundException' && errChallenge.message.toLowerCase().indexOf('device') !== -1) {
338 challengeResponses.DEVICE_KEY = null;
339 _this2.deviceKey = null;
340 _this2.randomPassword = null;
341 _this2.deviceGroupKey = null;
342
343 _this2.clearCachedDeviceKeyAndPassword();
344
345 return respondToAuthChallenge(challenge, challengeCallback);
346 }
347
348 return challengeCallback(errChallenge, dataChallenge);
349 });
350 };
351
352 var jsonReqResp = {
353 ChallengeName: 'PASSWORD_VERIFIER',
354 ClientId: _this2.pool.getClientId(),
355 ChallengeResponses: challengeResponses,
356 Session: data.Session,
357 ClientMetadata: clientMetaData
358 };
359
360 if (_this2.getUserContextData()) {
361 jsonReqResp.UserContextData = _this2.getUserContextData();
362 }
363
364 respondToAuthChallenge(jsonReqResp, function (errAuthenticate, dataAuthenticate) {
365 if (errAuthenticate) {
366 return callback.onFailure(errAuthenticate);
367 }
368
369 return _this2.authenticateUserInternal(dataAuthenticate, authenticationHelper, callback);
370 });
371 return undefined; // getPasswordAuthenticationKey callback end
372 });
373 return undefined;
374 }); // getLargeAValue callback end
375
376 });
377 }
378 /**
379 * PRIVATE ONLY: This is an internal only method and should not
380 * be directly called by the consumers.
381 * @param {AuthenticationDetails} authDetails Contains the authentication data.
382 * @param {object} callback Result callback map.
383 * @param {onFailure} callback.onFailure Called on any error.
384 * @param {mfaRequired} callback.mfaRequired MFA code
385 * required to continue.
386 * @param {authSuccess} callback.onSuccess Called on success with the new session.
387 * @returns {void}
388 */
389 ;
390
391 _proto.authenticateUserPlainUsernamePassword = function authenticateUserPlainUsernamePassword(authDetails, callback) {
392 var _this3 = this;
393
394 var authParameters = {};
395 authParameters.USERNAME = this.username;
396 authParameters.PASSWORD = authDetails.getPassword();
397
398 if (!authParameters.PASSWORD) {
399 callback.onFailure(new Error('PASSWORD parameter is required'));
400 return;
401 }
402
403 var authenticationHelper = new _AuthenticationHelper["default"](this.pool.getUserPoolId().split('_')[1]);
404 this.getCachedDeviceKeyAndPassword();
405
406 if (this.deviceKey != null) {
407 authParameters.DEVICE_KEY = this.deviceKey;
408 }
409
410 var clientMetaData = Object.keys(authDetails.getValidationData()).length !== 0 ? authDetails.getValidationData() : authDetails.getClientMetadata();
411 var jsonReq = {
412 AuthFlow: 'USER_PASSWORD_AUTH',
413 ClientId: this.pool.getClientId(),
414 AuthParameters: authParameters,
415 ClientMetadata: clientMetaData
416 };
417
418 if (this.getUserContextData(this.username)) {
419 jsonReq.UserContextData = this.getUserContextData(this.username);
420 } // USER_PASSWORD_AUTH happens in a single round-trip: client sends userName and password,
421 // Cognito UserPools verifies password and returns tokens.
422
423
424 this.client.request('InitiateAuth', jsonReq, function (err, authResult) {
425 if (err) {
426 return callback.onFailure(err);
427 }
428
429 return _this3.authenticateUserInternal(authResult, authenticationHelper, callback);
430 });
431 }
432 /**
433 * PRIVATE ONLY: This is an internal only method and should not
434 * be directly called by the consumers.
435 * @param {object} dataAuthenticate authentication data
436 * @param {object} authenticationHelper helper created
437 * @param {callback} callback passed on from caller
438 * @returns {void}
439 */
440 ;
441
442 _proto.authenticateUserInternal = function authenticateUserInternal(dataAuthenticate, authenticationHelper, callback) {
443 var _this4 = this;
444
445 var challengeName = dataAuthenticate.ChallengeName;
446 var challengeParameters = dataAuthenticate.ChallengeParameters;
447
448 if (challengeName === 'SMS_MFA') {
449 this.Session = dataAuthenticate.Session;
450 return callback.mfaRequired(challengeName, challengeParameters);
451 }
452
453 if (challengeName === 'SELECT_MFA_TYPE') {
454 this.Session = dataAuthenticate.Session;
455 return callback.selectMFAType(challengeName, challengeParameters);
456 }
457
458 if (challengeName === 'MFA_SETUP') {
459 this.Session = dataAuthenticate.Session;
460 return callback.mfaSetup(challengeName, challengeParameters);
461 }
462
463 if (challengeName === 'SOFTWARE_TOKEN_MFA') {
464 this.Session = dataAuthenticate.Session;
465 return callback.totpRequired(challengeName, challengeParameters);
466 }
467
468 if (challengeName === 'CUSTOM_CHALLENGE') {
469 this.Session = dataAuthenticate.Session;
470 return callback.customChallenge(challengeParameters);
471 }
472
473 if (challengeName === 'NEW_PASSWORD_REQUIRED') {
474 this.Session = dataAuthenticate.Session;
475 var userAttributes = null;
476 var rawRequiredAttributes = null;
477 var requiredAttributes = [];
478 var userAttributesPrefix = authenticationHelper.getNewPasswordRequiredChallengeUserAttributePrefix();
479
480 if (challengeParameters) {
481 userAttributes = JSON.parse(dataAuthenticate.ChallengeParameters.userAttributes);
482 rawRequiredAttributes = JSON.parse(dataAuthenticate.ChallengeParameters.requiredAttributes);
483 }
484
485 if (rawRequiredAttributes) {
486 for (var i = 0; i < rawRequiredAttributes.length; i++) {
487 requiredAttributes[i] = rawRequiredAttributes[i].substr(userAttributesPrefix.length);
488 }
489 }
490
491 return callback.newPasswordRequired(userAttributes, requiredAttributes);
492 }
493
494 if (challengeName === 'DEVICE_SRP_AUTH') {
495 this.getDeviceResponse(callback);
496 return undefined;
497 }
498
499 this.signInUserSession = this.getCognitoUserSession(dataAuthenticate.AuthenticationResult);
500 this.challengeName = challengeName;
501 this.cacheTokens();
502 var newDeviceMetadata = dataAuthenticate.AuthenticationResult.NewDeviceMetadata;
503
504 if (newDeviceMetadata == null) {
505 return callback.onSuccess(this.signInUserSession);
506 }
507
508 authenticationHelper.generateHashDevice(dataAuthenticate.AuthenticationResult.NewDeviceMetadata.DeviceGroupKey, dataAuthenticate.AuthenticationResult.NewDeviceMetadata.DeviceKey, function (errGenHash) {
509 if (errGenHash) {
510 return callback.onFailure(errGenHash);
511 }
512
513 var deviceSecretVerifierConfig = {
514 Salt: _buffer.Buffer.from(authenticationHelper.getSaltDevices(), 'hex').toString('base64'),
515 PasswordVerifier: _buffer.Buffer.from(authenticationHelper.getVerifierDevices(), 'hex').toString('base64')
516 };
517 _this4.verifierDevices = deviceSecretVerifierConfig.PasswordVerifier;
518 _this4.deviceGroupKey = newDeviceMetadata.DeviceGroupKey;
519 _this4.randomPassword = authenticationHelper.getRandomPassword();
520
521 _this4.client.request('ConfirmDevice', {
522 DeviceKey: newDeviceMetadata.DeviceKey,
523 AccessToken: _this4.signInUserSession.getAccessToken().getJwtToken(),
524 DeviceSecretVerifierConfig: deviceSecretVerifierConfig,
525 DeviceName: userAgent
526 }, function (errConfirm, dataConfirm) {
527 if (errConfirm) {
528 return callback.onFailure(errConfirm);
529 }
530
531 _this4.deviceKey = dataAuthenticate.AuthenticationResult.NewDeviceMetadata.DeviceKey;
532
533 _this4.cacheDeviceKeyAndPassword();
534
535 if (dataConfirm.UserConfirmationNecessary === true) {
536 return callback.onSuccess(_this4.signInUserSession, dataConfirm.UserConfirmationNecessary);
537 }
538
539 return callback.onSuccess(_this4.signInUserSession);
540 });
541
542 return undefined;
543 });
544 return undefined;
545 }
546 /**
547 * This method is user to complete the NEW_PASSWORD_REQUIRED challenge.
548 * Pass the new password with any new user attributes to be updated.
549 * User attribute keys must be of format userAttributes.<attribute_name>.
550 * @param {string} newPassword new password for this user
551 * @param {object} requiredAttributeData map with values for all required attributes
552 * @param {object} callback Result callback map.
553 * @param {onFailure} callback.onFailure Called on any error.
554 * @param {mfaRequired} callback.mfaRequired MFA code required to continue.
555 * @param {customChallenge} callback.customChallenge Custom challenge
556 * response required to continue.
557 * @param {authSuccess} callback.onSuccess Called on success with the new session.
558 * @param {ClientMetadata} clientMetadata object which is passed from client to Cognito Lambda trigger
559 * @returns {void}
560 */
561 ;
562
563 _proto.completeNewPasswordChallenge = function completeNewPasswordChallenge(newPassword, requiredAttributeData, callback, clientMetadata) {
564 var _this5 = this;
565
566 if (!newPassword) {
567 return callback.onFailure(new Error('New password is required.'));
568 }
569
570 var authenticationHelper = new _AuthenticationHelper["default"](this.pool.getUserPoolId().split('_')[1]);
571 var userAttributesPrefix = authenticationHelper.getNewPasswordRequiredChallengeUserAttributePrefix();
572 var finalUserAttributes = {};
573
574 if (requiredAttributeData) {
575 Object.keys(requiredAttributeData).forEach(function (key) {
576 finalUserAttributes[userAttributesPrefix + key] = requiredAttributeData[key];
577 });
578 }
579
580 finalUserAttributes.NEW_PASSWORD = newPassword;
581 finalUserAttributes.USERNAME = this.username;
582 var jsonReq = {
583 ChallengeName: 'NEW_PASSWORD_REQUIRED',
584 ClientId: this.pool.getClientId(),
585 ChallengeResponses: finalUserAttributes,
586 Session: this.Session,
587 ClientMetadata: clientMetadata
588 };
589
590 if (this.getUserContextData()) {
591 jsonReq.UserContextData = this.getUserContextData();
592 }
593
594 this.client.request('RespondToAuthChallenge', jsonReq, function (errAuthenticate, dataAuthenticate) {
595 if (errAuthenticate) {
596 return callback.onFailure(errAuthenticate);
597 }
598
599 return _this5.authenticateUserInternal(dataAuthenticate, authenticationHelper, callback);
600 });
601 return undefined;
602 }
603 /**
604 * This is used to get a session using device authentication. It is called at the end of user
605 * authentication
606 *
607 * @param {object} callback Result callback map.
608 * @param {onFailure} callback.onFailure Called on any error.
609 * @param {authSuccess} callback.onSuccess Called on success with the new session.
610 * @param {ClientMetadata} clientMetadata object which is passed from client to Cognito Lambda trigger
611 * @returns {void}
612 * @private
613 */
614 ;
615
616 _proto.getDeviceResponse = function getDeviceResponse(callback, clientMetadata) {
617 var _this6 = this;
618
619 var authenticationHelper = new _AuthenticationHelper["default"](this.deviceGroupKey);
620 var dateHelper = new _DateHelper["default"]();
621 var authParameters = {};
622 authParameters.USERNAME = this.username;
623 authParameters.DEVICE_KEY = this.deviceKey;
624 authenticationHelper.getLargeAValue(function (errAValue, aValue) {
625 // getLargeAValue callback start
626 if (errAValue) {
627 callback.onFailure(errAValue);
628 }
629
630 authParameters.SRP_A = aValue.toString(16);
631 var jsonReq = {
632 ChallengeName: 'DEVICE_SRP_AUTH',
633 ClientId: _this6.pool.getClientId(),
634 ChallengeResponses: authParameters,
635 ClientMetadata: clientMetadata
636 };
637
638 if (_this6.getUserContextData()) {
639 jsonReq.UserContextData = _this6.getUserContextData();
640 }
641
642 _this6.client.request('RespondToAuthChallenge', jsonReq, function (err, data) {
643 if (err) {
644 return callback.onFailure(err);
645 }
646
647 var challengeParameters = data.ChallengeParameters;
648 var serverBValue = new _BigInteger["default"](challengeParameters.SRP_B, 16);
649 var salt = new _BigInteger["default"](challengeParameters.SALT, 16);
650 authenticationHelper.getPasswordAuthenticationKey(_this6.deviceKey, _this6.randomPassword, serverBValue, salt, function (errHkdf, hkdf) {
651 // getPasswordAuthenticationKey callback start
652 if (errHkdf) {
653 return callback.onFailure(errHkdf);
654 }
655
656 var dateNow = dateHelper.getNowString();
657
658 var message = _core["default"].lib.WordArray.create(_buffer.Buffer.concat([_buffer.Buffer.from(_this6.deviceGroupKey, 'utf8'), _buffer.Buffer.from(_this6.deviceKey, 'utf8'), _buffer.Buffer.from(challengeParameters.SECRET_BLOCK, 'base64'), _buffer.Buffer.from(dateNow, 'utf8')]));
659
660 var key = _core["default"].lib.WordArray.create(hkdf);
661
662 var signatureString = _encBase["default"].stringify((0, _hmacSha["default"])(message, key));
663
664 var challengeResponses = {};
665 challengeResponses.USERNAME = _this6.username;
666 challengeResponses.PASSWORD_CLAIM_SECRET_BLOCK = challengeParameters.SECRET_BLOCK;
667 challengeResponses.TIMESTAMP = dateNow;
668 challengeResponses.PASSWORD_CLAIM_SIGNATURE = signatureString;
669 challengeResponses.DEVICE_KEY = _this6.deviceKey;
670 var jsonReqResp = {
671 ChallengeName: 'DEVICE_PASSWORD_VERIFIER',
672 ClientId: _this6.pool.getClientId(),
673 ChallengeResponses: challengeResponses,
674 Session: data.Session
675 };
676
677 if (_this6.getUserContextData()) {
678 jsonReqResp.UserContextData = _this6.getUserContextData();
679 }
680
681 _this6.client.request('RespondToAuthChallenge', jsonReqResp, function (errAuthenticate, dataAuthenticate) {
682 if (errAuthenticate) {
683 return callback.onFailure(errAuthenticate);
684 }
685
686 _this6.signInUserSession = _this6.getCognitoUserSession(dataAuthenticate.AuthenticationResult);
687
688 _this6.cacheTokens();
689
690 return callback.onSuccess(_this6.signInUserSession);
691 });
692
693 return undefined; // getPasswordAuthenticationKey callback end
694 });
695 return undefined;
696 }); // getLargeAValue callback end
697
698 });
699 }
700 /**
701 * This is used for a certain user to confirm the registration by using a confirmation code
702 * @param {string} confirmationCode Code entered by user.
703 * @param {bool} forceAliasCreation Allow migrating from an existing email / phone number.
704 * @param {nodeCallback<string>} callback Called on success or error.
705 * @param {ClientMetadata} clientMetadata object which is passed from client to Cognito Lambda trigger
706 * @returns {void}
707 */
708 ;
709
710 _proto.confirmRegistration = function confirmRegistration(confirmationCode, forceAliasCreation, callback, clientMetadata) {
711 var jsonReq = {
712 ClientId: this.pool.getClientId(),
713 ConfirmationCode: confirmationCode,
714 Username: this.username,
715 ForceAliasCreation: forceAliasCreation,
716 ClientMetadata: clientMetadata
717 };
718
719 if (this.getUserContextData()) {
720 jsonReq.UserContextData = this.getUserContextData();
721 }
722
723 this.client.request('ConfirmSignUp', jsonReq, function (err) {
724 if (err) {
725 return callback(err, null);
726 }
727
728 return callback(null, 'SUCCESS');
729 });
730 }
731 /**
732 * This is used by the user once he has the responses to a custom challenge
733 * @param {string} answerChallenge The custom challenge answer.
734 * @param {object} callback Result callback map.
735 * @param {onFailure} callback.onFailure Called on any error.
736 * @param {customChallenge} callback.customChallenge
737 * Custom challenge response required to continue.
738 * @param {authSuccess} callback.onSuccess Called on success with the new session.
739 * @param {ClientMetadata} clientMetadata object which is passed from client to Cognito Lambda trigger
740 * @returns {void}
741 */
742 ;
743
744 _proto.sendCustomChallengeAnswer = function sendCustomChallengeAnswer(answerChallenge, callback, clientMetadata) {
745 var _this7 = this;
746
747 var challengeResponses = {};
748 challengeResponses.USERNAME = this.username;
749 challengeResponses.ANSWER = answerChallenge;
750 var authenticationHelper = new _AuthenticationHelper["default"](this.pool.getUserPoolId().split('_')[1]);
751 this.getCachedDeviceKeyAndPassword();
752
753 if (this.deviceKey != null) {
754 challengeResponses.DEVICE_KEY = this.deviceKey;
755 }
756
757 var jsonReq = {
758 ChallengeName: 'CUSTOM_CHALLENGE',
759 ChallengeResponses: challengeResponses,
760 ClientId: this.pool.getClientId(),
761 Session: this.Session,
762 ClientMetadata: clientMetadata
763 };
764
765 if (this.getUserContextData()) {
766 jsonReq.UserContextData = this.getUserContextData();
767 }
768
769 this.client.request('RespondToAuthChallenge', jsonReq, function (err, data) {
770 if (err) {
771 return callback.onFailure(err);
772 }
773
774 return _this7.authenticateUserInternal(data, authenticationHelper, callback);
775 });
776 }
777 /**
778 * This is used by the user once he has an MFA code
779 * @param {string} confirmationCode The MFA code entered by the user.
780 * @param {object} callback Result callback map.
781 * @param {string} mfaType The mfa we are replying to.
782 * @param {onFailure} callback.onFailure Called on any error.
783 * @param {authSuccess} callback.onSuccess Called on success with the new session.
784 * @param {ClientMetadata} clientMetadata object which is passed from client to Cognito Lambda trigger
785 * @returns {void}
786 */
787 ;
788
789 _proto.sendMFACode = function sendMFACode(confirmationCode, callback, mfaType, clientMetadata) {
790 var _this8 = this;
791
792 var challengeResponses = {};
793 challengeResponses.USERNAME = this.username;
794 challengeResponses.SMS_MFA_CODE = confirmationCode;
795 var mfaTypeSelection = mfaType || 'SMS_MFA';
796
797 if (mfaTypeSelection === 'SOFTWARE_TOKEN_MFA') {
798 challengeResponses.SOFTWARE_TOKEN_MFA_CODE = confirmationCode;
799 }
800
801 if (this.deviceKey != null) {
802 challengeResponses.DEVICE_KEY = this.deviceKey;
803 }
804
805 var jsonReq = {
806 ChallengeName: mfaTypeSelection,
807 ChallengeResponses: challengeResponses,
808 ClientId: this.pool.getClientId(),
809 Session: this.Session,
810 ClientMetadata: clientMetadata
811 };
812
813 if (this.getUserContextData()) {
814 jsonReq.UserContextData = this.getUserContextData();
815 }
816
817 this.client.request('RespondToAuthChallenge', jsonReq, function (err, dataAuthenticate) {
818 if (err) {
819 return callback.onFailure(err);
820 }
821
822 var challengeName = dataAuthenticate.ChallengeName;
823
824 if (challengeName === 'DEVICE_SRP_AUTH') {
825 _this8.getDeviceResponse(callback);
826
827 return undefined;
828 }
829
830 _this8.signInUserSession = _this8.getCognitoUserSession(dataAuthenticate.AuthenticationResult);
831
832 _this8.cacheTokens();
833
834 if (dataAuthenticate.AuthenticationResult.NewDeviceMetadata == null) {
835 return callback.onSuccess(_this8.signInUserSession);
836 }
837
838 var authenticationHelper = new _AuthenticationHelper["default"](_this8.pool.getUserPoolId().split('_')[1]);
839 authenticationHelper.generateHashDevice(dataAuthenticate.AuthenticationResult.NewDeviceMetadata.DeviceGroupKey, dataAuthenticate.AuthenticationResult.NewDeviceMetadata.DeviceKey, function (errGenHash) {
840 if (errGenHash) {
841 return callback.onFailure(errGenHash);
842 }
843
844 var deviceSecretVerifierConfig = {
845 Salt: _buffer.Buffer.from(authenticationHelper.getSaltDevices(), 'hex').toString('base64'),
846 PasswordVerifier: _buffer.Buffer.from(authenticationHelper.getVerifierDevices(), 'hex').toString('base64')
847 };
848 _this8.verifierDevices = deviceSecretVerifierConfig.PasswordVerifier;
849 _this8.deviceGroupKey = dataAuthenticate.AuthenticationResult.NewDeviceMetadata.DeviceGroupKey;
850 _this8.randomPassword = authenticationHelper.getRandomPassword();
851
852 _this8.client.request('ConfirmDevice', {
853 DeviceKey: dataAuthenticate.AuthenticationResult.NewDeviceMetadata.DeviceKey,
854 AccessToken: _this8.signInUserSession.getAccessToken().getJwtToken(),
855 DeviceSecretVerifierConfig: deviceSecretVerifierConfig,
856 DeviceName: userAgent
857 }, function (errConfirm, dataConfirm) {
858 if (errConfirm) {
859 return callback.onFailure(errConfirm);
860 }
861
862 _this8.deviceKey = dataAuthenticate.AuthenticationResult.NewDeviceMetadata.DeviceKey;
863
864 _this8.cacheDeviceKeyAndPassword();
865
866 if (dataConfirm.UserConfirmationNecessary === true) {
867 return callback.onSuccess(_this8.signInUserSession, dataConfirm.UserConfirmationNecessary);
868 }
869
870 return callback.onSuccess(_this8.signInUserSession);
871 });
872
873 return undefined;
874 });
875 return undefined;
876 });
877 }
878 /**
879 * This is used by an authenticated user to change the current password
880 * @param {string} oldUserPassword The current password.
881 * @param {string} newUserPassword The requested new password.
882 * @param {nodeCallback<string>} callback Called on success or error.
883 * @param {ClientMetadata} clientMetadata object which is passed from client to Cognito Lambda trigger
884 * @returns {void}
885 */
886 ;
887
888 _proto.changePassword = function changePassword(oldUserPassword, newUserPassword, callback, clientMetadata) {
889 if (!(this.signInUserSession != null && this.signInUserSession.isValid())) {
890 return callback(new Error('User is not authenticated'), null);
891 }
892
893 this.client.request('ChangePassword', {
894 PreviousPassword: oldUserPassword,
895 ProposedPassword: newUserPassword,
896 AccessToken: this.signInUserSession.getAccessToken().getJwtToken(),
897 ClientMetadata: clientMetadata
898 }, function (err) {
899 if (err) {
900 return callback(err, null);
901 }
902
903 return callback(null, 'SUCCESS');
904 });
905 return undefined;
906 }
907 /**
908 * This is used by an authenticated user to enable MFA for itself
909 * @deprecated
910 * @param {nodeCallback<string>} callback Called on success or error.
911 * @returns {void}
912 */
913 ;
914
915 _proto.enableMFA = function enableMFA(callback) {
916 if (this.signInUserSession == null || !this.signInUserSession.isValid()) {
917 return callback(new Error('User is not authenticated'), null);
918 }
919
920 var mfaOptions = [];
921 var mfaEnabled = {
922 DeliveryMedium: 'SMS',
923 AttributeName: 'phone_number'
924 };
925 mfaOptions.push(mfaEnabled);
926 this.client.request('SetUserSettings', {
927 MFAOptions: mfaOptions,
928 AccessToken: this.signInUserSession.getAccessToken().getJwtToken()
929 }, function (err) {
930 if (err) {
931 return callback(err, null);
932 }
933
934 return callback(null, 'SUCCESS');
935 });
936 return undefined;
937 }
938 /**
939 * This is used by an authenticated user to enable MFA for itself
940 * @param {IMfaSettings} smsMfaSettings the sms mfa settings
941 * @param {IMFASettings} softwareTokenMfaSettings the software token mfa settings
942 * @param {nodeCallback<string>} callback Called on success or error.
943 * @returns {void}
944 */
945 ;
946
947 _proto.setUserMfaPreference = function setUserMfaPreference(smsMfaSettings, softwareTokenMfaSettings, callback) {
948 if (this.signInUserSession == null || !this.signInUserSession.isValid()) {
949 return callback(new Error('User is not authenticated'), null);
950 }
951
952 this.client.request('SetUserMFAPreference', {
953 SMSMfaSettings: smsMfaSettings,
954 SoftwareTokenMfaSettings: softwareTokenMfaSettings,
955 AccessToken: this.signInUserSession.getAccessToken().getJwtToken()
956 }, function (err) {
957 if (err) {
958 return callback(err, null);
959 }
960
961 return callback(null, 'SUCCESS');
962 });
963 return undefined;
964 }
965 /**
966 * This is used by an authenticated user to disable MFA for itself
967 * @deprecated
968 * @param {nodeCallback<string>} callback Called on success or error.
969 * @returns {void}
970 */
971 ;
972
973 _proto.disableMFA = function disableMFA(callback) {
974 if (this.signInUserSession == null || !this.signInUserSession.isValid()) {
975 return callback(new Error('User is not authenticated'), null);
976 }
977
978 var mfaOptions = [];
979 this.client.request('SetUserSettings', {
980 MFAOptions: mfaOptions,
981 AccessToken: this.signInUserSession.getAccessToken().getJwtToken()
982 }, function (err) {
983 if (err) {
984 return callback(err, null);
985 }
986
987 return callback(null, 'SUCCESS');
988 });
989 return undefined;
990 }
991 /**
992 * This is used by an authenticated user to delete itself
993 * @param {nodeCallback<string>} callback Called on success or error.
994 * @param {ClientMetadata} clientMetadata object which is passed from client to Cognito Lambda trigger
995 * @returns {void}
996 */
997 ;
998
999 _proto.deleteUser = function deleteUser(callback, clientMetadata) {
1000 var _this9 = this;
1001
1002 if (this.signInUserSession == null || !this.signInUserSession.isValid()) {
1003 return callback(new Error('User is not authenticated'), null);
1004 }
1005
1006 this.client.request('DeleteUser', {
1007 AccessToken: this.signInUserSession.getAccessToken().getJwtToken(),
1008 ClientMetadata: clientMetadata
1009 }, function (err) {
1010 if (err) {
1011 return callback(err, null);
1012 }
1013
1014 _this9.clearCachedUser();
1015
1016 return callback(null, 'SUCCESS');
1017 });
1018 return undefined;
1019 }
1020 /**
1021 * @typedef {CognitoUserAttribute | { Name:string, Value:string }} AttributeArg
1022 */
1023
1024 /**
1025 * This is used by an authenticated user to change a list of attributes
1026 * @param {AttributeArg[]} attributes A list of the new user attributes.
1027 * @param {nodeCallback<string>} callback Called on success or error.
1028 * @param {ClientMetadata} clientMetadata object which is passed from client to Cognito Lambda trigger
1029 * @returns {void}
1030 */
1031 ;
1032
1033 _proto.updateAttributes = function updateAttributes(attributes, callback, clientMetadata) {
1034 var _this10 = this;
1035
1036 if (this.signInUserSession == null || !this.signInUserSession.isValid()) {
1037 return callback(new Error('User is not authenticated'), null);
1038 }
1039
1040 this.client.request('UpdateUserAttributes', {
1041 AccessToken: this.signInUserSession.getAccessToken().getJwtToken(),
1042 UserAttributes: attributes,
1043 ClientMetadata: clientMetadata
1044 }, function (err) {
1045 if (err) {
1046 return callback(err, null);
1047 } // update cached user
1048
1049
1050 return _this10.getUserData(function () {
1051 return callback(null, 'SUCCESS');
1052 }, {
1053 bypassCache: true
1054 });
1055 });
1056 return undefined;
1057 }
1058 /**
1059 * This is used by an authenticated user to get a list of attributes
1060 * @param {nodeCallback<CognitoUserAttribute[]>} callback Called on success or error.
1061 * @returns {void}
1062 */
1063 ;
1064
1065 _proto.getUserAttributes = function getUserAttributes(callback) {
1066 if (!(this.signInUserSession != null && this.signInUserSession.isValid())) {
1067 return callback(new Error('User is not authenticated'), null);
1068 }
1069
1070 this.client.request('GetUser', {
1071 AccessToken: this.signInUserSession.getAccessToken().getJwtToken()
1072 }, function (err, userData) {
1073 if (err) {
1074 return callback(err, null);
1075 }
1076
1077 var attributeList = [];
1078
1079 for (var i = 0; i < userData.UserAttributes.length; i++) {
1080 var attribute = {
1081 Name: userData.UserAttributes[i].Name,
1082 Value: userData.UserAttributes[i].Value
1083 };
1084 var userAttribute = new _CognitoUserAttribute["default"](attribute);
1085 attributeList.push(userAttribute);
1086 }
1087
1088 return callback(null, attributeList);
1089 });
1090 return undefined;
1091 }
1092 /**
1093 * This is used by an authenticated user to get the MFAOptions
1094 * @param {nodeCallback<MFAOptions>} callback Called on success or error.
1095 * @returns {void}
1096 */
1097 ;
1098
1099 _proto.getMFAOptions = function getMFAOptions(callback) {
1100 if (!(this.signInUserSession != null && this.signInUserSession.isValid())) {
1101 return callback(new Error('User is not authenticated'), null);
1102 }
1103
1104 this.client.request('GetUser', {
1105 AccessToken: this.signInUserSession.getAccessToken().getJwtToken()
1106 }, function (err, userData) {
1107 if (err) {
1108 return callback(err, null);
1109 }
1110
1111 return callback(null, userData.MFAOptions);
1112 });
1113 return undefined;
1114 }
1115 /**
1116 * PRIVATE ONLY: This is an internal only method and should not
1117 * be directly called by the consumers.
1118 */
1119 ;
1120
1121 _proto.createGetUserRequest = function createGetUserRequest() {
1122 return this.client.promisifyRequest('GetUser', {
1123 AccessToken: this.signInUserSession.getAccessToken().getJwtToken()
1124 });
1125 }
1126 /**
1127 * PRIVATE ONLY: This is an internal only method and should not
1128 * be directly called by the consumers.
1129 */
1130 ;
1131
1132 _proto.refreshSessionIfPossible = function refreshSessionIfPossible() {
1133 var _this11 = this;
1134
1135 // best effort, if not possible
1136 return new Promise(function (resolve) {
1137 var refresh = _this11.signInUserSession.getRefreshToken();
1138
1139 if (refresh && refresh.getToken()) {
1140 _this11.refreshSession(refresh, resolve);
1141 } else {
1142 resolve();
1143 }
1144 });
1145 }
1146 /**
1147 * This is used by an authenticated users to get the userData
1148 * @param {nodeCallback<UserData>} callback Called on success or error.
1149 * @param {GetUserDataOptions} params
1150 * @returns {void}
1151 */
1152 ;
1153
1154 _proto.getUserData = function getUserData(callback, params) {
1155 var _this12 = this;
1156
1157 if (!(this.signInUserSession != null && this.signInUserSession.isValid())) {
1158 this.clearCachedUserData();
1159 return callback(new Error('User is not authenticated'), null);
1160 }
1161
1162 var userData = this.getUserDataFromCache();
1163
1164 if (!userData) {
1165 this.fetchUserData().then(function (data) {
1166 callback(null, data);
1167 })["catch"](callback);
1168 return;
1169 }
1170
1171 if (this.isFetchUserDataAndTokenRequired(params)) {
1172 this.fetchUserData().then(function (data) {
1173 return _this12.refreshSessionIfPossible().then(function () {
1174 return data;
1175 });
1176 }).then(function (data) {
1177 return callback(null, data);
1178 })["catch"](callback);
1179 return;
1180 }
1181
1182 try {
1183 callback(null, JSON.parse(userData));
1184 return;
1185 } catch (err) {
1186 this.clearCachedUserData();
1187 callback(err, null);
1188 return;
1189 }
1190 }
1191 /**
1192 *
1193 * PRIVATE ONLY: This is an internal only method and should not
1194 * be directly called by the consumers.
1195 */
1196 ;
1197
1198 _proto.getUserDataFromCache = function getUserDataFromCache() {
1199 var userData = this.storage.getItem(this.userDataKey);
1200 return userData;
1201 }
1202 /**
1203 *
1204 * PRIVATE ONLY: This is an internal only method and should not
1205 * be directly called by the consumers.
1206 */
1207 ;
1208
1209 _proto.isFetchUserDataAndTokenRequired = function isFetchUserDataAndTokenRequired(params) {
1210 var _ref = params || {},
1211 _ref$bypassCache = _ref.bypassCache,
1212 bypassCache = _ref$bypassCache === void 0 ? false : _ref$bypassCache;
1213
1214 return bypassCache;
1215 }
1216 /**
1217 *
1218 * PRIVATE ONLY: This is an internal only method and should not
1219 * be directly called by the consumers.
1220 */
1221 ;
1222
1223 _proto.fetchUserData = function fetchUserData() {
1224 var _this13 = this;
1225
1226 return this.createGetUserRequest().then(function (data) {
1227 _this13.cacheUserData(data);
1228
1229 return data;
1230 });
1231 }
1232 /**
1233 * This is used by an authenticated user to delete a list of attributes
1234 * @param {string[]} attributeList Names of the attributes to delete.
1235 * @param {nodeCallback<string>} callback Called on success or error.
1236 * @returns {void}
1237 */
1238 ;
1239
1240 _proto.deleteAttributes = function deleteAttributes(attributeList, callback) {
1241 if (!(this.signInUserSession != null && this.signInUserSession.isValid())) {
1242 return callback(new Error('User is not authenticated'), null);
1243 }
1244
1245 this.client.request('DeleteUserAttributes', {
1246 UserAttributeNames: attributeList,
1247 AccessToken: this.signInUserSession.getAccessToken().getJwtToken()
1248 }, function (err) {
1249 if (err) {
1250 return callback(err, null);
1251 }
1252
1253 return callback(null, 'SUCCESS');
1254 });
1255 return undefined;
1256 }
1257 /**
1258 * This is used by a user to resend a confirmation code
1259 * @param {nodeCallback<string>} callback Called on success or error.
1260 * @param {ClientMetadata} clientMetadata object which is passed from client to Cognito Lambda trigger
1261 * @returns {void}
1262 */
1263 ;
1264
1265 _proto.resendConfirmationCode = function resendConfirmationCode(callback, clientMetadata) {
1266 var jsonReq = {
1267 ClientId: this.pool.getClientId(),
1268 Username: this.username,
1269 ClientMetadata: clientMetadata
1270 };
1271 this.client.request('ResendConfirmationCode', jsonReq, function (err, result) {
1272 if (err) {
1273 return callback(err, null);
1274 }
1275
1276 return callback(null, result);
1277 });
1278 }
1279 /**
1280 * This is used to get a session, either from the session object
1281 * or from the local storage, or by using a refresh token
1282 *
1283 * @param {nodeCallback<CognitoUserSession>} callback Called on success or error.
1284 * @returns {void}
1285 */
1286 ;
1287
1288 _proto.getSession = function getSession(callback) {
1289 if (this.username == null) {
1290 return callback(new Error('Username is null. Cannot retrieve a new session'), null);
1291 }
1292
1293 if (this.signInUserSession != null && this.signInUserSession.isValid()) {
1294 return callback(null, this.signInUserSession);
1295 }
1296
1297 var keyPrefix = "CognitoIdentityServiceProvider." + this.pool.getClientId() + "." + this.username;
1298 var idTokenKey = keyPrefix + ".idToken";
1299 var accessTokenKey = keyPrefix + ".accessToken";
1300 var refreshTokenKey = keyPrefix + ".refreshToken";
1301 var clockDriftKey = keyPrefix + ".clockDrift";
1302
1303 if (this.storage.getItem(idTokenKey)) {
1304 var idToken = new _CognitoIdToken["default"]({
1305 IdToken: this.storage.getItem(idTokenKey)
1306 });
1307 var accessToken = new _CognitoAccessToken["default"]({
1308 AccessToken: this.storage.getItem(accessTokenKey)
1309 });
1310 var refreshToken = new _CognitoRefreshToken["default"]({
1311 RefreshToken: this.storage.getItem(refreshTokenKey)
1312 });
1313 var clockDrift = parseInt(this.storage.getItem(clockDriftKey), 0) || 0;
1314 var sessionData = {
1315 IdToken: idToken,
1316 AccessToken: accessToken,
1317 RefreshToken: refreshToken,
1318 ClockDrift: clockDrift
1319 };
1320 var cachedSession = new _CognitoUserSession["default"](sessionData);
1321
1322 if (cachedSession.isValid()) {
1323 this.signInUserSession = cachedSession;
1324 return callback(null, this.signInUserSession);
1325 }
1326
1327 if (!refreshToken.getToken()) {
1328 return callback(new Error('Cannot retrieve a new session. Please authenticate.'), null);
1329 }
1330
1331 this.refreshSession(refreshToken, callback);
1332 } else {
1333 callback(new Error('Local storage is missing an ID Token, Please authenticate'), null);
1334 }
1335
1336 return undefined;
1337 }
1338 /**
1339 * This uses the refreshToken to retrieve a new session
1340 * @param {CognitoRefreshToken} refreshToken A previous session's refresh token.
1341 * @param {nodeCallback<CognitoUserSession>} callback Called on success or error.
1342 * @param {ClientMetadata} clientMetadata object which is passed from client to Cognito Lambda trigger
1343 * @returns {void}
1344 */
1345 ;
1346
1347 _proto.refreshSession = function refreshSession(refreshToken, callback, clientMetadata) {
1348 var _this14 = this;
1349
1350 var authParameters = {};
1351 authParameters.REFRESH_TOKEN = refreshToken.getToken();
1352 var keyPrefix = "CognitoIdentityServiceProvider." + this.pool.getClientId();
1353 var lastUserKey = keyPrefix + ".LastAuthUser";
1354
1355 if (this.storage.getItem(lastUserKey)) {
1356 this.username = this.storage.getItem(lastUserKey);
1357 var deviceKeyKey = keyPrefix + "." + this.username + ".deviceKey";
1358 this.deviceKey = this.storage.getItem(deviceKeyKey);
1359 authParameters.DEVICE_KEY = this.deviceKey;
1360 }
1361
1362 var jsonReq = {
1363 ClientId: this.pool.getClientId(),
1364 AuthFlow: 'REFRESH_TOKEN_AUTH',
1365 AuthParameters: authParameters,
1366 ClientMetadata: clientMetadata
1367 };
1368
1369 if (this.getUserContextData()) {
1370 jsonReq.UserContextData = this.getUserContextData();
1371 }
1372
1373 this.client.request('InitiateAuth', jsonReq, function (err, authResult) {
1374 if (err) {
1375 if (err.code === 'NotAuthorizedException') {
1376 _this14.clearCachedUser();
1377 }
1378
1379 return callback(err, null);
1380 }
1381
1382 if (authResult) {
1383 var authenticationResult = authResult.AuthenticationResult;
1384
1385 if (!Object.prototype.hasOwnProperty.call(authenticationResult, 'RefreshToken')) {
1386 authenticationResult.RefreshToken = refreshToken.getToken();
1387 }
1388
1389 _this14.signInUserSession = _this14.getCognitoUserSession(authenticationResult);
1390
1391 _this14.cacheTokens();
1392
1393 return callback(null, _this14.signInUserSession);
1394 }
1395
1396 return undefined;
1397 });
1398 }
1399 /**
1400 * This is used to save the session tokens to local storage
1401 * @returns {void}
1402 */
1403 ;
1404
1405 _proto.cacheTokens = function cacheTokens() {
1406 var keyPrefix = "CognitoIdentityServiceProvider." + this.pool.getClientId();
1407 var idTokenKey = keyPrefix + "." + this.username + ".idToken";
1408 var accessTokenKey = keyPrefix + "." + this.username + ".accessToken";
1409 var refreshTokenKey = keyPrefix + "." + this.username + ".refreshToken";
1410 var clockDriftKey = keyPrefix + "." + this.username + ".clockDrift";
1411 var lastUserKey = keyPrefix + ".LastAuthUser";
1412 this.storage.setItem(idTokenKey, this.signInUserSession.getIdToken().getJwtToken());
1413 this.storage.setItem(accessTokenKey, this.signInUserSession.getAccessToken().getJwtToken());
1414 this.storage.setItem(refreshTokenKey, this.signInUserSession.getRefreshToken().getToken());
1415 this.storage.setItem(clockDriftKey, "" + this.signInUserSession.getClockDrift());
1416 this.storage.setItem(lastUserKey, this.username);
1417 }
1418 /**
1419 * This is to cache user data
1420 */
1421 ;
1422
1423 _proto.cacheUserData = function cacheUserData(userData) {
1424 this.storage.setItem(this.userDataKey, JSON.stringify(userData));
1425 }
1426 /**
1427 * This is to remove cached user data
1428 */
1429 ;
1430
1431 _proto.clearCachedUserData = function clearCachedUserData() {
1432 this.storage.removeItem(this.userDataKey);
1433 };
1434
1435 _proto.clearCachedUser = function clearCachedUser() {
1436 this.clearCachedTokens();
1437 this.clearCachedUserData();
1438 }
1439 /**
1440 * This is used to cache the device key and device group and device password
1441 * @returns {void}
1442 */
1443 ;
1444
1445 _proto.cacheDeviceKeyAndPassword = function cacheDeviceKeyAndPassword() {
1446 var keyPrefix = "CognitoIdentityServiceProvider." + this.pool.getClientId() + "." + this.username;
1447 var deviceKeyKey = keyPrefix + ".deviceKey";
1448 var randomPasswordKey = keyPrefix + ".randomPasswordKey";
1449 var deviceGroupKeyKey = keyPrefix + ".deviceGroupKey";
1450 this.storage.setItem(deviceKeyKey, this.deviceKey);
1451 this.storage.setItem(randomPasswordKey, this.randomPassword);
1452 this.storage.setItem(deviceGroupKeyKey, this.deviceGroupKey);
1453 }
1454 /**
1455 * This is used to get current device key and device group and device password
1456 * @returns {void}
1457 */
1458 ;
1459
1460 _proto.getCachedDeviceKeyAndPassword = function getCachedDeviceKeyAndPassword() {
1461 var keyPrefix = "CognitoIdentityServiceProvider." + this.pool.getClientId() + "." + this.username;
1462 var deviceKeyKey = keyPrefix + ".deviceKey";
1463 var randomPasswordKey = keyPrefix + ".randomPasswordKey";
1464 var deviceGroupKeyKey = keyPrefix + ".deviceGroupKey";
1465
1466 if (this.storage.getItem(deviceKeyKey)) {
1467 this.deviceKey = this.storage.getItem(deviceKeyKey);
1468 this.randomPassword = this.storage.getItem(randomPasswordKey);
1469 this.deviceGroupKey = this.storage.getItem(deviceGroupKeyKey);
1470 }
1471 }
1472 /**
1473 * This is used to clear the device key info from local storage
1474 * @returns {void}
1475 */
1476 ;
1477
1478 _proto.clearCachedDeviceKeyAndPassword = function clearCachedDeviceKeyAndPassword() {
1479 var keyPrefix = "CognitoIdentityServiceProvider." + this.pool.getClientId() + "." + this.username;
1480 var deviceKeyKey = keyPrefix + ".deviceKey";
1481 var randomPasswordKey = keyPrefix + ".randomPasswordKey";
1482 var deviceGroupKeyKey = keyPrefix + ".deviceGroupKey";
1483 this.storage.removeItem(deviceKeyKey);
1484 this.storage.removeItem(randomPasswordKey);
1485 this.storage.removeItem(deviceGroupKeyKey);
1486 }
1487 /**
1488 * This is used to clear the session tokens from local storage
1489 * @returns {void}
1490 */
1491 ;
1492
1493 _proto.clearCachedTokens = function clearCachedTokens() {
1494 var keyPrefix = "CognitoIdentityServiceProvider." + this.pool.getClientId();
1495 var idTokenKey = keyPrefix + "." + this.username + ".idToken";
1496 var accessTokenKey = keyPrefix + "." + this.username + ".accessToken";
1497 var refreshTokenKey = keyPrefix + "." + this.username + ".refreshToken";
1498 var lastUserKey = keyPrefix + ".LastAuthUser";
1499 var clockDriftKey = keyPrefix + "." + this.username + ".clockDrift";
1500 this.storage.removeItem(idTokenKey);
1501 this.storage.removeItem(accessTokenKey);
1502 this.storage.removeItem(refreshTokenKey);
1503 this.storage.removeItem(lastUserKey);
1504 this.storage.removeItem(clockDriftKey);
1505 }
1506 /**
1507 * This is used to build a user session from tokens retrieved in the authentication result
1508 * @param {object} authResult Successful auth response from server.
1509 * @returns {CognitoUserSession} The new user session.
1510 * @private
1511 */
1512 ;
1513
1514 _proto.getCognitoUserSession = function getCognitoUserSession(authResult) {
1515 var idToken = new _CognitoIdToken["default"](authResult);
1516 var accessToken = new _CognitoAccessToken["default"](authResult);
1517 var refreshToken = new _CognitoRefreshToken["default"](authResult);
1518 var sessionData = {
1519 IdToken: idToken,
1520 AccessToken: accessToken,
1521 RefreshToken: refreshToken
1522 };
1523 return new _CognitoUserSession["default"](sessionData);
1524 }
1525 /**
1526 * This is used to initiate a forgot password request
1527 * @param {object} callback Result callback map.
1528 * @param {onFailure} callback.onFailure Called on any error.
1529 * @param {inputVerificationCode?} callback.inputVerificationCode
1530 * Optional callback raised instead of onSuccess with response data.
1531 * @param {onSuccess} callback.onSuccess Called on success.
1532 * @param {ClientMetadata} clientMetadata object which is passed from client to Cognito Lambda trigger
1533 * @returns {void}
1534 */
1535 ;
1536
1537 _proto.forgotPassword = function forgotPassword(callback, clientMetadata) {
1538 var jsonReq = {
1539 ClientId: this.pool.getClientId(),
1540 Username: this.username,
1541 ClientMetadata: clientMetadata
1542 };
1543
1544 if (this.getUserContextData()) {
1545 jsonReq.UserContextData = this.getUserContextData();
1546 }
1547
1548 this.client.request('ForgotPassword', jsonReq, function (err, data) {
1549 if (err) {
1550 return callback.onFailure(err);
1551 }
1552
1553 if (typeof callback.inputVerificationCode === 'function') {
1554 return callback.inputVerificationCode(data);
1555 }
1556
1557 return callback.onSuccess(data);
1558 });
1559 }
1560 /**
1561 * This is used to confirm a new password using a confirmationCode
1562 * @param {string} confirmationCode Code entered by user.
1563 * @param {string} newPassword Confirm new password.
1564 * @param {object} callback Result callback map.
1565 * @param {onFailure} callback.onFailure Called on any error.
1566 * @param {onSuccess<void>} callback.onSuccess Called on success.
1567 * @param {ClientMetadata} clientMetadata object which is passed from client to Cognito Lambda trigger
1568 * @returns {void}
1569 */
1570 ;
1571
1572 _proto.confirmPassword = function confirmPassword(confirmationCode, newPassword, callback, clientMetadata) {
1573 var jsonReq = {
1574 ClientId: this.pool.getClientId(),
1575 Username: this.username,
1576 ConfirmationCode: confirmationCode,
1577 Password: newPassword,
1578 ClientMetadata: clientMetadata
1579 };
1580
1581 if (this.getUserContextData()) {
1582 jsonReq.UserContextData = this.getUserContextData();
1583 }
1584
1585 this.client.request('ConfirmForgotPassword', jsonReq, function (err) {
1586 if (err) {
1587 return callback.onFailure(err);
1588 }
1589
1590 return callback.onSuccess();
1591 });
1592 }
1593 /**
1594 * This is used to initiate an attribute confirmation request
1595 * @param {string} attributeName User attribute that needs confirmation.
1596 * @param {object} callback Result callback map.
1597 * @param {onFailure} callback.onFailure Called on any error.
1598 * @param {inputVerificationCode} callback.inputVerificationCode Called on success.
1599 * @param {ClientMetadata} clientMetadata object which is passed from client to Cognito Lambda trigger
1600 * @returns {void}
1601 */
1602 ;
1603
1604 _proto.getAttributeVerificationCode = function getAttributeVerificationCode(attributeName, callback, clientMetadata) {
1605 if (this.signInUserSession == null || !this.signInUserSession.isValid()) {
1606 return callback.onFailure(new Error('User is not authenticated'));
1607 }
1608
1609 this.client.request('GetUserAttributeVerificationCode', {
1610 AttributeName: attributeName,
1611 AccessToken: this.signInUserSession.getAccessToken().getJwtToken(),
1612 ClientMetadata: clientMetadata
1613 }, function (err, data) {
1614 if (err) {
1615 return callback.onFailure(err);
1616 }
1617
1618 if (typeof callback.inputVerificationCode === 'function') {
1619 return callback.inputVerificationCode(data);
1620 }
1621
1622 return callback.onSuccess();
1623 });
1624 return undefined;
1625 }
1626 /**
1627 * This is used to confirm an attribute using a confirmation code
1628 * @param {string} attributeName Attribute being confirmed.
1629 * @param {string} confirmationCode Code entered by user.
1630 * @param {object} callback Result callback map.
1631 * @param {onFailure} callback.onFailure Called on any error.
1632 * @param {onSuccess<string>} callback.onSuccess Called on success.
1633 * @returns {void}
1634 */
1635 ;
1636
1637 _proto.verifyAttribute = function verifyAttribute(attributeName, confirmationCode, callback) {
1638 if (this.signInUserSession == null || !this.signInUserSession.isValid()) {
1639 return callback.onFailure(new Error('User is not authenticated'));
1640 }
1641
1642 this.client.request('VerifyUserAttribute', {
1643 AttributeName: attributeName,
1644 Code: confirmationCode,
1645 AccessToken: this.signInUserSession.getAccessToken().getJwtToken()
1646 }, function (err) {
1647 if (err) {
1648 return callback.onFailure(err);
1649 }
1650
1651 return callback.onSuccess('SUCCESS');
1652 });
1653 return undefined;
1654 }
1655 /**
1656 * This is used to get the device information using the current device key
1657 * @param {object} callback Result callback map.
1658 * @param {onFailure} callback.onFailure Called on any error.
1659 * @param {onSuccess<*>} callback.onSuccess Called on success with device data.
1660 * @returns {void}
1661 */
1662 ;
1663
1664 _proto.getDevice = function getDevice(callback) {
1665 if (this.signInUserSession == null || !this.signInUserSession.isValid()) {
1666 return callback.onFailure(new Error('User is not authenticated'));
1667 }
1668
1669 this.client.request('GetDevice', {
1670 AccessToken: this.signInUserSession.getAccessToken().getJwtToken(),
1671 DeviceKey: this.deviceKey
1672 }, function (err, data) {
1673 if (err) {
1674 return callback.onFailure(err);
1675 }
1676
1677 return callback.onSuccess(data);
1678 });
1679 return undefined;
1680 }
1681 /**
1682 * This is used to forget a specific device
1683 * @param {string} deviceKey Device key.
1684 * @param {object} callback Result callback map.
1685 * @param {onFailure} callback.onFailure Called on any error.
1686 * @param {onSuccess<string>} callback.onSuccess Called on success.
1687 * @returns {void}
1688 */
1689 ;
1690
1691 _proto.forgetSpecificDevice = function forgetSpecificDevice(deviceKey, callback) {
1692 if (this.signInUserSession == null || !this.signInUserSession.isValid()) {
1693 return callback.onFailure(new Error('User is not authenticated'));
1694 }
1695
1696 this.client.request('ForgetDevice', {
1697 AccessToken: this.signInUserSession.getAccessToken().getJwtToken(),
1698 DeviceKey: deviceKey
1699 }, function (err) {
1700 if (err) {
1701 return callback.onFailure(err);
1702 }
1703
1704 return callback.onSuccess('SUCCESS');
1705 });
1706 return undefined;
1707 }
1708 /**
1709 * This is used to forget the current device
1710 * @param {object} callback Result callback map.
1711 * @param {onFailure} callback.onFailure Called on any error.
1712 * @param {onSuccess<string>} callback.onSuccess Called on success.
1713 * @returns {void}
1714 */
1715 ;
1716
1717 _proto.forgetDevice = function forgetDevice(callback) {
1718 var _this15 = this;
1719
1720 this.forgetSpecificDevice(this.deviceKey, {
1721 onFailure: callback.onFailure,
1722 onSuccess: function onSuccess(result) {
1723 _this15.deviceKey = null;
1724 _this15.deviceGroupKey = null;
1725 _this15.randomPassword = null;
1726
1727 _this15.clearCachedDeviceKeyAndPassword();
1728
1729 return callback.onSuccess(result);
1730 }
1731 });
1732 }
1733 /**
1734 * This is used to set the device status as remembered
1735 * @param {object} callback Result callback map.
1736 * @param {onFailure} callback.onFailure Called on any error.
1737 * @param {onSuccess<string>} callback.onSuccess Called on success.
1738 * @returns {void}
1739 */
1740 ;
1741
1742 _proto.setDeviceStatusRemembered = function setDeviceStatusRemembered(callback) {
1743 if (this.signInUserSession == null || !this.signInUserSession.isValid()) {
1744 return callback.onFailure(new Error('User is not authenticated'));
1745 }
1746
1747 this.client.request('UpdateDeviceStatus', {
1748 AccessToken: this.signInUserSession.getAccessToken().getJwtToken(),
1749 DeviceKey: this.deviceKey,
1750 DeviceRememberedStatus: 'remembered'
1751 }, function (err) {
1752 if (err) {
1753 return callback.onFailure(err);
1754 }
1755
1756 return callback.onSuccess('SUCCESS');
1757 });
1758 return undefined;
1759 }
1760 /**
1761 * This is used to set the device status as not remembered
1762 * @param {object} callback Result callback map.
1763 * @param {onFailure} callback.onFailure Called on any error.
1764 * @param {onSuccess<string>} callback.onSuccess Called on success.
1765 * @returns {void}
1766 */
1767 ;
1768
1769 _proto.setDeviceStatusNotRemembered = function setDeviceStatusNotRemembered(callback) {
1770 if (this.signInUserSession == null || !this.signInUserSession.isValid()) {
1771 return callback.onFailure(new Error('User is not authenticated'));
1772 }
1773
1774 this.client.request('UpdateDeviceStatus', {
1775 AccessToken: this.signInUserSession.getAccessToken().getJwtToken(),
1776 DeviceKey: this.deviceKey,
1777 DeviceRememberedStatus: 'not_remembered'
1778 }, function (err) {
1779 if (err) {
1780 return callback.onFailure(err);
1781 }
1782
1783 return callback.onSuccess('SUCCESS');
1784 });
1785 return undefined;
1786 }
1787 /**
1788 * This is used to list all devices for a user
1789 *
1790 * @param {int} limit the number of devices returned in a call
1791 * @param {string | null} paginationToken the pagination token in case any was returned before
1792 * @param {object} callback Result callback map.
1793 * @param {onFailure} callback.onFailure Called on any error.
1794 * @param {onSuccess<*>} callback.onSuccess Called on success with device list.
1795 * @returns {void}
1796 */
1797 ;
1798
1799 _proto.listDevices = function listDevices(limit, paginationToken, callback) {
1800 if (this.signInUserSession == null || !this.signInUserSession.isValid()) {
1801 return callback.onFailure(new Error('User is not authenticated'));
1802 }
1803
1804 var requestParams = {
1805 AccessToken: this.signInUserSession.getAccessToken().getJwtToken(),
1806 Limit: limit
1807 };
1808
1809 if (paginationToken) {
1810 requestParams.PaginationToken = paginationToken;
1811 }
1812
1813 this.client.request('ListDevices', requestParams, function (err, data) {
1814 if (err) {
1815 return callback.onFailure(err);
1816 }
1817
1818 return callback.onSuccess(data);
1819 });
1820 return undefined;
1821 }
1822 /**
1823 * This is used to globally revoke all tokens issued to a user
1824 * @param {object} callback Result callback map.
1825 * @param {onFailure} callback.onFailure Called on any error.
1826 * @param {onSuccess<string>} callback.onSuccess Called on success.
1827 * @returns {void}
1828 */
1829 ;
1830
1831 _proto.globalSignOut = function globalSignOut(callback) {
1832 var _this16 = this;
1833
1834 if (this.signInUserSession == null || !this.signInUserSession.isValid()) {
1835 return callback.onFailure(new Error('User is not authenticated'));
1836 }
1837
1838 this.client.request('GlobalSignOut', {
1839 AccessToken: this.signInUserSession.getAccessToken().getJwtToken()
1840 }, function (err) {
1841 if (err) {
1842 return callback.onFailure(err);
1843 }
1844
1845 _this16.clearCachedUser();
1846
1847 return callback.onSuccess('SUCCESS');
1848 });
1849 return undefined;
1850 }
1851 /**
1852 * This is used for the user to signOut of the application and clear the cached tokens.
1853 * @returns {void}
1854 */
1855 ;
1856
1857 _proto.signOut = function signOut() {
1858 this.signInUserSession = null;
1859 this.clearCachedUser();
1860 }
1861 /**
1862 * This is used by a user trying to select a given MFA
1863 * @param {string} answerChallenge the mfa the user wants
1864 * @param {nodeCallback<string>} callback Called on success or error.
1865 * @returns {void}
1866 */
1867 ;
1868
1869 _proto.sendMFASelectionAnswer = function sendMFASelectionAnswer(answerChallenge, callback) {
1870 var _this17 = this;
1871
1872 var challengeResponses = {};
1873 challengeResponses.USERNAME = this.username;
1874 challengeResponses.ANSWER = answerChallenge;
1875 var jsonReq = {
1876 ChallengeName: 'SELECT_MFA_TYPE',
1877 ChallengeResponses: challengeResponses,
1878 ClientId: this.pool.getClientId(),
1879 Session: this.Session
1880 };
1881
1882 if (this.getUserContextData()) {
1883 jsonReq.UserContextData = this.getUserContextData();
1884 }
1885
1886 this.client.request('RespondToAuthChallenge', jsonReq, function (err, data) {
1887 if (err) {
1888 return callback.onFailure(err);
1889 }
1890
1891 _this17.Session = data.Session;
1892
1893 if (answerChallenge === 'SMS_MFA') {
1894 return callback.mfaRequired(data.ChallengeName, data.ChallengeParameters);
1895 }
1896
1897 if (answerChallenge === 'SOFTWARE_TOKEN_MFA') {
1898 return callback.totpRequired(data.ChallengeName, data.ChallengeParameters);
1899 }
1900
1901 return undefined;
1902 });
1903 }
1904 /**
1905 * This returns the user context data for advanced security feature.
1906 * @returns {void}
1907 */
1908 ;
1909
1910 _proto.getUserContextData = function getUserContextData() {
1911 var pool = this.pool;
1912 return pool.getUserContextData(this.username);
1913 }
1914 /**
1915 * This is used by an authenticated or a user trying to authenticate to associate a TOTP MFA
1916 * @param {nodeCallback<string>} callback Called on success or error.
1917 * @returns {void}
1918 */
1919 ;
1920
1921 _proto.associateSoftwareToken = function associateSoftwareToken(callback) {
1922 var _this18 = this;
1923
1924 if (!(this.signInUserSession != null && this.signInUserSession.isValid())) {
1925 this.client.request('AssociateSoftwareToken', {
1926 Session: this.Session
1927 }, function (err, data) {
1928 if (err) {
1929 return callback.onFailure(err);
1930 }
1931
1932 _this18.Session = data.Session;
1933 return callback.associateSecretCode(data.SecretCode);
1934 });
1935 } else {
1936 this.client.request('AssociateSoftwareToken', {
1937 AccessToken: this.signInUserSession.getAccessToken().getJwtToken()
1938 }, function (err, data) {
1939 if (err) {
1940 return callback.onFailure(err);
1941 }
1942
1943 return callback.associateSecretCode(data.SecretCode);
1944 });
1945 }
1946 }
1947 /**
1948 * This is used by an authenticated or a user trying to authenticate to verify a TOTP MFA
1949 * @param {string} totpCode The MFA code entered by the user.
1950 * @param {string} friendlyDeviceName The device name we are assigning to the device.
1951 * @param {nodeCallback<string>} callback Called on success or error.
1952 * @returns {void}
1953 */
1954 ;
1955
1956 _proto.verifySoftwareToken = function verifySoftwareToken(totpCode, friendlyDeviceName, callback) {
1957 var _this19 = this;
1958
1959 if (!(this.signInUserSession != null && this.signInUserSession.isValid())) {
1960 this.client.request('VerifySoftwareToken', {
1961 Session: this.Session,
1962 UserCode: totpCode,
1963 FriendlyDeviceName: friendlyDeviceName
1964 }, function (err, data) {
1965 if (err) {
1966 return callback.onFailure(err);
1967 }
1968
1969 _this19.Session = data.Session;
1970 var challengeResponses = {};
1971 challengeResponses.USERNAME = _this19.username;
1972 var jsonReq = {
1973 ChallengeName: 'MFA_SETUP',
1974 ClientId: _this19.pool.getClientId(),
1975 ChallengeResponses: challengeResponses,
1976 Session: _this19.Session
1977 };
1978
1979 if (_this19.getUserContextData()) {
1980 jsonReq.UserContextData = _this19.getUserContextData();
1981 }
1982
1983 _this19.client.request('RespondToAuthChallenge', jsonReq, function (errRespond, dataRespond) {
1984 if (errRespond) {
1985 return callback.onFailure(errRespond);
1986 }
1987
1988 _this19.signInUserSession = _this19.getCognitoUserSession(dataRespond.AuthenticationResult);
1989
1990 _this19.cacheTokens();
1991
1992 return callback.onSuccess(_this19.signInUserSession);
1993 });
1994
1995 return undefined;
1996 });
1997 } else {
1998 this.client.request('VerifySoftwareToken', {
1999 AccessToken: this.signInUserSession.getAccessToken().getJwtToken(),
2000 UserCode: totpCode,
2001 FriendlyDeviceName: friendlyDeviceName
2002 }, function (err, data) {
2003 if (err) {
2004 return callback.onFailure(err);
2005 }
2006
2007 return callback.onSuccess(data);
2008 });
2009 }
2010 };
2011
2012 return CognitoUser;
2013}();
2014
2015exports["default"] = CognitoUser;
\No newline at end of file