Saurabh Sharma Saurabh Sharma - 2 months ago 73
Node.js Question

bcrypt-node is throwing error "No callback function was given"

I am creating a user registration using JWT authentication. and I am using bcrypt-node module to make password hash and salted.

useraModel.js

var mongoose =require('mongoose');
var Schema =mongoose.Schema;
var bcrypt =require('bcrypt-node');

var UserSchema=new Schema({
name:{type:String, unique:true, required:true},
password:{type:String, required:true}
});

UserSchema.pre('save', function (next) {
var user = this;
if (this.isModified('password') || this.isNew) {
bcrypt.genSalt(10, function (err, salt) {
if (err) {
return next(err);
}
bcrypt.hash(user.password, salt, function (err, hash) {
if (err) {
return next(err);
}
user.password = hash;
next();
});
});
} else {
return next();
}
});

UserSchema.methods.comparePassword = function (passw, cb) {
bcrypt.compare(passw, this.password, function (err, isMatch) {
if (err) {
return cb(err);
}
cb(null, isMatch);
});
};

module.exports = mongoose.model('User', UserSchema);


passport.js

var JwtStrategy =require('passport-jwt').Strategy;
var User =require('../app/models/user');
var config =require('../config/database');

module.exports=function(passport){
var opts = {};
opts.secretOrKey = config.secret;
passport.use(new JwtStrategy(opts, function(jwt_payload, done) {
User.findOne({id: jwt_payload.id}, function(err, user) {
if (err) {
return done(err, false);
}
if (user) {
done(null, user);
} else {
done(null, false);
}
});
}));
};


app.js

apiRoutes.post('/signup', function(req, res) {
if (!req.body.name || !req.body.password) {
res.json({success: false, msg: 'Please pass name and password.'});
} else {
var newUser = new User({
name: req.body.name,
password: req.body.password
});
// save the user
newUser.save(function(err) {
if (err) {
return res.json({success: false, msg: 'Username already exists.'});
}
res.json({success: true, msg: 'Successful created new user.'});
});
}
});


When I run this code its showing error-

throw "No callback function was given".

No Callback function was given


Please help me to fix this code.
Thanks

Answer

bcrypt.hash() requires 4 arguments:

hash(data, salt, progress, cb)

The documentation is unclear on this: it states that data, salt and cb are required, which implies that progress isn't, but without it you'll get the error.

Pass a null if you don't care about tracking progress:

bcrypt.hash(user.password, salt, null, function (err, hash) { ... })
Comments