I have a registration page on which users can send a request to the database. Before sending the request I modify the password with salt+hash algorithm.
EXAMPLE FROM DB:
username : aUser1234
password: password12345
hashed: $2b$13$dTbz4IeMdeXkqHwCL7Lzqe8NKNyKBvA2mQWk8gnPDLWc4O6hyvew2
I'm trying to fetch the hashed password from my database but I have three questions for my code.
- How to access the hashed password from the database, once verified that the username exists?
- How do I then use
await bcrypt.compare(password, hashedPassowrd);withingetConnection().query()... - Does the
router.postcallback function needs to beasyncas well?
router.post('/user_login', async (req, res) => { //Does this needs to be an async callback function?
const username = req.body.thisUsername; //aUser1234
const password = req.body.thisPassword; //password12345
const sqlString = "SELECT username FROM student_demographics WHERE username = ?";
getConnection().query(sqlString, [username], async (err, results, fields) => {
if(err){
res.sendStatus(500);
}
if(results.length){
console.log("NO ERRORS HERE"); //WORKS OKAY UNTIL HERE
//HOW TO GET HASHED PASSWORD AND STORE IT ON VARIABLE
const isValid = await bcrypt.compare(password, hashedPassowrd); //ERROR
if(isValid){
//PASSWORD MATCHED
res.redirect('/homePage.html');
res.end();
}else{
//PASSWORD DIDN'T MATCH
res.redirect('/login.html');
}
}else{ //THE USERNAME DOES NOT exists
console.log(" > The username or password are invalid :(")
res.redirect('/login.html');
res.end();
}
});
});