Monday, 22 April 2019

How to create user group security for REST API using middleware

In order to secure REST API I'm using middleware to check for user's JWT token and only allow that particular user to access his own data.

In auth.js

const jwt = require('jsonwebtoken')
const User = require('../models/user')

const auth = async (req, res, next) => {
    try {
        const token = req.header('Authorization').replace('Bearer ', '')
        const decoded = jwt.verify(token, process.env.JWT_SECRET)
        const user = await User.findOne({ _id: decoded._id, 'tokens.token': token })

        if (!user) { // If no user is found
            throw new Error()
        }

        // if there's a user
        req.token = token
        req.user = user
        next()
    } catch (e) {
        res.status(401).send({ error: 'Please authenticate.' })
    }
}

module.exports = auth

In one of the get/update router

router.get('/itemShipmentStatus', auth, async (req, res) => {
   // Get the items shipment status from db.
})

However, I've noticed I need to create a new admin user (e.g. admin 1, admin2) to get and update the itemShipmentStatus for all the users. Is there a way to achieve user group authentication through the middleware (auth.js?)

Update:

The only solution I can think of is to add another "userGroup" field to the user document when creating a new user. Then in the middleware auth.js add in another condition to check if the user belongs to the admin group.

if (!user || user.userGroup !== 'Admin') { // If no user is found
    throw new Error()
}

Is this the conventional way of doing it?



from How to create user group security for REST API using middleware

No comments:

Post a Comment