【问题标题】:Undefined function with bcrypt-nodejsbcrypt-nodejs 的未定义函数
【发布时间】:2015-11-08 10:55:32
【问题描述】:

我正在使用 bcrypt-nodejs 在预保存函数中对密码进行哈希处理。 我不知道为什么我在 bcrypt.hash 的回调函数中继续收到错误“[TypeError: undefined is not a function]”。

var mongoose = require('mongoose'),
    validate = require('mongoose-validate'),
    bcrypt   = require('bcrypt-nodejs'),
    SALT_WORK_FACTOR = 10,
    REQUIRED_PASSWORD_LENGTH = 8;

function validateStringLength (value) {
    return value && value.length >= REQUIRED_PASSWORD_LENGTH;
}

var schema = mongoose.Schema({
    email: {type: String,
            required: true,
            unique: true,
            validate: [validate.email, 'is not a valid email address']
    },
    passHash: {type: String,
                required: true,
                validate: [validateStringLength, 'The password must be of min ' + REQUIRED_PASSWORD_LENGTH + ' characters length.']}
});

schema.pre('save', function (next) {
    var self = this;

    if (!self.isModified('passHash')) return next();

    bcrypt.hash(self.passHash, SALT_WORK_FACTOR, null, function encryptedPassword (err, hash) {
        if(err) console.log(err);

        self.passHash = hash;
        next();
    });
});

schema.set('autoIndex', App.env !== 'production');

var Model = mongoose.model('User', schema);
module.exports = Model;

我检查了传递的参数,它们是正确的。 返回的哈希也是空的。

有人有类似经历吗? 我正在使用 bcrypt-nodejs,因为 bcrypt 在使用 npm 安装期间给了我错误。

【问题讨论】:

标签: node.js mongoose bcrypt


【解决方案1】:

用这个可以重现:

var bcrypt = require('bcrypt-nodejs')

bcrypt.hash('foo', 10, null, function(err) {
  if (err) throw err;
});

问题是盐必须是一个字符串(在内部,bcrypt-nodejs 使用的是salt.charAt(),而charAt() 是未定义的数字)。

你可能想要这个:

 bcrypt.hash(self.passHash, bcrypt.genSaltSync(SALT_WORK_FACTOR), ...);

(或异步版本,bcrypt.genSalt()

【讨论】:

  • 我没有注意到这个与 bcrypt 不同的参数(错误在于 bcrypt-nodejs),谢谢
猜你喜欢
  • 2017-07-28
  • 1970-01-01
  • 2020-11-28
  • 1970-01-01
  • 1970-01-01
  • 2016-02-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多