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