UNPKG

5.57 kBJavaScriptView Raw
1/*!
2 * Copyright 2016 Amazon.com,
3 * Inc. or its affiliates. All Rights Reserved.
4 *
5 * Licensed under the Amazon Software License (the "License").
6 * You may not use this file except in compliance with the
7 * License. A copy of the License is located at
8 *
9 * http://aws.amazon.com/asl/
10 *
11 * or in the "license" file accompanying this file. This file is
12 * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
13 * CONDITIONS OF ANY KIND, express or implied. See the License
14 * for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18import Client from './Client';
19import CognitoUser from './CognitoUser';
20import StorageHelper from './StorageHelper';
21
22/** @class */
23export default class CognitoUserPool {
24 /**
25 * Constructs a new CognitoUserPool object
26 * @param {object} data Creation options.
27 * @param {string} data.UserPoolId Cognito user pool id.
28 * @param {string} data.ClientId User pool application client id.
29 * @param {string} data.endpoint Optional custom service endpoint.
30 * @param {object} data.fetchOptions Optional options for fetch API.
31 * (only credentials option is supported)
32 * @param {object} data.Storage Optional storage object.
33 * @param {boolean} data.AdvancedSecurityDataCollectionFlag Optional:
34 * boolean flag indicating if the data collection is enabled
35 * to support cognito advanced security features. By default, this
36 * flag is set to true.
37 */
38 constructor(data) {
39 const {
40 UserPoolId,
41 ClientId,
42 endpoint,
43 fetchOptions,
44 AdvancedSecurityDataCollectionFlag,
45 } = data || {};
46 if (!UserPoolId || !ClientId) {
47 throw new Error('Both UserPoolId and ClientId are required.');
48 }
49 if (!/^[\w-]+_.+$/.test(UserPoolId)) {
50 throw new Error('Invalid UserPoolId format.');
51 }
52 const region = UserPoolId.split('_')[0];
53
54 this.userPoolId = UserPoolId;
55 this.clientId = ClientId;
56
57 this.client = new Client(region, endpoint, fetchOptions);
58
59 /**
60 * By default, AdvancedSecurityDataCollectionFlag is set to true,
61 * if no input value is provided.
62 */
63 this.advancedSecurityDataCollectionFlag =
64 AdvancedSecurityDataCollectionFlag !== false;
65
66 this.storage = data.Storage || new StorageHelper().getStorage();
67 }
68
69 /**
70 * @returns {string} the user pool id
71 */
72 getUserPoolId() {
73 return this.userPoolId;
74 }
75
76 /**
77 * @returns {string} the client id
78 */
79 getClientId() {
80 return this.clientId;
81 }
82
83 /**
84 * @typedef {object} SignUpResult
85 * @property {CognitoUser} user New user.
86 * @property {bool} userConfirmed If the user is already confirmed.
87 */
88 /**
89 * method for signing up a user
90 * @param {string} username User's username.
91 * @param {string} password Plain-text initial password entered by user.
92 * @param {(AttributeArg[])=} userAttributes New user attributes.
93 * @param {(AttributeArg[])=} validationData Application metadata.
94 * @param {(AttributeArg[])=} clientMetadata Client metadata.
95 * @param {nodeCallback<SignUpResult>} callback Called on error or with the new user.
96 * @param {ClientMetadata} clientMetadata object which is passed from client to Cognito Lambda trigger
97 * @returns {void}
98 */
99 signUp(
100 username,
101 password,
102 userAttributes,
103 validationData,
104 callback,
105 clientMetadata
106 ) {
107 const jsonReq = {
108 ClientId: this.clientId,
109 Username: username,
110 Password: password,
111 UserAttributes: userAttributes,
112 ValidationData: validationData,
113 ClientMetadata: clientMetadata,
114 };
115 if (this.getUserContextData(username)) {
116 jsonReq.UserContextData = this.getUserContextData(username);
117 }
118 this.client.request('SignUp', jsonReq, (err, data) => {
119 if (err) {
120 return callback(err, null);
121 }
122
123 const cognitoUser = {
124 Username: username,
125 Pool: this,
126 Storage: this.storage,
127 };
128
129 const returnData = {
130 user: new CognitoUser(cognitoUser),
131 userConfirmed: data.UserConfirmed,
132 userSub: data.UserSub,
133 codeDeliveryDetails: data.CodeDeliveryDetails,
134 };
135
136 return callback(null, returnData);
137 });
138 }
139
140 /**
141 * method for getting the current user of the application from the local storage
142 *
143 * @returns {CognitoUser} the user retrieved from storage
144 */
145 getCurrentUser() {
146 const lastUserKey = `CognitoIdentityServiceProvider.${
147 this.clientId
148 }.LastAuthUser`;
149
150 const lastAuthUser = this.storage.getItem(lastUserKey);
151 if (lastAuthUser) {
152 const cognitoUser = {
153 Username: lastAuthUser,
154 Pool: this,
155 Storage: this.storage,
156 };
157
158 return new CognitoUser(cognitoUser);
159 }
160
161 return null;
162 }
163
164 /**
165 * This method returns the encoded data string used for cognito advanced security feature.
166 * This would be generated only when developer has included the JS used for collecting the
167 * data on their client. Please refer to documentation to know more about using AdvancedSecurity
168 * features
169 * @param {string} username the username for the context data
170 * @returns {string} the user context data
171 **/
172 getUserContextData(username) {
173 if (typeof AmazonCognitoAdvancedSecurityData === 'undefined') {
174 return undefined;
175 }
176 /* eslint-disable */
177 const amazonCognitoAdvancedSecurityDataConst = AmazonCognitoAdvancedSecurityData;
178 /* eslint-enable */
179
180 if (this.advancedSecurityDataCollectionFlag) {
181 const advancedSecurityData = amazonCognitoAdvancedSecurityDataConst.getData(
182 username,
183 this.userPoolId,
184 this.clientId
185 );
186 if (advancedSecurityData) {
187 const userContextData = {
188 EncodedData: advancedSecurityData,
189 };
190 return userContextData;
191 }
192 }
193 return {};
194 }
195}