我正在使用基于此演示http://devsmash.com/blog/password-authentication-with-mongoose-and-bcrypt的密码验证,由于某种原因,该方法未附加到我的“用户”返回,导致错误
这是我的代码......
module.exports = function (app, mongoose, config, passport) {
var bcrypt = require('bcrypt')
var SALT_WORK_FACTOR = 10;
var UserSchema = new mongoose.Schema({
name: { type: String },
password: { type: String, required: true },
email: {
type:String,
lowercase: true,
required: true,
unique: true
}
});
var _User = mongoose.model('user', UserSchema);
// Bcrypt middleware
UserSchema.pre('save', function(next) {
var user = this;
if(!user.isModified('password')) return next();
bcrypt.genSalt(SALT_WORK_FACTOR, 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();
});
});
});
// Password verification
UserSchema.methods.comparePassword = function(candidatePassword, cb) {
bcrypt.compare(candidatePassword, this.password, function(err, isMatch) {
if(err) return cb(err);
cb(null, isMatch);
});
};
return {
User : _User,
isValidUserPassword : function(auth, done) {
_User.findOne({email : auth.body.username}, function(err, user){
// if(err) throw err;
if(err) return done(err);
if(!user) return done(null, false, { message : 'Incorrect email.' });
user.comparePassword(auth.body.password, function(err, isMatch) {
if (err) throw err;
console.log('Password123:', isMatch); // -> Password123: true
});
});
}
}
}
答案 0 :(得分:1)
您的代码存在的问题是它调用
var _User = mongoose.model('user', UserSchema);
在定义UserSchema.pre
挂钩和UserSchema.methods.comparePassword
方法之前。
在定义架构后调用mongoose.model
,事情就会起作用:
// Bcrypt middleware
UserSchema.pre('save', function(next) {
var user = this;
if(!user.isModified('password')) return next();
bcrypt.genSalt(SALT_WORK_FACTOR, 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();
});
});
});
// Password verification
UserSchema.methods.comparePassword = function(candidatePassword, cb) {
bcrypt.compare(candidatePassword, this.password, function(err, isMatch) {
if(err) return cb(err);
cb(null, isMatch);
});
};
var _User = mongoose.model('user', UserSchema);