Last active
August 29, 2015 14:10
-
-
Save myndzi/752ef36e64d3f25a4736 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var Promise = require('bluebird'); | |
var db = ... pg connection ... | |
var bcrypt = require('bcrypt'); | |
Promise.promisifyAll(db, { suffix: '$' }); | |
Promise.promisifyAll(bcrypt, { suffix: '$' }); | |
function hashPassword(plaintext) { | |
return bcrypt.genSalt$(10) | |
.then(function (salt) { | |
return bcrypt.hash$(plaintext, salt); | |
}); | |
} | |
function updatePassword(username, plaintext) { | |
return hashPassword(plaintext) | |
.then(function (hashed) { | |
return db.query$( | |
'UPDATE users SET password=? WHERE username=?', | |
[ hashed, username ] | |
); | |
}); | |
} | |
function getUser(username, plaintext) { | |
return db.query$( | |
'SELECT id, password FROM users WHERE username=? LIMIT 1', | |
[ username ] | |
).get(0).then(function (user) { | |
return bcrypt.compare$(plaintext, user.password); | |
.then(function (authenticated) { | |
if (!authenticated) { return null; } | |
return { | |
id: user.id | |
}; | |
}); | |
}); | |
}; | |
// login route, expects a form to submit 'username' and 'password' | |
app.post('/login', function (req, res) { | |
// req.params is filled by middleware like bodyParser | |
var username = req.params.username, | |
password = req.params.password; | |
getUser(req.params.username, req.params.password) | |
.then(function (user) { | |
if (user === null) { | |
res.send(401); // Unauthorized | |
return; | |
} | |
var token = jwt.sign(user, 'alina', { expiresInMinutes: 60*5 }); | |
res.json({ token: token }); | |
}) | |
.catch(function (err) { | |
res.send(500); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment