UNPKG

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