简体   繁体   English

使用bcrypt-nodejs的未定义函数

[英]Undefined function with bcrypt-nodejs

I'm using bcrypt-nodejs to hashify passwords within a pre save function. 我正在使用bcrypt-nodejs在预保存函数中散列密码。 I can't figure out why I continue to receive the error '[TypeError: undefined is not a function]' inside the callback function of bcrypt.hash. 我无法弄清楚为什么我继续在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;

I checked the parameters passed and they are correct. 我检查了传递的参数,它们是正确的。 Also the hash returned is null. 返回的哈希值也为null。

Does anyone had a similar experience? 有没有人有类似的经历? I'm using bcrypt-nodejs because bcrypt gives me error during the installation with npm. 我正在使用bcrypt-nodejs,因为bcrypt在使用npm进行安装时给出了错误。

Reproducable with this: 可重复使用:

var bcrypt = require('bcrypt-nodejs')

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

The issue is that the salt needs to be a string (internally, bcrypt-nodejs is using salt.charAt() , and charAt() is undefined for numbers). 问题是salt需要是一个字符串(内部, bcrypt-nodejs使用salt.charAt() ,而charAt()未定义为数字)。

You probably want this: 你可能想要这个:

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

(or the async version, bcrypt.genSalt() ) (或异步版本, bcrypt.genSalt()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM