意味着堆栈应用程序user.comparePassword不起作用

时间:2018-10-10 07:39:21

标签: javascript node.js mongodb

这是我的模型/user.js

var mongoose = require('mongoose');
var bcrypt = require('bcryptjs');

let emailLengthChecker = (email) => {
  if (!email) {
    return false;
  } else {
    if (email.length < 5 || email.length > 30) {
      return false;
    } else {
      return true;
    }
  }
};

let validEmailChecker = (email) => {
  if (!email) {
    return false;
  } else {
    // Regular expression to test for a valid e-mail
    const regExp = new RegExp(/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/);
    return regExp.test(email); // Return regular expression test results (true or false)
  }
};

const emailValidators = [{
  validator: emailLengthChecker,
  message: 'Email must be at least 5 characters but no more than 30 '
}, {
  validator: validEmailChecker,
  message: 'Must be a valid email'
}];

// Validate Function to check password length
let passwordLengthChecker = (password) => {
  // Check if password exists
  if (!password) {
    return false; // Return error
  } else {
    // Check password length
    if (password.length < 8 || password.length > 35) {
      return false; // Return error if passord length requirement is not met
    } else {
      return true; // Return password as valid
    }
  }
};

// Array of Password validators
const passwordValidators = [
  // First password validator
  {
    validator: passwordLengthChecker,
    message: 'Password must be at least 8 characters but no more than 35'
  }];

const UserSchema = mongoose.Schema({
  firstname: { type: String, require: true },
  lastname: { type: String, require: true },
  email: { type: String, require: true, unique: true, lowercase: true, validate: emailValidators },
  password: { type: String, require: true, validate: passwordValidators,select: false},
  active: { type: Boolean, required: true, default: false },
  temporarytoken: { type: String, required: true },
  resettoken: { type: String, required: false },
  //cnfpassword:{ type: String, required: false },
  creation_dt: { type: Date, require: true }
});



module.exports.getUserById = function (id, callback) {
  User.findById(id, callback);
}

module.exports.getUserByEmail = function (email, callback) {
  const query = { email: email }
  User.findOne(query, callback);
}

//module.exports.addUser = function(newUser, callback){
//bcrypt.genSalt(10, (err, salt) => {
//  bcrypt.hash(newUser.password, salt, (err, hash) => {
//    if(err) throw err;
//   newUser.password = hash;
//  newUser.save(callback);
// });
//});
// }
UserSchema.pre('save', function (next) {
  if (!this.isModified('password'))
    return next();

  bcrypt.hash(this.password, null, null, (err, hash) => {
    if (err) return next(err);
    this.password = hash;
    next();
  });
});


//User.methods.comparePassword = function (candidatePassword, hash, callback) {
 //bcrypt.compare(candidatePassword,this.password, hash, (err, isMatch) => {
 //if (err) throw err;
  // callback(null, isMatch);
 //});
//}
//UserSchema.methods.comparePassword = function(password) {
 // var user = this;

  //return bcrypt.compareSync(password, user.password);
//}

UserSchema.methods.comparePassword = function(candidatePassword) {
  if(this.password != null) {
      return bcrypt.compareSync(candidatePassword, this.password);
  } else {
      return false;
  }
};

const User = module.exports = mongoose.model('User', UserSchema);

在此模型中,我为注册激活链接输入了类似“ password:{type:String,require:true,validate:passwordValidators,select:false}”的密码。

这是我的route.js登录功能,

router.post('/authenticate',(req,res)=>{
   if(!req.body.email)
   {
    res.json({ success: false, message: 'No email was provided' }); // Return error
   }else {
    // Check if password was provided
    if (!req.body.password) {
      res.json({ success: false, message: 'No password was provided.' }); // Return error
    }else{
      User.findOne({ email: req.body.email.toLowerCase()},(err, user)=>{
        if(err){
          res.json({ success: false, message: err }); // Return error
        }else{
          if(!user)
          {
            res.json({ success: false, message: 'User not found.' }); // Return error
          }else{
            const validPassword =user.comparePassword(req.body.password); // Compare password provided to password in database
            if(!validPassword){
              res.json({ success: false, message: 'Password invalid' }); // Return error
            }else{
              res.json({ success:true, message:'Success!'});
            }
          }
        }
      });
    }
  }
});

user.comparePassword无法正常工作。我不知道我在哪里弄错了。如果有人知道,请帮助我

1 个答案:

答案 0 :(得分:0)

当我使用bcrypt来检查密码时,我更喜欢使用compare而不是compareSync。您可以尝试一下,看看是否可行:

module.exports.comparePassword = function(candidatePassword, this.password, callback){
    bcrypt.compare(candidatePassword,this.password, (err,isMatch)=>{
        if(err) throw err;
        callback(null, isMatch);
    })
}

并使用 U ser而不是用户

进行调用