I'm using express and mysql and I'm trying to finish my login feature.
app.post('/login', function(req, res){
var username = req.body.username;
var password = sha1(req.body.password);
db.query("SELECT user_id, username FROM users WHERE username = '" + username + "' AND password = '" + password + "';", function(err, rows, fields){
if(rows.length > 0){
console.log("User " + username + " connected.");
req.session.user_id = rows[0].user_id;
}
});
});
As you can see, I make a query on the database and if the username and password match, (rows.length >0) I try to log the user in by adding his id in the session object.
The problem is that the req.session is only modified inside the callback and I can't find a way to do it globally... I tried to call a function login(id) but that didn't work either.
A little help would be nice, thanks.
The best way to authenticate users using a Mysql DB would be to add passport.js to the app.
See this repo for a full example : Node-Express-Passport-Mysql authentication.
If you can't get it to work, let me know and I'll post a full code sample when I'm home.
Ok, I tried passport but I think it was just too much to add to my application since I'm making something very small. I figured out a way to change the session object after the callback by using app.locale which is a global variable then by destroying it right after.
EDIT : here's how I did it :
if(rows.length > 0){
// Put the user_id and its username on a global var
app.locals.user_id = rows[0].user_id;
app.locals.username = rows[0].username;
res.redirect('/login');
console.log("User " + username + " connected.".green);
}
And when I have a POST request on /login
if(app.locals.user_id){
// Change the session object
req.session.user_id = app.locals.user_id;
req.session.username = app.locals.username;
}
I guess there are better ways to do it but it works anyway.