0

I need to hash the password before insert in the DB I have the function of bcrypt but I don't know how to get it into a const and use it for make the insert into mysql.

I'm using bcrypt for it, so what's the method I should follow to get the password hashed?

  async postCompletedetails(req, res) {
    const company = req.params.company;
    const name = req.params.name;
    const password = req.params.password;
bcrypt.hash(password, saltRounds, (err, hash) => {
});



if (
  company !== undefined &&
  name !== undefined &&
  password !== undefined
) {
    
const { token } = req.headers;
const decoded = jwt.verify(token, process.env.JWT_ACCOUNT_ACTIVATION);
const id = decoded.id;

  const update = await pool.query(
    `UPDATE user SET Name_user= '${name}', password= '${password}' WHERE ID_user = ${id}`
  );
  const incompany = await pool.query(
    `INSERT INTO company (Name_company) VALUES ('${company}') `
  );

  const inrelcompany = await pool.query(
    `INSERT INTO rel_company_user (ID_company, ID_user) VALUES (LAST_INSERT_ID(), ${id})`
  );

  return res.json({
    code: 200,
    message: "todo bien... todo correcto y yo que me alegro",
    password,
  });
} else {
  return res.json({
    code: 400,
    message: "Bro hiciste algo mal",
  });
}

}

2 Answers2

1
 async postCompletedetails(req, res) {
    const company = req.params.company;
    const name = req.params.name;
    const password = req.params.password;
    const saltRounds = 10;

if (
  company !== undefined &&
  name !== undefined &&
  password !== undefined
) { 

const hashPass = bcrypt.hash(password, saltRounds, (err, hash) => {
   if (err) 
{
return err; 
}

return hash;
});

hashPass // this will be what you insert into the database.

}
exception_thrown
  • 529
  • 1
  • 7
  • 22
  • That won't work because if you don't await ``bcrypt.hash``, the function will be async and the constant ``hashPass`` will be undefined. – Take-Some-Bytes Aug 13 '20 at 04:12
0

Ok, I have it but the problem is that I can't get the hashed password, hassPass have de value undefined, what I should change?

 const hashPass = await bcrypt.genSalt(saltRounds, function (err, salt) {
      if (err) {
        throw err
      } else {
        bcrypt.hash(password, salt, function(err, hash) {
          if (err) {
            throw err
          } else {
            console.log(hash)
          }
        })
      }
    })

The password is being hashed, I now it for the console.log