Should I access user data from DB or req.user?

Viewed 23

I'm currently making a website just to improve my coding and I was wondering how I should access user data while making a profile page for users.

Here's how my userDetails controller look but I feel like this is not very safe because I am also accessing user from session req.user in my middleware.

module.exports.userDetails = async (req,res,next) => {

const {username} = req.params;
const user = await User.findOne({username}).populate({path: 'campgrounds'})
console.log(user)
if(!user){
    req.flash('error', 'Cannot access that username.')
    return res.redirect('/campgrounds')
}
res.render('users/details.ejs', {user})
}

and here's how my middleware looks.

app.use((req,res,next) => {

res.locals.currentUser = req.user;
res.locals.currentUserDetails = req.user._doc;


  res.locals.success = req.flash('success');
   res.locals.error = req.flash('error');
   next();
})

I would be happy if you could give me some suggestions. Because if I access from database with a query that sounds like anyone can reach it if I'm not wrong.

0 Answers
Related