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

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