Created
September 15, 2012 17:12
-
-
Save davybrion/3728895 to your computer and use it in GitHub Desktop.
code snippets for "Stop Storing Passwords Already!" post
This file contains 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 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'); |
This file contains 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 user = new User({ | |
name: 'test_user', | |
email: 'blah' | |
}); | |
user.setPassword('test'); | |
user.save(function(err, result) { | |
if (err) throw err; | |
}); |
This file contains 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
{ | |
"passwdHash" : "b604367796274cf64177eec345532fc6ca66c6f0501906f82bb03f7916265e9d", | |
"name" : "test_user", | |
"email" : "blah", | |
"_id" : ObjectId("4f1dbb2cfa6157b118000001"), | |
"salt" : "304a33f0-45fc-11e1-80d2-43c594a44fa0" | |
} |
This file contains 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 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