Created
February 13, 2015 18:21
-
-
Save cahlan/15a3b7c07c9dbbd01b92 to your computer and use it in GitHub Desktop.
demonstration of schema methods and bcrypt
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
//User, pseudo code!!!!! | |
var userSchema = { | |
name: String, | |
email: String, | |
password: String, | |
gender: String, | |
bio: String, | |
createdAt: Date, | |
age: {type: Number, min: 0, max: 99} | |
}; | |
var bcrypt = require('bcrypt'); | |
userSchema.pre('save', function(next) { | |
var user = this; | |
if (!user.isModified('password')) { | |
return next(); | |
} | |
bcrypt.genSalt(12, function(err, salt) { | |
if (err) { | |
return next(err); | |
} | |
bcrypt.hash(user.password, salt, function(err, hash) { | |
if (err) { | |
return next(err); | |
} | |
user.password = hash; | |
next(); | |
}); | |
}); | |
}); | |
var q = require('q'); | |
userSchema.methods.comparePassword = function(pass) { | |
var deferred = q.defer(); | |
bcrypt.compare(pass, this.password, function(err, isMatch) { | |
if (err) { | |
deferred.reject(err); | |
} | |
else { | |
deferred.resolve(isMatch) | |
} | |
}); | |
return deferred.promise; | |
}; | |
//inside a controller ... pseudo code!!!!! | |
User.findOne({email: req.body.email}).exec().then(function(err, user) { | |
if (user) { | |
user.comparePassword(req.body.password).then(function(isMatch) { | |
if (isMatch) { | |
req.session.authed = true; | |
} | |
else { | |
return res.redirect('/login'); | |
} | |
}) | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment