I'm trying to build a user login system using express js and MongoDB, but the issue is whenever I'm trying to log in as a user using the correct username and password, it works fine, but if I'm using any wrong username, it's giving me an error. It gives this error only when the username is wrong or both username and password are wrong but not when the password is wrong. This is my user login code:
router.post("/login", async (req, res) => {
try {
const user = await User.findOne({
username: req.body.username,
});
const hashedPassword = cryptoJS.AES.decrypt(
user.password,
process.env.PASS_SEC
);
const accessToken = jwt.sign(
{ id: user.id, isAdmin: user.isAdmin },
process.env.jwt_SEC,{expiresIn:"3d"}
);
const originalPassword = hashedPassword.toString(cryptoJS.enc.Utf8);
const inputPassword = req.body.password;
if (originalPassword !== inputPassword || !user) {
res.status(401).json("Wrong cridentials");
} else {
const { password, ...others } = user._doc;
console.log(others);
res.status(201).json({...others,accessToken});
}
} catch (error) {
res.status(500).json(error);
console.log(error);
}
});
This is the error i am having:
TypeError: Cannot read properties of null (reading 'password')
at D:\Web\API\Router\auth.js:33:12
at processTicksAndRejections (node:internal/process/task_queues:96:5)
Instead of using the logical OR (
||) operator, try the logical AND (&&) operator.