I am using connect-mysql-session to store sessions in db. Now my question is how do i add user data containing browser agent and ip-adress to check if the session is valid? How do i obtain that information? And how do i check if it matches?
users.login(credentials,function(err, results) {
//On errors
if (err) {
res.render(routes.index, {
title: 'Login'
});
//On success
} else if (results[0]) {
//Set session data and redirect to start page
req.session.userdata = results[0];
req.session.userdata.email = req.body.email_login;
req.session.is_logged_in = true;
res.redirect('/start');
//Wrong credentials
} else {
req.flash('warning','Wrong password or login');
res.render('index', {
title: 'Login'
});
}
});
Update:
I now got this added to the session:
req.session.ip = req.connection.remoteAddress;
req.session.useragent = req.headers['user-agent'];
and check for it in my auth middleware:
if(req.session.userdata && req.session.is_logged_in === true && req.session.ip === req.connection.remoteAddress && req.session.useragent === req.headers['user-agent']) {
next();
} else {
res.redirect('/');
}
Is this secure or do you see any risks with this? Should i go about it another way?
Your implementation looks good, and will give you some - very - basic protection against session hijacking.
However, I'm not sure I understand your middleware. What prevents an user from requesting /start
directly? And, more importantly, as the middleware intercepts all requests, even those for /start
, doesn't this look like some infinite redirect loop?
My suggestion would simply be to consider a user logged out at all time when ip or user agent mismatches.