Reputation: 529
This is my code.
router.route("/login").post((req, res) => {
const email = req.body.email;
const password = req.body.password;
Account.find().then((account) => {
account.forEach((eachAcc) => {
if (eachAcc.email.toUpperCase() === email.toUpperCase()) {
bcrypt.compare(password, eachAcc.password, function (err, result) {
if (result == true) res.status(200).json("Login Successful");
else if (err) res.status(400).json("Error: " + err);
});
}
});
res.status(400).json("Invalid email or password");
});
});
But I am always getting Invalid email/ password, I want it to be printed only when loop has completed and email/ password didn't match.
Please help.
Upvotes: 0
Views: 63
Reputation: 4519
Try this
router.route("/login").post((req, res) => {
const { email, password } = req.body;
Account.find().then((account) => {
let acc = account.find(
(eachAcc) => eachAcc.email.toUpperCase() ===
email.toUpperCase()
);
if (acc) {
bcrypt.compare(password, acc.password, function (err, result)
{
if (err) res.status(400).json("Error: " + err);
else if (result) res.status(200).json("Login Successful");
else res.status(400).json("Invalid password");
});
} else res.status(400).json("Invalid email");
});
});
Upvotes: 1
Reputation: 1600
I hope it will help:
router.route("/login").post((req, res) => {
const { email, password } = req.body;
Account.find().then((accounts) => {
let match = false;
for (acct of accounts) {
if (acct.email.toUpperCase() !== email.toUpperCase()) continue;
bcrypt.compare(password, acct.password, (err, result) => {
if (err) {
res.status(400).json("Error: " + err);
break;
}
res.status(200).json("Login Successful");
match = true;
break;
});
}
if (!match) res.status(400).json("Invalid email or password");
});
});
Upvotes: 0
Reputation: 994
You can use setTimeout function for this setTimeout(()=>{//code here},300).
Upvotes: 0