Compare the user entered password against the password that you have saved in database (hashed version). If they both match, you can login user.
// routes/auth
router.post("/login", auth.login);
// controllers/auth
export const login = async (req, res) => {
try {
const { email, password } = req.body;
// 1. find user by email
const user = await User.findOne({ email });
if (!user) {
return res.json({ error: "Please register first" });
}
// 2. compare password
const match = await comparePassword(password, user.password);
if (!match) {
return res.json({
error: "Wrong password",
});
}
// 3. create jwt tokens
const token = jwt.sign({ _id: user._id }, config.JWT_SECRET, {
expiresIn: "1d",
});
const refreshToken = jwt.sign({ _id: user._id }, config.JWT_SECRET, {
expiresIn: "30d",
});
// 4. send user and token as response excluding password
user.password = undefined;
user.resetCode = undefined;
res.json({
user,
token,
refreshToken,
});
} catch (err) {
console.log(err);
res.json({ error: "Something went wrong. Try again." });
}
};