Skip to content

Commit

Permalink
[ft-#162414161] validate user's input data
Browse files Browse the repository at this point in the history
  • Loading branch information
Luckzman committed Jan 18, 2019
1 parent 1d2b25a commit cedf8d2
Show file tree
Hide file tree
Showing 18 changed files with 468 additions and 95 deletions.
Binary file modified .DS_Store
Binary file not shown.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@ node_modules
.nyc_output
.env
.DS_Store
coverage
2 changes: 1 addition & 1 deletion .travis.yml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
language: node_js
node_js:
- 'node'
- "node"
install: npm install
services:
- postgresql
Expand Down
19 changes: 19 additions & 0 deletions constants/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
const OK_CODE = 200,
CREATED_CODE = 201,
BAD_REQUEST_CODE = 400,
UNAUTHORIZED_CODE = 401,
FORBIDDEN_CODE = 403,
NOT_FOUND_CODE = 404,
CONFLICT_CODE = 409,
SERVER_ERROR_CODE = 500;

module.exports = {
OK_CODE,
CREATED_CODE,
BAD_REQUEST_CODE,
UNAUTHORIZED_CODE,
FORBIDDEN_CODE,
NOT_FOUND_CODE,
CONFLICT_CODE,
SERVER_ERROR_CODE
};
Empty file removed controllers/index.js
Empty file.
2 changes: 2 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ const express = require('express'),
bodyParser = require('body-parser'),
session = require('express-session'),
cors = require('cors'),
validator = require('express-validator'),
errorhandler = require('errorhandler'),
isProduction = process.env.NODE_ENV === 'production';

Expand All @@ -19,6 +20,7 @@ app.use(require('morgan')('dev'));

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(validator());

app.use(require('method-override')());

Expand Down
23 changes: 21 additions & 2 deletions lib/modelManagers/usermodel.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,30 @@ class User {
*/
static async create(email, password, firstname, lastname) {
const createdRecord = await user.create({
email, password, firstname, lastname
email,
password,
firstname,
lastname
});
return createdRecord;
}

/**
*
* @param {string} email user's Email to search.
* @static
* @memberof User
* @returns {object} The parameters from the query
*/
static async findUserByEmail(email) {
const userRecord = await user.findOne({
where: {
email
}
});
return userRecord;
}

/**
*
* @param {id} id The user's id.
Expand All @@ -33,7 +52,7 @@ class User {
static async update(id, field) {
const updatedRecord = await user.update(
{
field,
field
},
{
where: {
Expand Down
14 changes: 14 additions & 0 deletions lib/utils/messageHandler.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
const { OK_CODE, NOT_FOUND_CODE } = require('../../constants/');

const successResponse = (res, message, data, statusCode = OK_CODE) => res.status(statusCode).json({
success: true,
message,
data
});

const failureResponse = (res, message, statusCode = NOT_FOUND_CODE) => res.status(statusCode).json({
success: false,
message
});

module.exports = { successResponse, failureResponse };
43 changes: 43 additions & 0 deletions lib/utils/signupValidator.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
/* eslint-disable newline-per-chained-call */
const { validateName, validateEmail, validatePassword } = require('./validate');
const { failureResponse } = require('../utils/messageHandler');
const { BAD_REQUEST_CODE } = require('../../constants/index');

// const BAD_REQUEST_CODE = 400;

const formatErrorMessage = (msgArr) => {
const message = {};
// eslint-disable-next-line no-restricted-syntax
for (const msg of msgArr) {
if (!message[msg.split(' ')[0]]) {
message[msg.split(' ')[0]] = [msg];
} else {
message[msg.split(' ')[0]].push(msg);
}
}
return message;
};

/**
* @description check against errors on signup fields
* @param {object} req
* @param {object} res
* @param {function} next
* @returns {function} undefined
*/
const signupValidator = (req, res, next) => {
validateEmail(req, 'email');
validatePassword(req, 'password');
validateName(req, 'firstname');
validateName(req, 'lastname');

const errors = req.validationErrors();

if (errors) {
const errorMessages = errors.map(err => err.msg);
return failureResponse(res, formatErrorMessage(errorMessages), BAD_REQUEST_CODE);
}
next();
};

module.exports = signupValidator;
56 changes: 56 additions & 0 deletions lib/utils/validate.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
/* eslint-disable newline-per-chained-call */
/**
*
* @description This function validate input field that need an alphabet
* @param {object} req
* @param {string} name
* @returns {*} *
*/
function validateName(req, name) {
req
.check(name)
.notEmpty()
.withMessage(`${name} is required`)
.isAlpha()
.trim()
.withMessage(`${name} must be alphabets`);
}
/**
*
* @description This function validate input field that need an alphabet
* @param {object} req
* @param {string} email
* @returns {*} *
*/
function validateEmail(req, email) {
req
.check(email)
.notEmpty()
.withMessage(`${email} is required`)
.isEmail()
.trim()
.withMessage('email must be valid');
}
/**
*
* @description This function validate input field that need an alphabet
* @param {object} req
* @param {string} password
* @returns {*} *
*/
function validatePassword(req, password) {
req
.check(password)
.notEmpty()
.withMessage(`${password} is required`)
.isLength({ min: 8 })
.withMessage(`${password} must not be less than 8 characters`)
.matches('[a-z]')
.withMessage(`${password} must contain atleast a lowercase`)
.matches('[A-Z]')
.withMessage(`${password} must contain atleast a uppercase`)
.matches('[0-9]')
.withMessage(`${password} must contain atleast a number`);
}

module.exports = { validateName, validateEmail, validatePassword };
24 changes: 24 additions & 0 deletions middlewares/checkEmail.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
const User = require('../lib/modelManagers/usermodel');
const { CONFLICT_CODE, SERVER_ERROR_CODE } = require('../constants');
const { failureResponse } = require('../lib/utils/messageHandler');

/**
* @description Check if email is already in the database
* @param {*} req
* @param {*} res
* @param {*} next middleware in the stack
* @returns {*} *
*/
async function checkEmail(req, res, next) {
try {
const record = await User.findUserByEmail(req.body.email);
if (record) {
return failureResponse(res, 'email already exist', CONFLICT_CODE);
}
return next();
} catch (error) {
return failureResponse(res, 'Something went wrong. Please try again later.', SERVER_ERROR_CODE);
}
}

module.exports = checkEmail;
Loading

0 comments on commit cedf8d2

Please sign in to comment.