Skip to content

Commit

Permalink
Merge f1f0ade into cfedf00
Browse files Browse the repository at this point in the history
  • Loading branch information
kagabof committed Jul 30, 2019
2 parents cfedf00 + f1f0ade commit 607fe9b
Show file tree
Hide file tree
Showing 13 changed files with 318 additions and 122 deletions.
3 changes: 1 addition & 2 deletions src/config/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,4 @@ dotenv.config();
module.exports = { development: { use_env_variable: 'DEV_DATABASE_URL',
logging: false },
staging: { use_env_variable: 'DATABASE_URL', },
test: { use_env_variable: 'TEST_DATABASE_URL',
logging: false, } };
test: { use_env_variable: 'TEST_DATABASE_URL', } };
9 changes: 4 additions & 5 deletions src/controllers/bookmarksController.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,11 +29,10 @@ class BookmarksController {
try {
const article = await findArticle(req.params.articleId);

await ArticleOwner(req.params.articleId, req.user.id) && res.status(403).json({ error: 'Not allowed to bookmark your article' });
const bookmark = article && await Bookmarks.create({ userId: req.user.id,
articleId: article.dataValues.id });

bookmark ? res.status(201).json({ message: 'Article added to bookmarks' }) : res.status(404).json({ error: 'No Article found!' });
if (!article) return res.status(404).json({ error: 'No Article found!' });
if (await ArticleOwner(req.params.articleId, req.user.id)) return res.status(403).json({ error: 'Not allowed to bookmark your article' });
return (await Bookmarks.create({ userId: req.user.id,
articleId: article.dataValues.id })) && res.status(201).json({ message: 'Article added to bookmarks' });
} catch (error) {
return res.status(500).json({ error: 'Internal server error' });
}
Expand Down
37 changes: 34 additions & 3 deletions src/controllers/helpers/findUser.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,39 @@ const { User } = model;


const findUser = async (id) => {
const { dataValues } = await User.findOne({ where: { id } });
return dataValues || {};
const dataValues = await User.findOne({ where: { id } });
return dataValues;
};

export default findUser;
const findUserData = async (object) => {
const user = await User.findOne(object);
return user;
};

const findUserExist = async (username, email) => {
const check1 = username ? (!!(await findUserData({ where: { username } }))) : false;
const check2 = email ? (!!(await findUserData({ where: { email } }))) : false;
return { check1, check2 };
};

const updateUser = async (id, username, email, firstName,
lastName, bio, image, dateOfBirth, gender) => {
const userData1 = await findUserData({ where: { id } });

const user = await User.update({ username: username || userData1.dataValues.username,
email: email || userData1.dataValues.email,
firstName: firstName || userData1.dataValues.firstName,
lastName: lastName || userData1.dataValues.lastName,
bio: bio || userData1.dataValues.bio,
image: image || userData1.dataValues.image,
dateOfBirth: dateOfBirth || userData1.dataValues.dateOfBirth,
gender: gender || userData1.dataValues.gender }, { where: { id } });
return user;
};

export {
findUser,
findUserData,
findUserExist,
updateUser
};
2 changes: 1 addition & 1 deletion src/controllers/rolesController.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/* eslint-disable require-jsdoc */
import checkRole from './helpers/checkRole';
import findUser from './helpers/findUser';
import { findUser } from './helpers/findUser';
import model from '../models';

const { Permissions, User } = model;
Expand Down
18 changes: 14 additions & 4 deletions src/controllers/userController.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import models from '../models';
import tokenGen from '../helpers/tokenGenerator';
import bcrypt from '../helpers/hash';
import MailSender from '../helpers/mail';
import { findUserData } from './helpers/findUser';

const { User, Blacklist } = models;
const { generateToken, decodeToken } = tokenGen;
Expand Down Expand Up @@ -112,14 +113,23 @@ export default class UserController {
static async verifyUser(req, res) {
try {
const decode = await decodeToken(req.params.userToken);
if (!decode.email || decode.verified) {
return (!decode.email && res.status(409).json({ error: `Email:${decode.email} does not exist in the database` }))
|| (decode.verified && res.status(409).json({ error: 'Your account is already verified' }));
}
await User.update({ verified: true }, { where: { email: decode.email } });
return res.status(200).json({ message: 'Your account is now verified you can login with your email', });
} catch (error) {
return res.status(500).json(error.message);
}
}

static async deleteUser(req, res) {
try {
const { id } = req.params;
const userData = await findUserData({ where: { id } });
if (!userData) return res.status(404).json({ error: 'User does not exist' });
if (userData.dataValues.roles.includes('superAdmin')) return res.status(403).json({ error: 'Not allowed to delete super admin' });

return (await User.destroy({ where: { id } })) && res.status(200).json({ message: 'User successfully deleted' });
} catch (error) {
return res.status(500).json({ error: 'Server error!' });
}
}
}
41 changes: 27 additions & 14 deletions src/controllers/userProfile.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
/* eslint-disable no-else-return */
/* eslint-disable prefer-destructuring */
import models from '../models';
import { findUserData, findUserExist, updateUser } from './helpers/findUser';

const { User } = models;
/**
Expand Down Expand Up @@ -31,20 +32,32 @@ class UserProfile {
* @return {object} returns an object containing the updated user profile
*/
static async updateProfile(req, res) {
const { username } = req.params;
const { body } = req;
const getUsername = await User.findOne({ where: { username } });
// eslint-disable-next-line no-undef
if (!getUsername) {
return res.status(404).json({ message: `Username: ${username} does not exist` });
// eslint-disable-next-line no-else-return
} else if (req.body.id !== getUsername.dataValues.id) {
return res.status(404).json({ message: `UserId: ${req.body.id} cannot be amended, You can only amend your id` });
} else {
const updatedUser = await User.update({ ...body },
{ where: { id: req.body.id } });
return updatedUser.length
&& res.status(200).json({ user: { message: 'User updated sucessfully', updatedUser } });
try {
const userId = req.user.id;
const { id } = req.query;
const { username, email, firstName, lastName, bio, image, dateOfBirth, gender } = req.body;

if (userId) {
const userData = await findUserData({ where: { id: userId } });
if (!userData) return res.status(403).json({ error: 'User does not exist' });
if (userData.dataValues.roles.includes('superAdmin')) {
if (id === userId) return res.status(404).json({ error: 'Not allowed to update super admin' });
const userData1 = await findUserData({ where: { id } });
if (!userData1) return res.status(403).json({ error: 'User does not exist' });
const check = await findUserExist(username, email);
if (check.check1 || check.check2) return res.status(409).json({ error: 'email or username is already used' });
return updateUser(id, username, email, firstName, lastName, bio, image, dateOfBirth, gender) && res.status(200).json({ message: 'User successfully updated!' });
} else {
if (id === userId) return res.status(404).json({ message: 'Not allowed to update super admin' });
const userData1 = await findUserData({ where: { id: userId } });
if (!userData1) return res.status(403).json({ message: 'User does not exist' });
const check = await findUserExist(username, email);
if (check.check1 || check.check2) return res.status(409).json({ error: 'email or username is already used' });
return updateUser(userId, username, email, firstName, lastName, bio, image, dateOfBirth, gender) && res.status(200).json({ message: 'User successfully updated!' });
}
}
} catch (error) {
return res.status(500).json({ message: 'Server error!' });
}
}

Expand Down
12 changes: 1 addition & 11 deletions src/middlewares/User.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,16 +29,6 @@ const checkEmail = async (req, res, next) => {
}
};

const usernameAvailability = async (req, res, next) => {
const userConstant = await models.User.findOne({ where: { username: req.params.username }, });
// eslint-disable-next-line no-cond-assign
if (userConstant.dataValues.username !== req.params.username) {
return res.status(400).json({ status: 400,
message: 'This username is not available, Please choose another one!', });
}
next();
};

const usernameCheck = async (req, res, next) => {
// eslint-disable-next-line no-constant-condition
if (!req.params.username || !(/^[A-Za-z_-]+$/.test(req.params.username))) {
Expand All @@ -51,6 +41,6 @@ const usernameCheck = async (req, res, next) => {
export {
checkEmail,
decodeResetPasswordToken,
usernameAvailability,
// usernameAvailability,
usernameCheck
};
10 changes: 6 additions & 4 deletions src/routes/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import express from 'express';
import UserController from '../controllers/userController';
import AuthController from '../controllers/authController';
// middlwares
import { decodeResetPasswordToken, checkEmail, usernameAvailability, usernameCheck } from '../middlewares/User';
import { decodeResetPasswordToken, checkEmail, usernameCheck } from '../middlewares/User';
import { bodyValidation, signinValidation } from '../middlewares/bodyValidation';
import socialRoute from './socialTestRoute';
import UserProfile from '../controllers/userProfile';
Expand All @@ -19,6 +19,8 @@ import bookmarkRoute from './bookmarksRoutes';
import readerStatsRoute from './readerStatsRoute';
import reportArticle from './ReportRoute';
import role from './roleRoutes';
import checkAction from '../middlewares/roleCheck';


const { verifyToken } = Auth;

Expand Down Expand Up @@ -46,13 +48,13 @@ router.post('/api/users/passwordreset/:token', decodeResetPasswordToken, checkEm
router.post('/api/users/logout', verifyToken, UserController.signOut);

router.get('/api/user/:username', usernameCheck, UserProfile.getProfile);
router.patch('/api/users/:username', verifyToken, bodyValidation, usernameAvailability, UserProfile.updateProfile);
router.get('/api/allusers/', verifyToken, UserProfile.getAllUser);
router.post('/api/users/login', signinValidation, AuthController.signin);
router.patch('/api/users/verification/:userToken', UserController.verifyUser);

router.patch('/api/users/:username', verifyToken, bodyValidation, usernameAvailability, UserProfile.updateProfile);
router.get('/api/users/', verifyToken, UserProfile.getAllUser);
router.patch('/api/users', verifyToken, UserProfile.updateProfile);
router.get('/api/users', verifyToken, UserProfile.getAllUser);

router.delete('/api/users/:id', verifyToken, checkAction('User'), UserController.deleteUser);

export default router;
2 changes: 0 additions & 2 deletions src/routes/roleRoutes.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,6 @@ const role = express.Router();

const { verifyToken } = Auth;

// role.use('/', );

role.post('/role', verifyToken, checkAction('Permissions'), roles.createRole);
role.delete('/role', verifyToken, checkAction('Permissions'), roles.deleteRole);
role.get('/role', verifyToken, checkAction('Permissions'), roles.getAllRoles);
Expand Down
15 changes: 15 additions & 0 deletions src/test/bookmarksTest.js
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,21 @@ describe('Article', () => {
});
});

it('it should not bookmark a bad article', (done) => {
const article = { title: 'hello man, how was the night',
body: 'hello man, how was the night',
description: 'hello man, how was the night' };
chai.request(app)
.post('/api/bookmarks/100')
.set('token', tokens1)
.send(article)
.end((req, res) => {
res.should.have.status(404);
res.body.should.be.an('object');
done();
});
});

it('it should find all bookmarks', (done) => {
const article = { title: 'hello man, how was the night',
body: 'hello man, how was the night',
Expand Down
30 changes: 30 additions & 0 deletions src/test/roleTest.js
Original file line number Diff line number Diff line change
Expand Up @@ -145,4 +145,34 @@ describe('role', () => {
done();
});
});

it('should not delete with bad role', (done) => {
const role = { tablesAllowed: 'Articles,User',
role: 'adminsdfwad',
actions: 'GET' };
chai.request(app)
.delete('/api/role')
.set('token', tokenGen)
.send(role)
.end((req, res) => {
res.should.have.status(401);
res.body.should.have.property('error');
done();
});
});

it('should delete with admin token', (done) => {
const role = { tablesAllowed: 'Articles,User',
role: 'admin',
actions: 'GET' };
chai.request(app)
.delete('/api/role')
.set('token', tokenGen)
.send(role)
.end((req, res) => {
res.should.have.status(200);
res.body.should.have.property('message');
done();
});
});
});
Loading

0 comments on commit 607fe9b

Please sign in to comment.