I'd like to know what is the best way to get the current logged user from anywhere in my code (controllers, models...). The best way I've found to do that so far is to set the user data in the middleware used for authentication:
const requireAuth = (req, res, next) => {
const token = req.cookies.jwt;
// Check if a jwt token does exist and is verified.
if (token) {
jwt.verify(token, config.token_secret, async (err, decodedToken) => {
if (err) {
res.locals.user = null;
res.redirect('/login');
}
else {
let user = await User.findById(decodedToken.id);
// Inject the current user data into the view.
res.locals.currentUser = user;
// To get the current user from anywhere .
req.currentUser = user;
next();
}
});
}
else {
res.locals.user = null;
res.redirect('/login');
}
};
Is it a good practice or is there another way to do that ?