Skip to content

Instantly share code, notes, and snippets.

@IftekharDani
Last active April 10, 2018 11:17
Show Gist options
  • Save IftekharDani/253e4fa03985ea1b3a27fbbc75c96e67 to your computer and use it in GitHub Desktop.
Save IftekharDani/253e4fa03985ea1b3a27fbbc75c96e67 to your computer and use it in GitHub Desktop.
Node Js + express + MongoDb role-based permissions middleware.
const jwt = require('jwt-simple');
const jwtUtil = {};
jwtUtil.getAuthToken = (data) => {
return jwt.encode(data, process.env.JwtSecret);
};
jwtUtil.decodeAuthToken = (token) => {
if (token) {
try {
return jwt.decode(token, process.env.JwtSecret);
} catch (err) {
return false;
}
}
return false;
};
module.exports = jwtUtil;
const _ = require('lodash');
const jwt = require('../../../helper/jwt.js');
const User = require('./userModel'); //model to access mongodb model
const middleWare = {};
middleWare.loadUser = (...allowed) => {
return (req, res, next) => {
const { headers, byPassRoutes } = req;
if (!_.isEmpty(byPassRoutes)) {
if (_.includes(byPassRoutes, req.path)) {
next();
return;
}
}
if (_.isEmpty(headers.authorization)) { //check header
res.status(401).json({ error: req.t('ERR_UNAUTH') });
} else {
//validate jwt token
const decoded = jwt.decodeAuthToken(headers.authorization.replace('Bearer ', ''));
if (decoded) {
Admin.findOne({ _id: decoded.id })
.then((user) => {
if (user) {
//check role base access
const isAllowed = (role) => { return allowed.indexOf(role) > -1; };
if (isAllowed(user.role)) {
req.user = user;
next();// role is allowed, so continue on the next middleware
} else {
res.status(403).json({ message: 'Forbidden' }); // user is forbidden
}
} else {
res.status(401).json({ error: req.t('ERR_TOKEN_EXP') });
}
})
.catch((err) => {
logger.error(err);
res.status(401).json({ error: req.t('ERR_TOKEN_EXP') });
});
req.user = decoded;
} else {
res.status(401).json({ error: req.t('TOKEN_EXP') });
}
}
};
};
module.exports = middleWare;
const express = require('express');
const middleWare = require('./middleWare'); //middleware added in this file
const controller = require('./controller'); //controller to handle logic
const myRouter = express.Router();
//add middleware function in routing.
//Ex : access only for 'superAdmin'.
myRouter.get('/list', adminMiddleware.loadUser('superAdmin'), controller.list);
module.exports = myRouter;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment