user.comparePassword不是函数

时间:2019-01-18 13:40:35

标签: express mongoose bcrypt

我在使用bcrypt-nodejs,nodeJS(expressJS)和mongoose进行哈希密码验证时遇到了麻烦。用户可以注册并通过代码生成哈希密码,但是当我尝试使用登录页面中的comparePassword函数验证该密码时,该密码无法正常工作,并显示错误user.comparePassword is not a function

代码如下:

数据库:

UserSchema.pre('save', async 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,null, function(err,hash){
       if(err) return next(err)

       user.password = hash
       next()
    })


})

})

UserSchema.methods.comparePassword = async function(candidatePassword, cb){
bcrypt.compare(candidatePassword, this.password, function(err, isMatch){
  if(err) return cb(err);
  cb(null, isMatch)
 })
}

路线:

router.post('/', async (req, res) => {
try {
const {username, password} = req.body;

const user = await User.findOne({username}).lean();


if (!user) {
  return res.status(404).send({
    message: 'user is not registered'
  });
}
if(username.trim().length < 1 && password.trim().length < 1){
  return res.status(409).send({message: 'username & password is required'})
}




  // if (user.password !== password) {
  // return res.status(403).send({
  //  message: 'user password invalid'
  //});
  //}



    user.comparePassword(password, function(err, isMatch){
    if(err){
      return res.status(500).send({message: err.message})
    }

    if(!isMatch){
      return res.status(403).send({
        message: 'user password invali'
      });
    }

    req.session.user = user;

    const redirectTo = '/dashboard';

    if (
      req.is('application/json') // request content type is json
      || // or
      req.xhr // is ajax
    ) {
      // respond with json response
      return res.status(200).send({redirectTo});
    }

    // not ajax request
    // then respond redirect header
    res.redirect(redirectTo);


  })

1 个答案:

答案 0 :(得分:-1)

const mongoose = require('mongoose');
var bcrypt = require('bcrypt-nodejs');
SALT_WORK_FACTOR = 10;

const userDataModal = mongoose.Schema({
    username: {
        type: String,
        required : true,
        unique:true
    },
    password: {
        type: String,
        required : true
    }

});

userDataModal.pre('save', function(next) {
    var user = this;

    // only hash the password if it has been modified (or is new)
    if (!user.isModified('password')) return next();

    // generate a salt
    bcrypt.genSalt(SALT_WORK_FACTOR, function(err, salt) {
        if (err) return next(err);

        // hash the password using our new salt
        bcrypt.hash(user.password, salt, null, function(err, hash) {
            if (err) return next(err);

            // override the cleartext password with the hashed one
            user.password = hash;
            next();
        });
    });
});

userDataModal.methods.comparePassword = function(candidatePassword, cb) {
    bcrypt.compare(candidatePassword, this.password, function(err, isMatch) {
        if (err) return cb(err);
        cb(null, isMatch);
    });
};


// Users.index({ emaiId: "emaiId", fname : "fname", lname: "lname" });

const userDatamodal = module.exports = mongoose.model("usertemplates" , userDataModal)



//inserting document
     userDataModel.findOne({ username: reqData.username }).then(doc => {
            console.log(doc)
            if (doc == null) {
                let userDataMode = new userDataModel(reqData);
               // userDataMode.password = userDataMode.generateHash(reqData.password);
                userDataMode.save({new:true}).then(data=>{
                          let obj={
                              success:true,
                              message: "New user registered successfully",
                              data:data
                          }
                            resolve(obj)
                }).catch(err=>{
                                reject(err)
                })

            }
            else {
                resolve({
                    success: true,
                    docExists: true,
                    message: "already user registered",
                    data: doc
                }
                )
            }

        }).catch(err => {
            console.log(err)
            reject(err)
        })

//retriving and checking
      // test a matching password
                user.comparePassword(requestData.password, function(err, isMatch) {
                    if (err){ 

                        reject({
                            'status': 'Error',
                            'data': err
                        });

                        throw err;
                    } else  {
                        if(isMatch){

                            resolve({   
                                'status': true,
                                'data': user,
                                'loginStatus' : "successfully Login"
                            });

                            console.log('Password123:', isMatch); // -&gt; Password123: true

                        }