Skip to content

Commit

Permalink
Merge 4893af5 into fe55f66
Browse files Browse the repository at this point in the history
  • Loading branch information
Niyitangasam committed May 28, 2019
2 parents fe55f66 + 4893af5 commit f7eac6a
Show file tree
Hide file tree
Showing 9 changed files with 463 additions and 10 deletions.
1 change: 0 additions & 1 deletion config/passport/localstrategy.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ const pass = (passport) => {
}).then(user => done(null, user)).catch(error => done(error));
}
));

passport.use('local_signin', new LocalStrategy(
{
usernameField: 'email',
Expand Down
86 changes: 84 additions & 2 deletions controllers/user.controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -88,8 +88,8 @@ class UserController {
}

/**
* Verify account of a user
* @function verifyAccount
* Verify account of a user
* @function verifyAccount
* @param {object} req - accept object with user info
* @param {object} res - accept object with user info
* @return {json} Returns json object
Expand Down Expand Up @@ -123,6 +123,60 @@ class UserController {
});
}

/**
* Create a new User
* @function addUser
* @param {object} req - accept object with user info
* @param {object} res - accept object with user info
* @return {json} Returns json object
* @static
*/
static async createUser(req, res) {
const newUser = await userHelper.createNewUser(req);
if (newUser) {
return res.status(201).send({
status: 201, message: `New User created and the password is ${newUser.generatedPassword}`
});
}
}

/**
* @param {object} req
* @param {object} res
* @returns {object} return object containg user info
*/
static async updateUser(req, res) {
const { ...user } = req.body;
try {
const { username } = req.params;
const updateUser = await User.update(
user,
{ where: { username }, returning: true, plain: true }
);
if (user.email) {
await User.update(
{ isVerified: false },
{ where: { username }, returning: true, plain: true }
);
await userHelper.sendVerificationEmail(user.email);
}
const newUserUpdated = {
firstName: updateUser[1].firstName,
lastName: updateUser[1].lastName,
email: updateUser[1].email
};
res.status(200).send({
status: 200,
data: newUserUpdated
});
} catch (error) {
res.status(500).json({
status: 500,
error: error.message
});
}
}

/**
* Check the environment
* @function loginUser
Expand Down Expand Up @@ -159,5 +213,33 @@ class UserController {
users
});
}

/**
* @param {object} req - Request object
* @param {object} res - Response object
* @returns {object} response
* @static
*/
static async getUser(req, res) {
const user = await userHelper.getOneUser(req);
if (!user) {
return res.status(404).json({
status: res.statusCode,
error: 'User Not found'
});
}
return res.status(200).send({ user });
}

/**
* @param {object} req - Request object
* @param {object} res - Response object
* @returns {object} response
* @static
*/
static async enableOrDisableUser(req, res) {
const user = await userHelper.enableOrDisableUser(req);
return res.status(200).send({ user });
}
}
export default UserController;
206 changes: 203 additions & 3 deletions helpers/userHelper.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
import jwt from 'jsonwebtoken';
import Joi from 'joi';
import generator from 'generate-password';
import db from '../models';
import helper from './index';
import recordHelper from './passport';
import sendEmail from './utils/mail-sender';
import ArticleHelper from './article';

const { User, Follows, Sequelize } = db;
/**
Expand All @@ -11,6 +14,78 @@ const { User, Follows, Sequelize } = db;
* @description User Helper
* */
class UserHelper {
/**
* Create a new User
* @function createNewUser
* @param {object} req - a request received
* @return {object} object of follower
* @static
*/
static async createNewUser(req) {
const {
firstName, lastName, username, email
} = req.body;
const generatedPassword = generator.generate({
length: 10,
numbers: true,
symbols: true
});
const password = await helper.hashPassword(generatedPassword);
const user = await User.create({
firstName,
lastName,
username,
email,
password
});
await this.sendVerificationEmail(email);
return { user, generatedPassword };
}

/**
* Check if it is a Article
* @param {object} req - an object
* @param {object} res - an object
* @param {object} next - an object
* @return {boolean} Returns if true if it is valid else return false
* @static
*/
static isValidInfo(req, res, next) {
const schema = Joi.object().keys({
firstName: Joi.string().required(),
lastName: Joi.string().required(),
username: Joi.string().required(),
email: Joi.string().email().required()
});
const result = Joi.validate(req.body, schema);
if (result.error) {
return ArticleHelper.invalidDataMessage(res, result);
}
next();
}

/**
* Check if it is a Article
* @param {object} req - an object
* @param {object} res - an object
* @param {object} next - an object
* @return {boolean} Returns if true if it is valid else return false
* @static
*/
static isValidUpdateInfo(req, res, next) {
const schema = Joi.object().keys({
firstName: Joi.string(),
lastName: Joi.string(),
username: Joi.string(),
email: Joi.string().email()
});
const result = Joi.validate(req.body, schema);
if (result.error) {
return ArticleHelper.invalidDataMessage(res, result);
}
next();
}

/**
* Create a user signup validation
* @param {string} req - request body
Expand All @@ -32,10 +107,12 @@ class UserHelper {
const emailUsernameValidation = helper.emailUsernamevalidator(checkemail, checkusername);
if (req.body.email === undefined || req.body.email.length === 0) { errorMessage.push('Email is required'); }
if (req.body.username === undefined || req.body.username.length === 0) { errorMessage.push('Username is required'); }
if (req.body.password === undefined || req.body.password.length === 0) { errorMessage.push('Password is required'); }
if (emailValidatior !== true) { errorMessage.push(emailValidatior); }
const passwordValidator = helper.passwordValidator(req.body.password);
if (passwordValidator !== true) { errorMessage.push(passwordValidator); }
if (req.body.firstName === undefined) {
if (req.body.password === undefined || req.body.password.length === 0) { errorMessage.push('Password is required'); }
const passwordValidator = helper.passwordValidator(req.body.password);
if (passwordValidator !== true) { errorMessage.push(passwordValidator); }
}
if (emailUsernameValidation !== true) { errorMessage.push(emailUsernameValidation); }
if (errorMessage.length) {
return res.status(400).json({ status: 400, errors: { body: errorMessage } });
Expand All @@ -56,6 +133,24 @@ class UserHelper {
return newUser;
}

/**
* Create a user signup validation
* @param {string} req - request body
* @param {string} res - response body
* @param {string} next - Allow to proceed execution
* @return {string} Returns an error or allow to proceed execution
* @static
*/
static async checkEmail(req, res, next) {
if (req.body.email) {
const email = await User.findOne({ where: { email: req.body.email } });
if (email) {
return res.status(400).json({ status: 400, errors: 'Email already in use' });
}
}
next();
}

/**
* Send verification email
* @function sendVerificationEmail
Expand Down Expand Up @@ -117,5 +212,110 @@ class UserHelper {
}
return userId;
}

/**
* Return one article
* @param {object} req - an object
*@return {object} Return article
*/
static async getOneUser(req) {
const user = await User.findOne({
where: { username: req.params.username },
attributes: [
'id',
'firstName',
'lastName',
'username',
'email',
'bio',
'image',
'roles',
'notification',
'createdAt',
'updatedAt'
]
});
return user;
}

/**
* Check if it is valid actiomn
* @param {object} req - an object
* @param {object} res - an object
* @param {object} next - an object
* @return {boolean} Returns if true if it is valid else return false
* @static
*/
static isValidAction(req, res, next) {
const validValues = ['enable', 'disable'];
if (validValues.indexOf(req.params.action) === -1) {
return res.status(422).send({ status: 422, Error: 'Only option must be enable or disable' });
}
next();
}

/**
* Check if action is already se
* @param {object} req - an object
* @param {object} res - an object
* @param {object} next - an object
* @return {res} Returns response
* @static
*/
static async isItAlreadySet(req, res, next) {
const { action, username } = req.params;
const user = await User.findOne({ where: { username } });
const isActive = action === 'enable';
if (user) {
if (isActive === user.isActive) {
return res.status(422).send({ status: 422, Error: 'Can not perform existing action' });
}
}
next();
}

/**
* Check if account is active
* @param {object} req - an object
* @param {object} res - an object
* @param {object} next - an object
* @return {res} Returns response
* @static
*/
static async isAccountActive(req, res, next) {
const user = await User.findOne({ where: { email: req.body.email } });
if (user) {
if (!user.isActive) {
return res.status(422).send({ status: 422, Error: ' Account disabled, please contact Administrator' });
}
}
next();
}

/**
* Return updated object
* @param {object} req - an object
* @param {object} res - an object
* @return {object} Return updated data
* @static
*/
static async enableOrDisableUser(req) {
const { action, username } = req.params;
const isActive = action === 'enable';
const updateUser = await User.update(
{
isActive
},
{ where: { username }, returning: true, plain: true }
);

const newUserUpdated = {
firstName: updateUser[1].firstName,
lastName: updateUser[1].lastName,
email: updateUser[1].email,
isActive: updateUser[1].isActive,
};
return newUserUpdated;
}
}
export default UserHelper;
6 changes: 3 additions & 3 deletions middlewares/roles.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@ class Role {
*/
static async isAdmin(req, res, next) {
const findUser = await RoleAccess.findOne(req.user.id);
if (findUser.roles !== roles.isUser || findUser.roles !== roles.isSuperAdmin) {
return res.status(401).json({ status: 401, message: 'You are not a super admin!' });
if (findUser.roles !== roles.isAdmin) {
return res.status(401).json({ status: 401, message: 'You are not an admin!' });
}
next();
}
Expand All @@ -32,7 +32,7 @@ class Role {
static async isSuperAdmin(req, res, next) {
const findUser = await RoleAccess.findOne(req.user.id);
if (findUser.roles !== roles.isSuperAdmin) {
return res.status(401).json({ status: 401, message: 'You are not an Admin!' });
return res.status(401).json({ status: 401, message: 'You are not a Super Admin!' });
}
next();
}
Expand Down
Loading

0 comments on commit f7eac6a

Please sign in to comment.