UNPKG

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