diff --git a/SalgodeUserCreate.js b/SalgodeUserCreate.js deleted file mode 100644 index fc5753c..0000000 --- a/SalgodeUserCreate.js +++ /dev/null @@ -1,126 +0,0 @@ -const aws = require('aws-sdk'); -const dynamoDb = new aws.DynamoDB.DocumentClient(); -const uuidv4 = require('uuid/v4'); -const moment = require('moment'); -const bcrypt = require('bcryptjs'); - -const SALT_LENGTH = 15; - -module.exports.handler = function(event, context, callback) { - if ( - !event.TableName || - !event.resource || - !event.operation || - !event.payload || - !event.payload.Item - ) { - return callback(null, BadRequest); - } - - console.log('enters create'); - let timestamp = moment().format('YYYY-MM-DDTHH:mm:ss-04:00'); - - let input = event.payload.Item; - - if ( - !input.email || - !input.name || - !input.lastName || - !input.phone || - !input.selfieLink || - !input.dniFrontLink || - !input.dniBackLink || - !input.password || - !input.passwordRepeat - ) { - return callback(null, BadRequest); - } - - if ( - input.car && - !(input.car.plate && input.car.model && input.car.color && input.car.brand) - ) { - if ( - input.car.plate || - input.car.model || - input.car.color || - input.car.brand - ) { - return callback(null, BadRequest); - } - delete event.payload.Item.car; - } - - let params = { - TableName: event.TableName, - Item: { - id: 'usr_' + uuidv4(), - token: uuidv4(), - ...filterEmptyKeys(event.payload.Item), - createdAt: timestamp, - updatedAt: timestamp - }, - ConditionExpression: 'attribute_not_exists(email)' - }; - - console.log('params\n', params); - console.log('params\n', params); - console.log('params\n', params); - - if (params.Item.password !== params.Item.passwordRepeat) { - return callback(null, ValidationErrorPasswordMismatch); - } - - delete params.Item.passwordRepeat; - - const Salt = bcrypt.genSaltSync(SALT_LENGTH); - params.Item.password = bcrypt.hashSync(params.Item.password, Salt); - - return dynamoDb.put(params, error => { - if (error) { - console.error(error); - if (error.code === 'ConditionalCheckFailedException') { - return callback(null, ValidationErrorEmailAlreadyInUse); - } - return callback(null, InternalServerError); - } - - delete params.Item.password; - - let response = { - statusCode: 200, - body: params.Item - }; - return callback(null, response); - }); -}; - -function filterEmptyKeys(obj) { - var nonEmptyKeys = Object.keys(obj).filter(k => obj[k] !== ''); - var retObj = {}; - nonEmptyKeys.forEach(key => { - retObj[key] = obj[key]; - }); - return retObj; -} - -function isEmpty(obj) { - return Object.keys(obj).length === 0 && obj.constructor === Object; -} - -let BadRequest = { - statusCode: 400, - message: 'Tu solicitud tiene errores' -}; -let ValidationErrorEmailAlreadyInUse = { - statusCode: 400, - message: 'El email ya está en uso' -}; -let ValidationErrorPasswordMismatch = { - statusCode: 400, - message: 'Las contraseñas no coinciden' -}; -let InternalServerError = { - statusCode: 503, - message: 'Algo inesperado acaba de pasar... gracias por intentar más tarde' -}; diff --git a/create_user.js b/create_user.js new file mode 100644 index 0000000..0be6c61 --- /dev/null +++ b/create_user.js @@ -0,0 +1,102 @@ +const aws = require('aws-sdk'); +const dynamoDB = new aws.DynamoDB.DocumentClient(); +const uuidv4 = require('uuid/v4'); +const moment = require('moment'); +const bcrypt = require('bcryptjs'); + +function hashPassword(userPassword) { + let Salt = bcrypt.genSaltSync(15); + return bcrypt.hashSync(userPassword, Salt); +} + +async function checkEmail(userEmail) { + let params = { + TableName: process.env.dynamodb_table_name, + IndexName: process.env.dynamodb_index_name, + ProjectionExpression: "user_id, email", + KeyConditionExpression: "email = :email", + ExpressionAttributeValues: { + ":email": userEmail + } + }; + let data = await dynamoDB.query(params).promise(); + return data.Count; +} + +async function createUser(userId, bearerToken, userEmail, passwordHash, firstName, lastName, userPhone, identificationImages, createdAt) { + let params = { + TableName: process.env.dynamodb_table_name, + Item: { + user_id: userId, + email: userEmail, + password_hash: passwordHash, + bearer_token: bearerToken, + first_name: firstName, + last_name: lastName, + phone: userPhone, + user_identifications: { + identification_image_front: identificationImages.identification_image_front, + identification_image_back: identificationImages.identification_image_back, + selfie_image: identificationImages.selfie_image + }, + created_at: createdAt, + updated_at: createdAt + } + }; + let data = await dynamoDB.put(params).promise(); + return data; +} + +exports.handler = async (event) => { + let body = JSON.parse(event.body); + let userEmail = body.email; + let userPassword = body.password; + let firstName = body.first_name; + let lastName = body.last_name; + let userPhone = body.phone; + let identificationImages = body.user_identifications; + + let emailIsUsed = await checkEmail(userEmail); + + if (emailIsUsed > 0) { + let responseBody = { + message: 'Email has already been used' + }; + return { + statusCode: 409, + headers: {'Access-Control-Allow-Origin': '*'}, + body: JSON.stringify(responseBody) + }; + } + else { + let userId = 'usr_' + uuidv4(); + let bearerToken = uuidv4(); + let createdAt = moment().format('YYYY-MM-DDTHH:mm:ss-04:00'); + let passwordHash = hashPassword(userPassword); + await createUser(userId, bearerToken, userEmail, passwordHash, firstName, lastName, userPhone, identificationImages, createdAt); + let responseBody = { + message: 'User has been created', + user: { + user_id: userId, + email: userEmail, + bearer_token: bearerToken, + first_name: firstName, + last_name: lastName, + phone: userPhone, + user_identifications: { + identification_image_front: identificationImages.identification_image_front, + identification_image_back: identificationImages.identification_image_back, + selfie_image: identificationImages.selfie_image + }, + created_at: createdAt, + updated_at: createdAt + } + }; + return { + statusCode: 201, + headers: {'Access-Control-Allow-Origin': '*'}, + body: JSON.stringify(responseBody) + }; + } + +};