【发布时间】:2015-08-10 06:29:33
【问题描述】:
我正在尝试使用 mongoose、passport-local 和 bcrypt-nodejs 登录我的应用程序。
userSchema pre('save') 函数可以正常工作并保存散列密码。但是 bcrypt compare 方法每次都会返回 false 。
这是我的用户架构
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: '/#/'
}))
【问题讨论】:
标签: javascript node.js mongoose bcrypt