Skip to content

Instantly share code, notes, and snippets.

@davybrion
Created September 15, 2012 17:12
Show Gist options
  • Save davybrion/3728895 to your computer and use it in GitHub Desktop.
Save davybrion/3728895 to your computer and use it in GitHub Desktop.
code snippets for "Stop Storing Passwords Already!" post
var mongoose = require('mongoose'),
crypto = require('crypto'),
uuid = require('node-uuid'),
Schema = mongoose.Schema,
ObjectId = Schema.ObjectId;
var userSchema = new Schema({
name: { type: String, required: true, unique: true },
email: { type: String, required: true },
salt: { type: String, required: true, default: uuid.v1 },
passwdHash: { type: String, required: true }
});
var hash = function(passwd, salt) {
return crypto.createHmac('sha256', salt).update(passwd).digest('hex');
};
userSchema.methods.setPassword = function(passwordString) {
this.passwdHash = hash(passwordString, this.salt);
};
userSchema.methods.isValidPassword = function(passwordString) {
return this.passwdHash === hash(passwordString, this.salt);
};
mongoose.model('User', userSchema);
module.exports = mongoose.model('User');
var user = new User({
name: 'test_user',
email: 'blah'
});
user.setPassword('test');
user.save(function(err, result) {
if (err) throw err;
});
{
"passwdHash" : "b604367796274cf64177eec345532fc6ca66c6f0501906f82bb03f7916265e9d",
"name" : "test_user",
"email" : "blah",
"_id" : ObjectId("4f1dbb2cfa6157b118000001"),
"salt" : "304a33f0-45fc-11e1-80d2-43c594a44fa0"
}
var authenticate = function(username, password, callback) {
User.findOne({ name: username }, function(err, user) {
if (err) return callback(new Error('User not found'));
if (user.isValidPassword(password)) return callback(null, user);
return callback(new Error('Invalid password'));
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment