Does the user check the admin based on req.user?

I use a simple middleware function in my express.js application to check if the user has administrator rights:

 function isAdmin (req, res, next) { if (req.user.admin) return next(); res.redirect("/"); } 

passport used to authenticate an account.

Is this safe or can req.user.admin be entered into a query for users who should not have administrator rights? Should I first find the user and then check if the user has administrator rights? For instance:

 function isAdmin (req, res, next) { if (req.user) { User.findOne({ "_id" : req.user._id }, function (err, user) { if (err) { throw err; } else if (user.admin) { return next(); } else { res.redirect("/"); } }) } else { res.redirect("/"); } } 

To me this seems overly complicated. This will also lead to more access to the database. Is it necessary to check whether the user is really an administrator or is my first function? In essence, who can view or modify req and thus req.user ?

+6
source share
1 answer

I am new to the passport, but if it looks like express-session , the req.session object is stored in a (potentially encrypted) cookie, so if you create an authentication system, you can store user information in req.session.user and be sure that it is safe.

0
source

Source: https://habr.com/ru/post/972002/


All Articles