Skip to content

Instantly share code, notes, and snippets.

/stuff.js Secret

Created January 25, 2014 20:46
Show Gist options
  • Save anonymous/0ea4963391498b35ce96 to your computer and use it in GitHub Desktop.
Save anonymous/0ea4963391498b35ce96 to your computer and use it in GitHub Desktop.
Code, that is responsible for logging users in and maintaining their session:
/////////////////////////////////////////
// FILE 1: a route handler called "login"
/////////////////////////////////////////
module.exports = function(req, res) {
/* removed meaningless anti-bruteforce code from this sector */
if (req.params.logout) {
// handle loging the user aout
req.session.account = null;
req.session.user = null
delete req.session.account;
delete req.session.user;
res.redirect('/');
return;
}
/* removed hard-coded IP bans from sector */
if (req.body.username && req.body.password) {
// if the FORM was posted, then call the exchange.login method
exchange.login(req.body.username, req.body.password, function(err, user) {
if (err) {
// login failed, redirect
res.redirect('/');
}
else { // <- this means that exchange.login method called the callback without an error
// login OK, set session data and redirect
req.session.account = user.id.toString();
req.session.user = user;
res.redirect('/');
}
}, req /* pass connection to login handler */);
}
else {
// no login data in POST, redirect to /
res.redirect('/');
}
};
/////////////////////////////////////////
// FILE 2: a method called exchange.login
/////////////////////////////////////////
Exchange.prototype.login = function(username, password, callback, request) {
// salt password to protect from rainbow attack on a leaked database
password = this.saltPassword(username, password);
// hash it with SHA-1 to check against the database
password = crypto.createHash('sha1').update(password).digest("hex");
this.numLogins++; // increment login counter for stats
var exchange = this;
var query = 'SELECT * FROM accounts WHERE username = ? AND password = ?';
db.query(query, [username, password], function(err, rows) {
// if the database query returns error or no rows, then:
if (err || !rows || !rows.length) {
callback(err.toString());
return; // EXECUTION STOPS HERE
}
// code below executes only when a match was found (a row returned from the database)
var user = rows[0];
db.query('INSERT INTO logins VALUES (NULL, ?, ?, NOW())', [user.id, request.connection.remoteAddress]);
callback(null, user); // pass control back to the route handler (FILE 1)
exchange.numLoginsSuccess++; // increment successful login counter for stats
});
}
/////////////////////////////////////////
How do we check if an user is logged in?
We simply check for the session variables in every handler.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment