【问题标题】:Can't save hashed password to database using bcrypt and bookshelf无法使用 bcrypt 和 bookshelf 将散列密码保存到数据库
【发布时间】:2017-03-29 17:30:38
【问题描述】:

对 nodejs 还是很陌生,所以我经常被整个异步的东西绊倒。我正在尝试使用 bcrypt 和 bookshelf 在将密码存储到数据库之前对其进行哈希处理。非常直截了当...

我这样调用保存操作,

create(data) {
    this.logger.info(`creating account`);
    return bookshelf.transaction(trx => {
        return new Account().save(data, { method: 'insert', transacting: trx });
    });
}

在帐户模型中,我拦截了保存操作

initialize: function() {
    let _this = this;
    const saltRounds = 10;
    _this.on('creating', function () {
        bcrypt.genSaltSync(saltRounds, function(err, salt) {
            bcrypt.hashSync(_this.get('password'), salt, function (err, hash) {
                if (err) throw err;

                _this.set('password', hash);
            });
        });
    });
}

到目前为止,我查看的所有内容都表明这应该可以工作,但是纯文本密码仍然保存到数据库中,而不是散列密码。我做错了什么?

【问题讨论】:

    标签: node.js bcrypt bookshelf.js


    【解决方案1】:

    您正在使用同步函数,但向它们传递了不会被调用的回调(因此,密码不会被替换)。

    试试这个:

    initialize: function() {
      const saltRounds = 10;
      this.on('creating', () => {
        let salt = bcrypt.genSaltSync(saltRounds);
        let hash = bcrypt.hashSync(this.get('password'), salt);
        this.set('password', hash);
      });
    }
    

    或者用异步函数替换同步函数,使用 Promise(bcryptbookshelf 都支持):

    initialize: function() {
      const saltRounds = 10;
      this.on('creating', () => {
        return bcrypt.genSalt(saltRounds).then(salt => {
          return bcrypt.hash(this.get('password'), salt);
        }).then(hash => {
          this.set('password', hash);
        });
      });
    }
    

    【讨论】:

      【解决方案2】:

      我不确定,但我认为错误是因为您使用的是 es6 let 而不是 var 那么 this 的上下文将推迟

      【讨论】:

        猜你喜欢
        • 2019-07-17
        • 2017-06-26
        • 1970-01-01
        • 1970-01-01
        • 2018-10-05
        • 1970-01-01
        • 1970-01-01
        • 2013-04-24
        • 2015-05-14
        相关资源
        最近更新 更多