-
Notifications
You must be signed in to change notification settings - Fork 0
/
create_user.js
297 lines (274 loc) · 8.27 KB
/
create_user.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
const aws = require('aws-sdk');
const bcrypt = require('bcryptjs');
const moment = require('moment');
const uuidv4 = require('uuid/v4');
const BaseEmailConfirmationUrl = process.env.salgode_email_confirmation_base_url;
const ImagesBaseUrl = process.env.salgode_images_bucket_base_url;
const UsersIndexName = process.env.dynamodb_users_index_name;
let EventsTableName = process.env.dynamodb_events_table_name;
let ImagesTableName = process.env.dynamodb_images_table_name;
let UsersTableName = process.env.dynamodb_users_table_name;
function stagingOverwrite() {
EventsTableName = `Dev_${process.env.dynamodb_events_table_name}`;
ImagesTableName = `Dev_${process.env.dynamodb_images_table_name}`;
UsersTableName = `Dev_${process.env.dynamodb_users_table_name}`;
}
const dynamoDB = new aws.DynamoDB.DocumentClient();
const ses = new aws.SES();
function hashPassword(userPassword) {
const Salt = bcrypt.genSaltSync(15);
return bcrypt.hashSync(userPassword, Salt);
}
function parseImageUrl(baseUrl, folder, file) {
return `${baseUrl}/${folder}/${file}`;
}
function parseConfirmationUrl(userId, token) {
return `${BaseEmailConfirmationUrl}?user=${userId}&token=${token}`;
}
async function getImageUrl(imageId) {
const params = {
TableName: ImagesTableName,
Key: {
image_id: imageId
},
ProjectionExpression: 'file_name, folder_name'
};
const data = await dynamoDB.get(params).promise();
const image = data.Item;
return parseImageUrl(ImagesBaseUrl, image.folder_name, image.file_name);
}
async function checkEmail(userEmail) {
const params = {
TableName: UsersTableName,
IndexName: UsersIndexName,
ProjectionExpression: 'user_id, email',
KeyConditionExpression: 'email = :email',
ExpressionAttributeValues: {
':email': userEmail
}
};
const data = await dynamoDB.query(params).promise();
return data.Count;
}
async function sendConfirmationEmail(recipientAddress, recipientName, confirmationLink) {
const params = {
Destination: {
ToAddresses: [recipientAddress]
},
Message: {
Subject: { Data: 'Bienvenid@ a SALGODE - Confirma tu email' },
Body: {
Text:
{
Data:
`Hola ${recipientName}!
List@ para hacer del mundo un lugar mejor?
Confirma tu email con este link ${confirmationLink}
Atentamente,
Equipo #SalgoDe`
}
}
},
Source: '[email protected]'
};
const result = await ses.sendEmail(params).promise();
return result;
}
async function createUser(
userEmail,
userPassword,
firstName,
lastName,
userPhone,
userIdentifications,
rawData
) {
const eventId = `evt_${uuidv4()}`;
const userId = `usr_${uuidv4()}`;
const bearerToken = uuidv4();
const emailToken = uuidv4();
const passwordHash = hashPassword(userPassword);
const timestamp = moment().format('YYYY-MM-DDTHH:mm:ss-04:00');
const eventData = rawData;
delete eventData.password;
try {
await dynamoDB
.transactWrite({
TransactItems: [
{
Put: {
TableName: UsersTableName,
Item: {
user_id: userId,
bearer_token: bearerToken,
email: userEmail,
email_token: emailToken,
password_hash: passwordHash,
first_name: firstName,
last_name: lastName,
phone: userPhone,
user_identifications: {
selfie_image: userIdentifications.selfie_image || null,
identification: {
front: userIdentifications.identification_image_front || null,
back: userIdentifications.identification_image_back || null
},
driver_license: {
front: userIdentifications.driver_license_image_front || null,
back: userIdentifications.driver_license_image_back || null
}
},
user_verifications: {
email: false,
phone: false,
selfie_image: false,
selfie_image_checked: false,
identification: {
front: false,
front_checked: false,
back: false,
back_checked: false
},
driver_license: {
front: false,
front_checked: false,
back: false,
back_checked: false
}
},
vehicles: [],
created_at: timestamp,
updated_at: timestamp
}
}
},
{
Put: {
TableName: EventsTableName,
Item: {
event_id: eventId,
user_id: userId,
resource_id: userId,
resource: 'user',
action: 'create',
event_data: eventData,
created_at: timestamp
}
}
}
]
})
.promise();
return { userId, bearerToken, emailToken };
} catch (e) {
return false;
}
}
exports.handler = async (event) => {
if (event.requestContext.stage === 'staging') { stagingOverwrite(); }
const body = JSON.parse(event.body);
const userEmail = body.email.toLowerCase();
const userPassword = body.password;
const firstName = body.first_name;
const lastName = body.last_name;
const userPhone = body.phone;
const userIdentifications = body.user_identifications;
if (
!userEmail || !userPassword || !firstName || !lastName || !userPhone
|| !userIdentifications || !userIdentifications.selfie_image
) {
return {
statusCode: 400,
headers: { 'Access-Control-Allow-Origin': '*' },
body: JSON.stringify({
action: 'create',
success: false,
resource: 'user',
message: 'Wrong or missing parameters'
})
};
}
const emailIsUsed = await checkEmail(userEmail);
if (emailIsUsed) {
return {
statusCode: 409,
headers: { 'Access-Control-Allow-Origin': '*' },
body: JSON.stringify({ message: 'Email has already been used' })
};
}
let selfieUrl;
let identFrontUrl;
let identBackUrl;
let driverFrontUrl;
let driverBackUrl;
try {
selfieUrl = userIdentifications.selfie_image
? await getImageUrl(userIdentifications.selfie_image)
: null;
identFrontUrl = userIdentifications.identification_image_front
? await getImageUrl(userIdentifications.identification_image_front)
: null;
identBackUrl = userIdentifications.identification_image_back
? await getImageUrl(userIdentifications.identification_image_back)
: null;
driverFrontUrl = userIdentifications.driver_license_image_front
? await getImageUrl(userIdentifications.driver_license_image_front)
: null;
driverBackUrl = userIdentifications.driver_license_image_back
? await getImageUrl(userIdentifications.driver_license_image_back)
: null;
} catch (err) {
return {
statusCode: 400,
headers: { 'Access-Control-Allow-Origin': '*' },
body: JSON.stringify({
action: 'create',
success: false,
resource: 'user',
message: 'Wrong or missing parameters'
})
};
}
const { userId, bearerToken, emailToken } = await createUser(
userEmail,
userPassword,
firstName,
lastName,
userPhone,
userIdentifications,
body
);
const confirmationUrl = parseConfirmationUrl(userId, emailToken);
await sendConfirmationEmail(userEmail, firstName, confirmationUrl);
const responseBody = {
bearer_token: bearerToken,
user_id: userId,
first_name: firstName,
last_name: lastName,
email: userEmail,
phone: userPhone,
avatar: selfieUrl,
user_verifications: {
email: false,
phone: false,
identity: false,
driver_license: false
},
user_identifications: {
selfie: selfieUrl,
identification: {
front: identFrontUrl,
back: identBackUrl
},
driver_license: {
front: driverFrontUrl,
back: driverBackUrl
}
}
};
return {
statusCode: 201,
headers: { 'Access-Control-Allow-Origin': '*' },
body: JSON.stringify(responseBody)
};
};