diff --git a/packages/amazon-cognito-identity-js/__tests__/internalsIndex.test.js b/packages/amazon-cognito-identity-js/__tests__/internalsIndex.test.js deleted file mode 100644 index 12b4ffa9676..00000000000 --- a/packages/amazon-cognito-identity-js/__tests__/internalsIndex.test.js +++ /dev/null @@ -1,13 +0,0 @@ -import * as exported from '../src/internals/index'; - -describe('import * keys', () => { - it('should match snapshot', () => { - expect(Object.keys(exported)).toMatchInlineSnapshot(` - Array [ - "addAuthCategoryToCognitoUserAgent", - "addFrameworkToCognitoUserAgent", - "InternalCognitoUser", - ] - `); - }); -}); diff --git a/packages/amazon-cognito-identity-js/index.d.ts b/packages/amazon-cognito-identity-js/index.d.ts index 2c526568121..ca8dfaf330e 100644 --- a/packages/amazon-cognito-identity-js/index.d.ts +++ b/packages/amazon-cognito-identity-js/index.d.ts @@ -1,4 +1,4 @@ -import { InternalCognitoUser } from './internals'; +import { InternalCognitoUser, InternalCognitoUserPool } from './internals'; declare module 'amazon-cognito-identity-js' { //import * as AWS from "aws-sdk"; @@ -320,18 +320,7 @@ declare module 'amazon-cognito-identity-js' { AdvancedSecurityDataCollectionFlag?: boolean; } - export class CognitoUserPool { - constructor( - data: ICognitoUserPoolData, - wrapRefreshSessionCallback?: ( - target: NodeCallback.Any - ) => NodeCallback.Any - ); - - public getUserPoolId(): string; - public getUserPoolName(): string; - public getClientId(): string; - + export class CognitoUserPool extends InternalCognitoUserPool { public signUp( username: string, password: string, @@ -340,8 +329,6 @@ declare module 'amazon-cognito-identity-js' { callback: NodeCallback, clientMetadata?: ClientMetadata ): void; - - public getCurrentUser(): CognitoUser | null; } export interface ICognitoUserSessionData { diff --git a/packages/amazon-cognito-identity-js/internals/index.d.ts b/packages/amazon-cognito-identity-js/internals/index.d.ts index f1160c9563d..5bb20d17a63 100644 --- a/packages/amazon-cognito-identity-js/internals/index.d.ts +++ b/packages/amazon-cognito-identity-js/internals/index.d.ts @@ -1,24 +1,50 @@ import { - NodeCallback, - UpdateAttributesNodeCallback, - ClientMetadata, - IAuthenticationCallback, - IMfaSettings, AuthenticationDetails, - ICognitoUserData, - GetSessionOptions, ChallengeName, - CognitoUserSession, + ClientMetadata, CognitoRefreshToken, + CognitoUser, CognitoUserAttribute, + CognitoUserSession, + GetSessionOptions, + IAuthenticationCallback, ICognitoUserAttributeData, + ICognitoUserData, + ICognitoUserPoolData, + IMfaSettings, + ISignUpResult, MFAOption, + NodeCallback, + UpdateAttributesNodeCallback, UserData, } from 'amazon-cognito-identity-js'; export const addAuthCategoryToCognitoUserAgent: () => void; export const addFrameworkToCognitoUserAgent: (content: string) => void; +export class InternalCognitoUserPool { + constructor( + data: ICognitoUserPoolData, + wrapRefreshSessionCallback?: (target: NodeCallback.Any) => NodeCallback.Any + ); + + public getUserPoolId(): string; + public getUserPoolName(): string; + public getClientId(): string; + + public signUp( + username: string, + password: string, + userAttributes: CognitoUserAttribute[], + validationData: CognitoUserAttribute[], + callback: NodeCallback, + clientMetadata?: ClientMetadata, + userAgentValue?: string + ): void; + + public getCurrentUser(): CognitoUser | null; +} + export class InternalCognitoUser { constructor(data: ICognitoUserData); diff --git a/packages/amazon-cognito-identity-js/src/Client.js b/packages/amazon-cognito-identity-js/src/Client.js index 199432eb44a..4ab28a4be4e 100644 --- a/packages/amazon-cognito-identity-js/src/Client.js +++ b/packages/amazon-cognito-identity-js/src/Client.js @@ -83,6 +83,7 @@ export default class Client { * @param {string} operation API operation * @param {object} params Input parameters * @param {function} callback Callback called when a response is returned + * @param {string} userAgentValue Optional string containing custom user agent value * @returns {void} */ request(operation, params, callback, userAgentValue) { diff --git a/packages/amazon-cognito-identity-js/src/CognitoUserPool.js b/packages/amazon-cognito-identity-js/src/CognitoUserPool.js index 3f188234291..d71a575311e 100644 --- a/packages/amazon-cognito-identity-js/src/CognitoUserPool.js +++ b/packages/amazon-cognito-identity-js/src/CognitoUserPool.js @@ -3,83 +3,13 @@ * SPDX-License-Identifier: Apache-2.0 */ -import Client from './Client'; import CognitoUser from './CognitoUser'; -import StorageHelper from './StorageHelper'; +import { InternalCognitoUserPool } from './internals'; const USER_POOL_ID_MAX_LENGTH = 55; /** @class */ -export default class CognitoUserPool { - /** - * Constructs a new CognitoUserPool object - * @param {object} data Creation options. - * @param {string} data.UserPoolId Cognito user pool id. - * @param {string} data.ClientId User pool application client id. - * @param {string} data.endpoint Optional custom service endpoint. - * @param {object} data.fetchOptions Optional options for fetch API. - * (only credentials option is supported) - * @param {object} data.Storage Optional storage object. - * @param {boolean} data.AdvancedSecurityDataCollectionFlag Optional: - * boolean flag indicating if the data collection is enabled - * to support cognito advanced security features. By default, this - * flag is set to true. - */ - constructor(data, wrapRefreshSessionCallback) { - const { - UserPoolId, - ClientId, - endpoint, - fetchOptions, - AdvancedSecurityDataCollectionFlag, - } = data || {}; - if (!UserPoolId || !ClientId) { - throw new Error('Both UserPoolId and ClientId are required.'); - } - if (UserPoolId.length > USER_POOL_ID_MAX_LENGTH || !/^[\w-]+_[0-9a-zA-Z]+$/.test(UserPoolId)) { - throw new Error('Invalid UserPoolId format.'); - } - const region = UserPoolId.split('_')[0]; - - this.userPoolId = UserPoolId; - this.clientId = ClientId; - - this.client = new Client(region, endpoint, fetchOptions); - - /** - * By default, AdvancedSecurityDataCollectionFlag is set to true, - * if no input value is provided. - */ - this.advancedSecurityDataCollectionFlag = - AdvancedSecurityDataCollectionFlag !== false; - - this.storage = data.Storage || new StorageHelper().getStorage(); - - if (wrapRefreshSessionCallback) { - this.wrapRefreshSessionCallback = wrapRefreshSessionCallback; - } - } - - /** - * @returns {string} the user pool id - */ - getUserPoolId() { - return this.userPoolId; - } - - /** - * @returns {string} the user pool name - */ - getUserPoolName() { - return this.getUserPoolId().split('_')[1]; - } - - /** - * @returns {string} the client id - */ - getClientId() { - return this.clientId; - } +export default class CognitoUserPool extends InternalCognitoUserPool { /** * @typedef {object} SignUpResult @@ -105,90 +35,13 @@ export default class CognitoUserPool { callback, clientMetadata ) { - const jsonReq = { - ClientId: this.clientId, - Username: username, - Password: password, - UserAttributes: userAttributes, - ValidationData: validationData, - ClientMetadata: clientMetadata, - }; - if (this.getUserContextData(username)) { - jsonReq.UserContextData = this.getUserContextData(username); - } - this.client.request('SignUp', jsonReq, (err, data) => { - if (err) { - return callback(err, null); - } - - const cognitoUser = { - Username: username, - Pool: this, - Storage: this.storage, - }; - - const returnData = { - user: new CognitoUser(cognitoUser), - userConfirmed: data.UserConfirmed, - userSub: data.UserSub, - codeDeliveryDetails: data.CodeDeliveryDetails, - }; - - return callback(null, returnData); - }); - } - - /** - * method for getting the current user of the application from the local storage - * - * @returns {CognitoUser} the user retrieved from storage - */ - getCurrentUser() { - const lastUserKey = `CognitoIdentityServiceProvider.${this.clientId}.LastAuthUser`; - - const lastAuthUser = this.storage.getItem(lastUserKey); - if (lastAuthUser) { - const cognitoUser = { - Username: lastAuthUser, - Pool: this, - Storage: this.storage, - }; - - return new CognitoUser(cognitoUser); - } - - return null; - } - - /** - * This method returns the encoded data string used for cognito advanced security feature. - * This would be generated only when developer has included the JS used for collecting the - * data on their client. Please refer to documentation to know more about using AdvancedSecurity - * features - * @param {string} username the username for the context data - * @returns {string} the user context data - **/ - getUserContextData(username) { - if (typeof AmazonCognitoAdvancedSecurityData === 'undefined') { - return undefined; - } - /* eslint-disable */ - const amazonCognitoAdvancedSecurityDataConst = AmazonCognitoAdvancedSecurityData; - /* eslint-enable */ - - if (this.advancedSecurityDataCollectionFlag) { - const advancedSecurityData = amazonCognitoAdvancedSecurityDataConst.getData( - username, - this.userPoolId, - this.clientId - ); - if (advancedSecurityData) { - const userContextData = { - EncodedData: advancedSecurityData, - }; - return userContextData; - } - } - return {}; + return super.signUp( + username, + password, + userAttributes, + validationData, + callback, + clientMetadata + ); } } diff --git a/packages/amazon-cognito-identity-js/src/internals/InternalCognitoUserPool.js b/packages/amazon-cognito-identity-js/src/internals/InternalCognitoUserPool.js new file mode 100644 index 00000000000..af98946441e --- /dev/null +++ b/packages/amazon-cognito-identity-js/src/internals/InternalCognitoUserPool.js @@ -0,0 +1,196 @@ +/* + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * SPDX-License-Identifier: Apache-2.0 + */ + +import Client from '../Client'; +import CognitoUser from '../CognitoUser'; +import StorageHelper from '../StorageHelper'; + +const USER_POOL_ID_MAX_LENGTH = 55; + +/** @class */ +export class InternalCognitoUserPool { + /** + * Constructs a new CognitoUserPool object + * @param {object} data Creation options. + * @param {string} data.UserPoolId Cognito user pool id. + * @param {string} data.ClientId User pool application client id. + * @param {string} data.endpoint Optional custom service endpoint. + * @param {object} data.fetchOptions Optional options for fetch API. + * (only credentials option is supported) + * @param {object} data.Storage Optional storage object. + * @param {boolean} data.AdvancedSecurityDataCollectionFlag Optional: + * boolean flag indicating if the data collection is enabled + * to support cognito advanced security features. By default, this + * flag is set to true. + */ + constructor(data, wrapRefreshSessionCallback) { + const { + UserPoolId, + ClientId, + endpoint, + fetchOptions, + AdvancedSecurityDataCollectionFlag, + } = data || {}; + if (!UserPoolId || !ClientId) { + throw new Error('Both UserPoolId and ClientId are required.'); + } + if (UserPoolId.length > USER_POOL_ID_MAX_LENGTH || !/^[\w-]+_[0-9a-zA-Z]+$/.test(UserPoolId)) { + throw new Error('Invalid UserPoolId format.'); + } + const region = UserPoolId.split('_')[0]; + + this.userPoolId = UserPoolId; + this.clientId = ClientId; + + this.client = new Client(region, endpoint, fetchOptions); + + /** + * By default, AdvancedSecurityDataCollectionFlag is set to true, + * if no input value is provided. + */ + this.advancedSecurityDataCollectionFlag = + AdvancedSecurityDataCollectionFlag !== false; + + this.storage = data.Storage || new StorageHelper().getStorage(); + + if (wrapRefreshSessionCallback) { + this.wrapRefreshSessionCallback = wrapRefreshSessionCallback; + } + } + + /** + * @returns {string} the user pool id + */ + getUserPoolId() { + return this.userPoolId; + } + + /** + * @returns {string} the user pool name + */ + getUserPoolName() { + return this.getUserPoolId().split('_')[1]; + } + + /** + * @returns {string} the client id + */ + getClientId() { + return this.clientId; + } + + /** + * @typedef {object} SignUpResult + * @property {CognitoUser} user New user. + * @property {bool} userConfirmed If the user is already confirmed. + */ + /** + * method for signing up a user + * @param {string} username User's username. + * @param {string} password Plain-text initial password entered by user. + * @param {(AttributeArg[])=} userAttributes New user attributes. + * @param {(AttributeArg[])=} validationData Application metadata. + * @param {(AttributeArg[])=} clientMetadata Client metadata. + * @param {nodeCallback} callback Called on error or with the new user. + * @param {ClientMetadata} clientMetadata object which is passed from client to Cognito Lambda trigger + * @param {string} userAgentValue Optional string containing custom user agent value + * @returns {void} + */ + signUp( + username, + password, + userAttributes, + validationData, + callback, + clientMetadata, + userAgentValue + ) { + const jsonReq = { + ClientId: this.clientId, + Username: username, + Password: password, + UserAttributes: userAttributes, + ValidationData: validationData, + ClientMetadata: clientMetadata, + }; + if (this.getUserContextData(username)) { + jsonReq.UserContextData = this.getUserContextData(username); + } + this.client.request('SignUp', jsonReq, (err, data) => { + if (err) { + return callback(err, null); + } + + const cognitoUser = { + Username: username, + Pool: this, + Storage: this.storage, + }; + + const returnData = { + user: new CognitoUser(cognitoUser), + userConfirmed: data.UserConfirmed, + userSub: data.UserSub, + codeDeliveryDetails: data.CodeDeliveryDetails, + }; + + return callback(null, returnData); + }, userAgentValue); + } + + /** + * method for getting the current user of the application from the local storage + * + * @returns {CognitoUser} the user retrieved from storage + */ + getCurrentUser() { + const lastUserKey = `CognitoIdentityServiceProvider.${this.clientId}.LastAuthUser`; + + const lastAuthUser = this.storage.getItem(lastUserKey); + if (lastAuthUser) { + const cognitoUser = { + Username: lastAuthUser, + Pool: this, + Storage: this.storage, + }; + + return new CognitoUser(cognitoUser); + } + + return null; + } + + /** + * This method returns the encoded data string used for cognito advanced security feature. + * This would be generated only when developer has included the JS used for collecting the + * data on their client. Please refer to documentation to know more about using AdvancedSecurity + * features + * @param {string} username the username for the context data + * @returns {string} the user context data + **/ + getUserContextData(username) { + if (typeof AmazonCognitoAdvancedSecurityData === 'undefined') { + return undefined; + } + /* eslint-disable */ + const amazonCognitoAdvancedSecurityDataConst = AmazonCognitoAdvancedSecurityData; + /* eslint-enable */ + + if (this.advancedSecurityDataCollectionFlag) { + const advancedSecurityData = amazonCognitoAdvancedSecurityDataConst.getData( + username, + this.userPoolId, + this.clientId + ); + if (advancedSecurityData) { + const userContextData = { + EncodedData: advancedSecurityData, + }; + return userContextData; + } + } + return {}; + } +} diff --git a/packages/amazon-cognito-identity-js/src/internals/index.js b/packages/amazon-cognito-identity-js/src/internals/index.js index 5de97fc3cc3..f2ea4e2869e 100644 --- a/packages/amazon-cognito-identity-js/src/internals/index.js +++ b/packages/amazon-cognito-identity-js/src/internals/index.js @@ -4,3 +4,4 @@ export { } from '../UserAgent'; export { InternalCognitoUser } from './InternalCognitoUser'; +export { InternalCognitoUserPool } from './InternalCognitoUserPool'; diff --git a/packages/auth/package.json b/packages/auth/package.json index e3419e0616e..6c9116c2dd4 100644 --- a/packages/auth/package.json +++ b/packages/auth/package.json @@ -60,7 +60,7 @@ "name": "Auth (top-level class)", "path": "./lib-esm/index.js", "import": "{ Amplify, Auth }", - "limit": "56.29 kB" + "limit": "56.38 kB" } ], "jest": {