Code Review Stack Exchange is a question and answer site for peer programmer code reviews. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I'm creating a simple registration form, but stuck somewhere. I want to use token variable in new user() scope, but if I put new user() part outside of crypto, I can't access it.

Right now it works as expected, but is incomplete. I wonder whether there's another way to achieve this without putting everything inside each other. I need to access hash, so I put new user() inside bcrypt.hash. I also need to access buf, so I put it inside bcrypt, too.

Should I restructure my code (if yes, please help me a little) or is it "okay" as it is? Everything is kinda chained right now, is that normal?

var newUser = req.body;

bcrypt.genSalt(10, function (err, salt) {
    bcrypt.hash(newUser.password1, salt, function (err, hash) {

        crypto.randomBytes(48, function (ex, buf) {
            var token = buf.toString('hex');

            new user({
                email: newUser.email,
                username: newUser.username,
                password_hash: hash,
                image_id: 1,
                confirmation_code: token

            }).save().then(function (data) {
                // do stuff
                console.log(data.toJSON());
            });
        });
    });
});
share|improve this question
1  
FWIW, my attempt came out more-or-less the same (Except I used pbkdf2 instead of bcrypt because windows is silly) gist.github.com/danpantry/790eb6aab90194a6377b – Dan Pantry Oct 29 '15 at 11:59
1  
You can generate a salt and hash with a single function call by passing a number to bcrypt.hash. See the documentation. – Spike Oct 29 '15 at 15:13

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.