DEV Community

Sateesh Madagoni
Sateesh Madagoni

Posted on

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.

Top comments (1)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.