【问题标题】:node.js bcrypt compare return false even just after where I hashnode.js bcrypt 比较即使在我散列之后也返回 false
【发布时间】:2018-12-22 10:42:36
【问题描述】:

我已经尝试了至少三个小时,但仍然没有得到它。

我的 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) 是假的...

更不用说每次我尝试登录时,我的 User.prototype.comparePassword(password) 也总是返回 false!

请帮帮我,谢谢!

【问题讨论】:

    标签: node.js hash bcrypt


    【解决方案1】:

    哦不...我自己发现了问题

    请注意:

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

    它不止一次对密码进行哈希处理...

    在我修改之后...

    hooks:{
      beforeCreate: hashPassword,
      beforeUpdate: hashPassword
    }
    

    一切正常!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-09-16
      • 2017-10-01
      • 2018-02-01
      • 1970-01-01
      • 2020-07-24
      • 2013-01-25
      • 1970-01-01
      • 2015-08-10
      相关资源
      最近更新 更多