问题
I'm trying to make a login in for my app using mongoose, passport-local, and bcrypt-nodejs.
The userSchema pre('save') function works fine and saves a hashed password. however the bcrypt compare method will return false every time.
see bcrypt-nodejs
here is my userSchema
var userSchema = mongoose.Schema({
login:{
local:{
email: {type: String, unique: true, required: true},
password: {type: String, unique: true, required: true}
}
}
userSchema.pre('save', function(next) {
bcrypt.hash('user.login.local.password', null, null, function(err, hash){
if(err){
next(err);
}
console.log('hash', hash);
user.login.local.password = hash;
next();
})
});
userSchema.methods.validPassword = function(password, cb){
bcrypt.compare(password, this.login.local.password, function(err, isMatch){
if(err) return cb(err);
cb(null, isMatch);
})
module.exports = mongoose.model('User', userSchema);
this works fine, and saves a new user with a hashed password
here is my my login strategy
no matter what info the user inputs, this will always return false
passport.use('local-login', new LocalStrategy({
usernameField: 'email',
passwordField: 'password',
passReqToCallBack: true
},
function(email, password, done){
User.findOne({ 'login.local.email' : email }, function(err, user){
if(err){
console.log(err);
return done(err);
}
if(!user){
console.log('no user found');
return done(err);
}
user.validPassword(password, function(err,match){
if(err){
console.log(err);
throw err;
}
console.log(password, match);
})
})
}))
lastly my route
app.post('/user/login', passport.authenticate('local-login'{
successRedirect: '/#/anywhereBUThere'
failureRedirect: '/#/'
}))
回答1:
Most likely the root of the problem is that the compare function is returning false because you are indeed comparing two non-identical hashes.
You appear to be passing in a string 'user.login.local.password' instead of the actual password in your userSchema pre save function:
e.g. this
bcrypt.hash('user.login.local.password', null, null, function(err, hash){
should be bcrypt.hash(user.login.local.password, null, null, function(err, hash){
(no single-quotes on the password being passed in as the first parameter.)
Additionally, you're then setting the generated hash to a 'user' object which seems to live outside of your user model. I can't see that code, but I suspect that you're not updating the value of the hash on the user model being saved to mongoDB.
e.g.
user.login.local.password = hash;
should probably be
this.login.local.password = hash;
来源:https://stackoverflow.com/questions/30494856/bcrypt-nodejs-compare-method-returns-false-every-time