I create a user on the login page and hash this password with Argon2 but when I compare it, it does not match the password. The hashed password is shown in the database and I can also see the plain text. When I compare the two, it returns false. I have been trying for a day. I was using normal bcryptjs but when it did not work, I switched to argon2. I guess I was making the same mistake in both
exports.register = async (req, res) => {
try {
const { fullname, username, email, password } = req.body;
const existingUser = await User.findOne({ email });
if (existingUser)
return res.status(400).json({ message: "User already exists!" });
const trimmedPassword = password.trim();
const hashedPassword = await argon2.hash(trimmedPassword);
const newUser = new User({
fullname,
username,
email,
password: hashedPassword,
});
await newUser.save();
console.log(newUser);
res
.status(201)
.json({ message: "User created successfully. Welcome to InkSpace..." });
} catch (error) {
res.status(500).json({ message: "Error creating user", error });
}
};
exports.login = async (req, res) => {
try {
const { email, password } = req.body;
const plainPassword = password.trim();
console.log("plain password",plainPassword);
const user = await User.findOne({ email });
const hashPassword = user.password;
console.log(user);
if (!user) {
return res.status(400).json({ message: "Invalid email or password" });
}
console.log(hashPassword);
const isMatch = await argon2.verify(hashPassword, plainPassword);
console.log(isMatch)
if (isMatch) {
req.session.user = {
userId: user._id,
username: user.username,
};
console.log("Session data after login:", req.session.user);
return res.status(200).json({ message: "Login successful" });
} else {
console.log("did not match")
return res.status(400).json({ message: "Invalid email or password" });
}
} catch (error) {
console.log("verify argon2 ", error);
res.status(500).json({ message: "Error logging in", error });
}
};