In my backend server which runs on express I have:
app.post("/login", async(req, res) => {
try {
const { username, password } = req.body;
let result = await checkCredentials(username, password)
console.log("result of checkCredentials:", result);
res.json(result);
} catch (error) {
console.error(error);
}
});
on post, the function checkCredentials
get's called
const checkCredentials = async (clientUsername, clientPassword) => {
try {
const dbUsernameObj = await pool.query("SELECT varol_users_dealer_username FROM varol_users_dealers_credentials WHERE varol_users_dealer_username = $1", [clientUsername]);
const dbUsername = dbUsernameObj.rows[0]?.varol_users_dealer_username
const dbHashObj = await pool.query("SELECT varol_users_dealer_hash FROM varol_users_dealers_credentials WHERE varol_users_dealer_username = $1", [clientUsername])
const dbHash = dbHashObj.rows[0]?.varol_users_dealer_hash
// the 4 lines above are SQL queries that get the respective values, if they exist, if not they're undefined.
if (dbUsername === clientUsername) {
bcrypt.compare(clientPassword, dbHash, function(err, result) {
if (err) {
console.log(err)
}
return result
});
} else {
return false
}
} catch (error) {
console.error(error);
}
}
The problem with this code is, if I supply the right combination of username and password, when checkCredentials
logs, it returns undefined. if my password is wrong, it also returns undefined.
But when my username is wrong, it returns false.
I believe the issue lays in promise chaining, since bcrypt.hash
returns another promise, and the value of checkCredentials
get's logged before bcrypt
finishes.
How can I solve this issue? many thanks.