I'm making my own small API, and I've coded out the following POST request to my MongoDB database:
api.post("/account/login", async (req, res) => {
const user = {
username: req.body.username,
password: req.body.password
};
const username = JSON.stringify(user.username);
const hashedPassword = await logincollection.find(user.username).toArray();
const hardCodedPassword = "$2b$10$q0iOBFTqqZ3vnp5oqDQUqejdS7UD/ayw4Q4qgi5hs1pfFI.xfipDS"
console.log(hashedPassword)
// Search for matching login credentials
logincollection.find(user, (err, result) => {
try {
if (bcrypt.compare(req.body.password, hardCodedPassword)) {
// Return credentials back to the client
const sendObject = {
username: result.username,
password: result.password
};
console.log(sendObject);
// Return code 200 (success) to the client
res.status(200).send(sendObject);
// Log to console when user logs in
console.log("User " username " logged in");
}
} catch(error) {
// If matching credentials were not found, return code 404 (wrong credentials) to the client
res.status(404).send()
}
})
})
I have set a valid hardcoded password for purely testing purposes. When this request is processed, console.log(sendObject)
prints undefined results to the console and bcrypt returns true
, no matter what password I put in. What's the problem here?
CodePudding user response:
As @jonrsharpe said, bcrypt.compare
returns a Promise not a value. You must use a callback function, Promise.then() or async/await to handle the asynchronous result.
// Search for matching login credentials
logincollection.find(user, (err, result) => {
bcrypt.compare(req.body.password, hardCodedPassword)
.then(match => {
if (match) {
// Return credentials back to the client
const sendObject = {
username: result.username,
password: result.password
};
console.log(sendObject);
// Return code 200 (success) to the client
res.status(200).send(sendObject);
// Log to console when user logs in
console.log("User " username " logged in");
} else {
// If matching credentials were not found, return code 404 (wrong credentials) to the client
res.status(404).send()
}
})
.catch(error => {
res.status(500).send()
})
})