I made my own login system in nodejs and I have couple question about that.
To check user login I make this:
function loadUser (req, res, next) {
// Check user_id
if (req.session.user_id) {
// Is there in db
User.findById({_id: req.session.user_id}, function (err, user) {
if (user) {
req.currentUser = user;
next();
} else {
res.redirect('/login');
}
});
}
}
app.get('/secure', loadUser, function (req, res) {
res.render('secure.jade', {user: req.currentUser});
});
how safe is it? Can a hacker to pick up a session key? And are there best practice to make this approach better
Well if the hacker steals the cookie of the user he can impersonate him, but that’s the case for many websites. You shouldn’t worry to much about that though.
Also, it’s better to have the username remembered along with the user_id, no point in making two queries over the time.