我正在尝试使用mongoose,passport-local和bcrypt-nodejs登录我的应用程序 .
userSchema pre('save')函数工作正常并保存哈希密码 . 但是bcrypt compare方法每次都会返回false .
这是我的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);
这样可以正常工作,并使用哈希密码保存新用户
这是我的登录策略
无论用户输入什么信息,这都将返回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: '/#/'
}))
1 回答
很可能问题的根源是compare函数返回false,因为您确实在比较两个不相同的哈希值 .
您似乎在传递了一个字符串'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;