node.js bcrypt比较即使在我哈希之后也返回false

时间:2018-07-14 05:15:32

标签: node.js hash bcrypt

我已经尝试了至少三个小时,但还是不明白。

我的node.js应用依赖项

"dependencies": {
  "bcrypt": "^3.0.0",
  "bluebird": "^3.5.1",
  "body-parser": "^1.18.3",
  "cors": "^2.8.4",
  "express": "^4.16.3",
  "jsonwebtoken": "^8.3.0",
  "morgan": "^1.9.0",
  "mysql2": "^1.5.3",
  "sequelize": "^4.38.0",
  "sqlite": "^2.9.2"
}

这是我的bcrypt代码:

const Promise = require('bluebird')
const bcrypt = Promise.promisifyAll(require('bcrypt'))

function hashPassword (user , options) {
  if(!user.changed('password')){
    return;
  }
  const saltRounds = 10 
  return bcrypt.hash(user.password, saltRounds).then( hash => {
    user.setDataValue('password', hash)
    bcrypt.compare(user.password, hash, function(err, result) {
      if (err) { throw (err); }
      console.log(result);
    });
  });
}

module.exports = (sequelize, Datatypes) =>{
  const User = sequelize.define('User', {
    email:{
      type:Datatypes.STRING,
      unique: true
    },
    password:Datatypes.STRING
  }, {
    hooks:{
      beforeCreate: hashPassword,
      beforeUpdate: hashPassword,
      beforeSave: hashPassword
    }
  })

  User.prototype.comparePassword = function(password) {
    return bcrypt.compare(password, this.password)
  }

  return User
}

插入新用户后,它将返回User.toJSON,如下所示:

{
    "id": 5,
    "email": "zxc@gmail.com",
    "password": "$2b$10$nr51wOKQaXkejeku2CnLrOtodhrJoNxLdHaHB/keNH5PbtVLdBAKe",
    "updatedAt": "2018-07-14T05:02:22.764Z",
    "createdAt": "2018-07-14T05:02:22.764Z"
}

我认为它运行良好,因为我们可以看到密码已成功散列(顺便说说60个字符)

但是请注意,我在user.setDataValue之后使用bcrypt.compare函数

并且console.log(result)为false ...

甚至在我每次尝试登录时都没有提及,我的User.prototype.comparePassword(password)总是也返回false!

请帮帮我,谢谢!

1 个答案:

答案 0 :(得分:0)

哦,不...我一个人发现了问题

在这里注意:

hooks:{
  beforeCreate: hashPassword,
  beforeUpdate: hashPassword,
  beforeSave: hashPassword
}

它多次哈希密码...

然后我对其进行修改...

hooks:{
  beforeCreate: hashPassword,
  beforeUpdate: hashPassword
}

一切正常!