While sign up, I am converting the plain text password into a hashed password using bcrypt and storing it in the database, but while logging in, when I am checking the password entered and the hashed password in the database, it's not working. I am using bcrypt.compare() to compare the two passwords. I can't seem to get the solution for this. This is my code snippet of the login function
// Function called for login
export const login = async (req, res) => {
const { email, password } = req.body; // It will request name, email and password from the database
try {
const existingUser = await users.findOne({ email }); // To find only one user with the email stored in the database
if (!existingUser) {
// If user's email does not exist in the database then show this message
return res.status(404).json({ message: "User not found" });
}
//Comparing the password entered with the hashed password stored in the database of that particular user
bcrypt.compare(password, existingUser.password, (err, res) => {
if (err) {
console.log("Error:", err);
return err;
}
if (!res) {
return res.status(400).json({ message: "Invalid Password" });
}
});
const token = jwt.sign(
{ email: existingUser.email, id: existingUser._id },
"test",
{ expiresIn: "1h" }
);
res.status(200).json({ result: existingUser, token }); // Successful
} catch (error) {
res.status(500).json("Umm okay...something went wrong..."); // Internal server error
}
};
I tried to compare the plain text password entered and the hashed password stored in the database using bcrypt.compare() but it didn't seem to give me a proper output for which I am not able authenticate the user. The user can log in even if the password is incorrect.