3

I'm using bcrypt-nodejs to hashify passwords within a pre save function. 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.

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.

Does anyone had a similar experience? I'm using bcrypt-nodejs because bcrypt gives me error during the installation with npm.

1

1 Answer 1

10

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).

You probably want this:

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

(or the async version, bcrypt.genSalt())

Sign up to request clarification or add additional context in comments.

1 Comment

I didn't notice this different parameter from bcrypt (the error is with bcrypt-nodejs), thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.