Skip to content

Commit

Permalink
feat(verification):Implement user verification
Browse files Browse the repository at this point in the history
- Write a verification function to verify user token
- Write a verification function to verify admin token
  • Loading branch information
amaechi-chuks committed Apr 2, 2019
1 parent 9bbc57b commit ee13163
Showing 1 changed file with 58 additions and 0 deletions.
58 changes: 58 additions & 0 deletions server/helpers/validations.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import Joi from 'joi';
import Authenticate from './auth';

const validations = {
/**
Expand All @@ -17,6 +18,63 @@ const validations = {
}
return true;
},
verifyAuthHeader(req) {
if (!req.headers.authorization) {
return { error: 'error' };
}
const token = req.headers.authorization;
const payload = Authenticate.decode(token);
if (!payload) {
return { error: 'token' };
}
return payload;
},

/**
* @method verifyUser
* @description Verifies the token provided by the user
* @param {*} req
* @param {*} res
* @returns {*} - JSON response object
*/

verifyUser(req, res, next) {
const payload = validations.verifyAuthHeader(req);
let error;
let status;
if (!payload || payload === 'error') {
status = 401;
error = 'You are not authorized';
}
if (payload.error === 'token') {
status = 403;
error = 'Forbidden';
}
if (error) {
return res.status(status).json({ status, error });
}
req.user = payload;
return next();
},
/**
* @method verifyAdmin
* @description Verifies the token provided by the Admin
* @param {*} req
* @param {*} res
* @param {*} next
* @returns {*} - JSON response object
*/
verifyAdmin(req, res, next) {
const payload = validations.verifyAuthHeader(req);
const { isadmin } = payload;
if (isadmin !== true) {
return res.status(401).json({
status: 401,
error: 'You are not authorized to access this endpoint.',
});
}
return next();
},
};

export default validations;

0 comments on commit ee13163

Please sign in to comment.