In my node application, I have an admin
that can make all requests and the normal user that has the right to make only certain requests.
example:
admin cans make:
post on /root, /user, /tools
simple users can make:
post on /users, /tools
If a simple user tries to make a request on /root
, he just receives and error message.
How can I handle this is node js? which package, if possible few examples.
thank
A general approach should be define a custom middleware to verify the authentication
function VerifyUser(req, res, next){
if(user.isAuthenticated){
return next(); //call the next middleware
}
next(err); //call the error middleware
}
error handler
app.use(function(err, req, res, next) {
if(!err) return next();
res.status(500).json(new Error('error happened'));
});
and then for each route that needs authentication bind the VerifyUser
middleware before the router middleware. Since in express the middleware order is relevant, VerifyUser
will be called at first, and if the branch reach the next()
call your routing function will be triggered.
Authenticated routes:
router.get('/root', VerifyUser, function(req, res){
//if you reach this point means the user has been granted the access
})
Non-authenticated routes:
router.get('/tools', function(req, res){
})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.