skip to Main Content

So i need to create a post request that gets login data(name, email, password) from the user, runs validations, encrypts password, then stores data. The problem is that the encryption function takes time to run, and the variable is still not populated by the time i use it. Tried using another promise-await inside but didn’t work. How do i wait till encryptedPass is not null?

// Bcrypt import, initialize number of rounds of salting
saltRounds = 10;

router.post('/user/create', bodyPraser.json(), async (req, res) => {

        // Some code here that runs validations

        // Encrypting password 
        var passwordToEncrypt = req.body.password;
        var encryptedPass;

        // MongoDB model to store data
        const encryptedData = new Model({
            fullname: req.body.fullname,
            email: req.body.email,
            password: encryptedPass
        });
    
        // Salting function
        bcrypt.genSalt(saltRounds, function (err, salt) {
            // Hashing function
            bcrypt.hash(passwordToEncrypt, salt, function (err, hash) {
                // Store hash in database here
                encryptedPass = hash;
            });
        });


        // Save, and store data. Sedn success.
        const dataToSave = await encryptedData.save(); // The password is still null at this point
        res.status(200).json(dataToSave);
        console.log("Data saved");
    }

    catch (error) {
        res.status(400).json({ message: error.message });
        console.log("Data not saved!");
    }
})

2

Answers


  1. Here’s the modified code. I just put everything under your salt function, because everything depends on salt.

    // Bcrypt import, initialize number of rounds of salting
    saltRounds = 10;
    
    router.post('/user/create', bodyPraser.json(), async (req, res) => {
    
            // Some code here that runs validations
            
            // Salting function
            bcrypt.genSalt(saltRounds, function (err, salt) {
                // Hashing function
                bcrypt.hash(req.body.password, salt, function (err, hash) {
                    if(err){
                        res.status(400).json({message: 'Something went wrong'});
                    } else {
                        // MongoDB model to store data
                        const encryptedData = new Model({
                            fullname: req.body.fullname,
                            email: req.body.email,
                            password: hash
                        });
                        // Save, and store data. Sedn success.
                        const dataToSave = await encryptedData.save();
                        res.status(200).json(dataToSave);
                    }
                }
                });
            });
        }
    
        catch (error) {
            res.status(400).json({ message: error.message });
            console.log("Data not saved!");
        }
    })
    
    Login or Signup to reply.
  2. You need to store data in database at the time once the password is hashed and then do it you are doing it before the password is hashed and you are getting the wrong results,

    PTR: Also avoid using var instead use let because it’s a bad practice

    Do this instead

    // Bcrypt import, initialize number of rounds of salting
    saltRounds = 10;
    
    router.post('/user/create', bodyPraser.json(), async (req, res) => {
        try {
            // Some code here that runs validations
    
            // Encrypting password 
            let passwordToEncrypt = req.body.password;
            let encryptedPass;
            let encryptedData
    
            // MongoDB model to store data
    
    
            // Salting function
            bcrypt.genSalt(saltRounds, function (err, salt) {
                if (err) {
                    return res
                        .status(400)
                        .json({
                            message: 'Something went wrong'
                        });
                } else {
                    // Hashing function
                    bcrypt.hash(passwordToEncrypt, salt, function (err, hash) {
                        if (err) {
                            return res
                                .status(400)
                                .json({
                                    message: 'Something went wrong'
                                });
                        } else {
                            // Store hash in database here
                            encryptedPass = hash;
                            encryptedData = new Model({
                                fullname: req.body.fullname,
                                email: req.body.email,
                                password: encryptedPass
                            });
                        }
    
                    });
                }
    
            });
    
            // Save, and store data. Sedn success.
            const dataToSave = await encryptedData.save(); // The password is still null at this point
            console.log("Data saved");
            return res
                .status(200)
                .json(dataToSave);
    
        }
        catch (error) {
            console.log("Data not saved!");
            return res
                .status(400)
                .json({
                    message: error.message
                });
    
        }
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search