DEV Community

Sateesh Madagoni
Sateesh Madagoni

Posted on

10 2

User Role Management in NodeJS, Express, MongoDB

Problem: Multiple users in a system, allowed to do specific actions.

Solution: There are multiple user role management packages in npm, but I want something easier, quicker. So I started solving it myself.

Example: A blog with users - U, authors - A, admin - M

  • Create users with a field user_type.
Users.create({
name: 'User',
user_type: 'U'
})
Users.create({
name: 'Author',
user_type: 'A'
})
Users.create({
name: 'Author',
user_type: 'M'
})
  • Assuming user logins managed using a jwt token. And sign the token including user_type, add a middleware to decode and save user data to req.user
const decoded = await jwt.verify(token, process.env.JWT_SECRET);
req.user = {
    name: decoded.name,
    user_type: decoded.user_type
};
  • Write another middleware to authenticate role.
const authenticateRole = (roleArray) => (req, res, next) => {
  if(!req.user) {
    return res.status(401).json({
      success: false,
      message: 'Session expired',
      code: 'SESSION_EXPIRED'
    });
  }
  const authorized = false;
//if user has a role that is required to access any API
  rolesArray.forEach(role => {
   authorized = req.user.user_type === role;
  })
  if(authorized) {
    return next();
  }
  return res.status(401).json({
    success: false,
    message: 'Unauthorized',
  })
}
  • Finally use the authenticateRole middleware in the API access.
//This is accessed by only Admin user
route.get('/users', authenticateRole(['M']), handler)
//This is accessed by anyone
route.get('/posts', authenticateRole(['M','U','A']))

I am trying to enhance this idea as my needs.

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more