Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

#162414161 validate user's input data #16

Merged
merged 1 commit into from
Jan 22, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
28 changes: 23 additions & 5 deletions constants/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,18 +9,29 @@ const FROM = 'no-reply@authorshaven.com',
SERVER_ERROR_CODE = 500,
UNSUCCESSFUL = false,
SUCCESSFUL = true,
LIMIT = 15,
OFFSET = 1,
NO_TOKEN_PROVIDED = 'No token provided',
JWT_EXPIRED = 'The token provided has expired',
JWT_MALFORMED = 'Wrong token provided or Invalid signature',
TOKEN_TIMESPAN = '1d',
LIMIT = 15,
OFFSET = 1,
SERVER_ERROR_MESSAGE = 'Ooops! Something went wrong, kindly try again',
ACCOUNT_CREATED = 'Account successfully created, Kindly check your email to activate your account',
ALREADY_ACTIVATED_ERROR = 'Account is already activated',
ACCOUNT_ACTIVATED = 'Your Account is Now Activated!',
INVALID_USER = 'Invalid user',
WELCOME_NEW_USER = 'Welcome!',
WELCOME_EXISTING_USER = 'Welcome back',
INVALID_EMAIL = 'email must be valid',
EMAIL_ALREADY_EXIST = 'email already exist',
USER_RETRIEVAL_SUCCESS_MESSAGE = 'users retrieved succesfully',
SERVER_RETRIEVAL_MESSAGE = 'There as been an error somewhere,please try again!';

module.exports = {
FROM,
SUBJECT,
LIMIT,
OFFSET,
BAD_REQUEST_CODE,
UNAUTHORIZED_CODE,
OK_CODE,
Expand All @@ -34,8 +45,15 @@ module.exports = {
NO_TOKEN_PROVIDED,
JWT_MALFORMED,
JWT_EXPIRED,
LIMIT,
OFFSET,
SERVER_ERROR_MESSAGE,
ACCOUNT_CREATED,
ACCOUNT_ACTIVATED,
ALREADY_ACTIVATED_ERROR,
INVALID_USER,
WELCOME_NEW_USER,
WELCOME_EXISTING_USER,
INVALID_EMAIL,
EMAIL_ALREADY_EXIST,
USER_RETRIEVAL_SUCCESS_MESSAGE,
SERVER_RETRIEVAL_MESSAGE,
SERVER_RETRIEVAL_MESSAGE
};
8 changes: 8 additions & 0 deletions constants/mock.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
const user = {
email: 'testmail@yahoo.com',
password: '111111',
firstname: 'testfirstname',
lastname: 'testlastname'
};

module.exports = user;
4 changes: 2 additions & 2 deletions controllers/Users/userController.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,12 +24,12 @@ class UsersController {
}
} catch (error) {
response.failureResponse(
res, constants.SERVER_RETRIEVAL_MESSAGE,
res,
constants.SERVER_RETRIEVAL_MESSAGE,
constants.SERVER_ERROR_CODE
);
}
}
}


module.exports = UsersController;
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
34 changes: 24 additions & 10 deletions lib/modelManagers/usermodel.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,21 @@ class UserModelManager {
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;
}

/**
*
Expand All @@ -43,7 +58,6 @@ class UserModelManager {
return findUser;
}


/**
*
* @param {id} id The user's id.
Expand Down Expand Up @@ -92,15 +106,15 @@ class UserModelManager {
}

/**
*
*
* @static
* @param {any} emails
* @param {any} name
* @returns {object} User
*
* @memberOf User
*/
*
*
* @static
* @param {any} emails
* @param {any} name
* @returns {object} User
*
* @memberOf User
*/
static async findOrCreateUser(emails, name) {
const createdUser = await user.findOrCreate({
where: {
Expand Down
4 changes: 2 additions & 2 deletions lib/utils/emailService/emailVerification.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,9 @@ const baseUrl = process.env.APP_BASE_URL;
async function sendVerificationMail(req, res) {
sgMail.setApiKey(process.env.SENDGRID_API_KEY);

const { token, email } = req;
const { jwtToken, email } = req;

const hostUrl = `${baseUrl}/verifyemail/${token}`;
const hostUrl = `${baseUrl}/verifyemail/${jwtToken}`;
const msg = {
to: email,
from: FROM,
Expand Down
14 changes: 14 additions & 0 deletions lib/utils/messageFormatter.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
const formatErrorMessage = (msgArr) => {
const message = {};
const messageSpliter = arr => arr.split(' ')[0];
msgArr.forEach((msg) => {
if (!message[messageSpliter(msg)]) {
message[messageSpliter(msg)] = [msg];
} else {
message[messageSpliter(msg)].push(msg);
}
});
return message;
};

module.exports = formatErrorMessage;
16 changes: 16 additions & 0 deletions lib/utils/messageHandler.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
const {
OK_CODE, NOT_FOUND_CODE, UNSUCCESSFUL, SUCCESSFUL
} = require('../../constants/');

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

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

module.exports = { successResponse, failureResponse };
4 changes: 1 addition & 3 deletions lib/utils/pagination/paginationHelper.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
const { LIMIT, OFFSET } = require('../../../constants');

const { LIMIT, OFFSET } = require('../../../constants/index');

const paginate = (query) => {
if (query.limit || query.offset) {
Expand All @@ -26,7 +25,6 @@ const paginate = (query) => {
const page = OFFSET;
const limit = LIMIT;
const offset = limit * (page - 1);

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

/**
* @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 @@
const { INVALID_EMAIL } = require('../../constants/index');
/**
*
* @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) {
Luckzman marked this conversation as resolved.
Show resolved Hide resolved
req
.check(email)
.notEmpty()
.withMessage(`${email} is required`)
.isEmail()
.trim()
.withMessage(INVALID_EMAIL);
}
/**
*
* @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 an uppercase`)
.matches('[0-9]')
.withMessage(`${password} must contain atleast a number`);
}

module.exports = { validateName, validateEmail, validatePassword };
29 changes: 29 additions & 0 deletions middlewares/checkEmail.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
const User = require('../lib/modelManagers/usermodel');
const {
CONFLICT_CODE,
SERVER_ERROR_CODE,
EMAIL_ALREADY_EXIST,
SERVER_ERROR_MESSAGE
} = 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, SERVER_ERROR_MESSAGE, SERVER_ERROR_CODE);
}
}

module.exports = checkEmail;
Loading