bcrypt-nodejs比较方法每次都返回false
我试图使用mongoose,护照本地和bcrypt-nodejs来login我的应用程序。
userSchema预('保存')function正常工作,并保存一个哈希密码。 但是bcrypt比较方法每次都会返回false。
请参阅bcrypt-nodejs
这里是我的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);
这工作正常,并保存一个新的用户密码散列
这是我的login策略
无论用户input什么信息,这总是会返回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); }) }) }))
最后是我的路线
app.post('/user/login', passport.authenticate('local-login'{ successRedirect: '/#/anywhereBUThere' failureRedirect: '/#/' }))
最可能的问题的根源是比较函数返回false,因为你确实比较了两个不相同的散列。
你似乎传递一个string“ user.login.local.password ”,而不是你的userSchema预保存函数中的实际密码:
例如: bcrypt.hash('user.login.local.password', null, null, function(err, hash){
应该是bcrypt.hash(user.login.local.password, null, null, function(err, hash){
(密码中没有单引号作为第一个参数传入)
另外,你将生成的哈希值设置为一个“用户”对象,这似乎超出了你的用户模型。 我看不到那个代码,但是我怀疑你没有更新保存到mongoDB的用户模型的散列值。
例如user.login.local.password = hash;
应该可能是this.login.local.password = hash;