Skip to content
This repository has been archived by the owner on May 9, 2021. It is now read-only.

Commit

Permalink
Merge 27a7e0a into 180a973
Browse files Browse the repository at this point in the history
  • Loading branch information
KvNGCzA committed Nov 9, 2018
2 parents 180a973 + 27a7e0a commit 35c06b0
Show file tree
Hide file tree
Showing 11 changed files with 194 additions and 124 deletions.
61 changes: 54 additions & 7 deletions server/controllers/UsersController.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import cloudinary from 'cloudinary';
import models from '../models';
import sendEmail from '../helpers/sendEmail';
import verifyEmailMessage from '../helpers/verifyEmailMessage';
import { createToken } from '../helpers/tokenUtils';
import { createToken } from '../middlewares/tokenUtils';
import cloudinaryConfig from '../config/cloudinaryConfig';

cloudinary.config(cloudinaryConfig);
Expand Down Expand Up @@ -35,7 +35,10 @@ class UsersController {
})
.then((user) => {
const token = createToken(user.id, lifeSpan);
sendEmail(user, verifyEmailMessage(token));
sendEmail(
user,
verifyEmailMessage(token)
);
res.status(201).json({
status: 'success',
message: 'New user created successfully',
Expand All @@ -53,8 +56,8 @@ class UsersController {
})
.catch(err => res.status(500)
.json({
error: {
message: err.message,
errors: {
message: [err.message]
},
}));
}
Expand Down Expand Up @@ -101,9 +104,9 @@ class UsersController {
});
}
})
.catch(error => res.status(500).json({
.catch(err => res.status(500).json({
errors: {
message: ['error reading user table', `${error}`]
message: [err.message]
}
}));
}
Expand All @@ -118,7 +121,7 @@ class UsersController {
static async updateProfile(req, res, next) {
// check if request token id matches id of account to be updated
const { userId } = req.params;
const { id } = res.locals.payload;
const { id } = req.userData;
if (id !== parseInt(userId, 10)) {
const error = new Error('can\'t update another user\'s profile');
error.status = 403;
Expand Down Expand Up @@ -179,6 +182,50 @@ class UsersController {
};
updateProfile();
}

/**
* @description - This method logs in user and return a token.
* @param {object} req - The request object bearing the email and password.
* @param {object} res - The response object that is returned as json.
* @returns {object} - The json object with message.
* @memberOf UserController
* @static
*/
static verifyUser(req, res) {
const { id } = req.userData;
User
.findByPk(id)
.then((user) => {
if (user.confirmEmail) {
return res.status(403).json({
errors: {
message: ['user already verified']
}
});
}
User
.update(
{ confirmEmail: true },
{ where: { id } }
)
.then(() => res.status(200).json({
status: 'success',
message: 'user successfully verified'
}))
.catch(err => res.status(500)
.json({
errors: {
message: [err.message]
}
}));
})
.catch(() => res.status(404)
.json({
errors: {
message: ['user does not exist']
}
}));
}
}

export default UsersController;
31 changes: 0 additions & 31 deletions server/helpers/tokenUtils.js

This file was deleted.

12 changes: 8 additions & 4 deletions server/helpers/verifyEmailMessage.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,17 @@
import dotenv from 'dotenv';

dotenv.config();
/**
* @description verifyEmailMessage contains the email message template
* @param {string} token - The token generated for the user
* @returns {object} - contains the mail message template
*/

const verifyEmailMessage = (token) => {
if (token === undefined || token === '') {
const err = new Error('token is invalid');
err.status = 401;
const err = { errors: {} };
if (token === undefined || token.trim() === '') {
err.errors.token = ['please provide a token'];
} if (Object.keys(err.errors).length > 0) {
return err;
}
return {
Expand All @@ -16,7 +20,7 @@ const verifyEmailMessage = (token) => {
`<div style="height: 20em, background-color: #E6FFED;
border: 1px solid black; padding: 0.5em;">
<p>
<a href="http://localhost:3001/api/test/verify?token=${token}">
<a href="${process.env.API_BASE_URL}/users/verify?token=${token}">
<strong>
CLICK HERE!
</strong>
Expand Down
43 changes: 43 additions & 0 deletions server/middlewares/tokenUtils.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import dotenv from 'dotenv';
import jwt from 'jsonwebtoken';

dotenv.config();

const secret = process.env.JWT_SECRET;

/**
*
* @param {integer} id - The id of the user
* @param {integer} lifeSpan - The the lifespan of the token
* @returns {void}
*/
export const createToken = (id, lifeSpan) => jwt
.sign({ id }, secret, { expiresIn: lifeSpan });


/**
* This middleware protects a route from access without a token
* sets the payload in res.locals
* @param {object} req - express request object
* @param {object} res - express response object
* @param {object} next - express next to pass to next middleware
* @returns {void}
*/
export const verifyToken = (req, res, next) => {
const token = req.headers.authorization || req.query.token;
if (!token) {
return res.status(401).json({
status: 'unauthorized',
message: 'please provide a token'
});
}
try {
req.userData = jwt.verify(token, secret);
next();
} catch (error) {
return res.status(401).json({
status: 'unauthorized',
message: 'invalid token!'
});
}
};
23 changes: 0 additions & 23 deletions server/middlewares/verifyJWT.js

This file was deleted.

9 changes: 4 additions & 5 deletions server/models/user.js
Original file line number Diff line number Diff line change
Expand Up @@ -52,14 +52,13 @@ export default (sequelize, DataTypes) => {
});

User.associate = (models) => {
const { Article } = models;
const { Article, Role } = models;
User.hasMany(Article, {
foreignKey: 'userId'
});
};
User.associate = (models) => {
const { Role } = models;
User.belongsTo(Role, { foreignKey: 'roleId' });
User.belongsTo(Role, {
foreignKey: 'roleId'
});
};
return User;
};
14 changes: 10 additions & 4 deletions server/routes/api/users.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,19 @@ import express from 'express';
import UserValidation from '../../middlewares/UserValidation';
import UserController from '../../controllers/UsersController';
import facebookPassportRoutes from '../../config/facebookPassportRoutes';
import verifyJWT from '../../middlewares/verifyJWT';
import { verifyToken } from '../../middlewares/tokenUtils';

const {
validateUserSignUp,
checkExistingEmail,
validateUserLogin,
validateUserUpdate,
} = UserValidation;

const {
userLogin,
signUp,
updateProfile,
verifyUser,
updateProfile
} = UserController;

const router = express.Router();
Expand All @@ -27,22 +27,28 @@ router.get('/', (req, res) => {
status: 200
});
});

// sign up route
router.post(
'/users/signup',
validateUserSignUp, checkExistingEmail, signUp
);
// login with email and password
router.post(
'/users/login',
validateUserLogin, userLogin
);

// verify users email
router.get('/users/verify', verifyToken, verifyUser);

// signup or login with facebook
router.get('/auth/facebook', facebookPassportRoutes.authenticate());

// facebook callback route
router.get('/auth/facebook/callback', facebookPassportRoutes.callback());

// update profile route
router.patch('/users/:userId', verifyJWT, validateUserUpdate, updateProfile);
router.patch('/users/:userId', verifyToken, validateUserUpdate, updateProfile);

export default router;
Loading

0 comments on commit 35c06b0

Please sign in to comment.