Im trying to pass the result of the bcrypt hashing function into the user model below.
I can't seem be able to wrap my head around how to efficiently resolve this promise.
Heres the code:
router.post("/", async (req, res) => {
req.body = sanitize(req.body);
// SHA-256
/* const bitArray = sjcl.hash.sha256.hash(req.body.data[2].value);
const passwordHashed = sjcl.codec.hex.fromBits(bitArray); */
const saltRounds = 10;
const password = req.body.data[2].value;
var passwordHashed;
async function hash() {
return await bcrypt.hash(password, saltRounds, function (err, hash) {});
}
const user = new User({
username: req.body.data[0].value,
email: req.body.data[1].value,
password: hash(),
});
try {
await user.save();
res.status(200).json({ msg: "Success" });
} catch (e) {}
});
That is what I have tried so far, which is probably wrong
CodePudding user response:
Don't pass a callback to bcrypt.hash
and then you can await
it.
const user = new User({
username: req.body.data[0].value,
email: req.body.data[1].value,
password: await bcrypt.hash(password, saltRounds),
});
CodePudding user response:
The function is not asynchronous at all, so run it synchronously. You also did not generate the hash correctly according to bcrypt.
Here's a correction:
function hash(password) {
bcrypt.genSalt(10, (err, salt) => {
if (err) return null;
bcrypt.hash(password, salt, (err, hash) => {
if (err) return null;
console.log(hash);
return hash;
});
});
}
When you want to create a new password, let hash = hash("newpassword");
If any issues, hash will be null and that means don't use it! You'd later when logging in, do a compare using bcrypt.compare! :)