I am trying to authenticate a Node.js API with JSON Web Tokens. I could generate the token authenticate the users. Now I need to proptect my API based on the user roles. Here is how I route middleware to authenticate and check token.
var app = express();
var apiRoutes = express.Router();
apiRoutes.use(function (req, res, next) {
var token = req.body.token || req.param('token') || req.headers['x-access-token'];
if (token) {
jwt.verify(token, app.get('superSecret'), function (err, decoded) {
if (err) {
return res.json({ success: false, message: 'Failed to authenticate token.' });
} else {
req.decoded = decoded;
next();
}
});
} else {
return res.status(403).send({
success: false,
message: 'No token provided.'
});
}
});
apiRoutes.get('/check', function (req, res) {
//...
});
app.use('/api', apiRoutes);
This way, I protect the API say /api/check
. This can be accessed by admin user
only. Now I have another super user
who can access /api/validate
which the admin user
can't access. How can I protect /api/validate
only for super user
. Do I need to write one more middleware to do this?
Here is how I do the admin check now,
apiRoutes.post('/delete/:id',requireAdmin, function (req, res) {
//do the rest
};
function requireAdmin(req, res, next) {
var currentUserRole=".."; //get current user role
if('admin' == currentUserRole )
{
next();
}
else{
next(new Error("Permission denied."));
return;
}
};
Similarly requireSuperUser
function for super user check.Is this the right way to do admin/super user check?