0

New to NodeJS, trying to write user registration by my own, but facing a trouble when app saves non-hashed password. Tried to check if password is hashed before saving and alert says it is. Here's my code:

var userData = {
        email: req.body.email,
        password: req.body.password
    }

        var user = userData;

        bcrypt.hash(user.password, 10, function(err, hash){
                if(err) console.log(err);
                user.password = hash;
                alert(user.password); //shows hashed password
            });

        //skipped connection code

        database.connection.query("insert into users set ?", user, function(err){ //saves non-hashed password
            if(err) console.log(err);
            console.log("successfull");

        });

2 Answers 2

3

bcrypt.hash is asynchronous. You have what is essentially a race condition in your code.

    database.connection.query("insert into users set ?", user, function(err){ //saves non-hashed password
        if(err) console.log(err);
        console.log("successfull");

    });

When you pass user to this method, user.password has not yet been populated by the bcrypt.hash callback.

You'll need to put the query logic in the bcrypt callback if you stick with a callback oriented style, though most javascripters would likely use promises or async/await (which should be available natively in most recent releases of Node.js).

    bcrypt.hash(user.password, 10, function(err, hash){
            if(err) console.log(err);
            user.password = hash;
            alert(user.password); //shows hashed password

            //>>query logic should go here.
        });
Sign up to request clarification or add additional context in comments.

Comments

1

Looks like you need to put the database query inside the callback. Try something like this:

    var userData = {
       email: req.body.email,
       password: req.body.password
    }

    var user = userData;

    bcrypt.hash(user.password, 10, function(err, hash){
         if(err) console.log(err);
         user.password = hash;
         database.connection.query("insert into users set ?", 
            user, function(err){ //saves non-hashed password
            if(err) console.log(err);
            console.log("successfull");
        });
    });

Node.js is asynchronous like that. That is why there are callback functions. You are inserting the user before you have hashed the password or those events happened at the same time. Basically, you have a race condition.

Comments

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.