Reputation: 1
I have this code for the login, and it doesn't authenticate the user, it gives me back the error response I wrote. I tried changing it so the user would stop giving back "null", but nothing is functioning. This is the code:
router.post("/login", async (req, res) => {
try {
const user = await User.findOne({ username: req.body.username
});
!user && res.status(401).json("Wrong Credentials");
const hashedPassword = CryptoJS.AES.decrypt(
user.password,
process.env.PASS_SEC
);
const OriginalPassword = hashedPassword.toString(CryptoJS.enc.Utf8);
OriginalPassword !== req.body.password &&
res.status(401).json("Wrong Password!");
const accessToken = jwt.sign({
id: user._id,
isAdmin: user.isAdmin,
}, process.env.JWT_SEC,
{expiresIn:"3d"}
);
const { password, ...others } = user._doc;
res.status(200).json(...others, accessToken);
} catch (err) {
res.status(500).json(err);
}
});
what it gives back is the "Wrong Credentials" string I put; I console logged the req.body.username and it gives me back my username, but the const user just keeps giving back null. I hope I can find some answer, I'm losing hope already
Upvotes: 0
Views: 199
Reputation: 1
const { username, password } = req.body;
try {
const getUser=user.findOne({username:username})
if (!getUser) {
return res.json({err:"User Doesn't Exists"})
} else {
const hashedPassword = CryptoJS.AES.decrypt(
getUser.password,
process.env.PASS_SEC
);
const OriginalPassword = hashedPassword.toString(CryptoJS.enc.Utf8);
if (user.password === OriginalPassword) {
const accessToken = jwt.sign({
id: user._id,
isAdmin: user.isAdmin,
}, process.env.JWT_SEC, {
expiresIn: "3d"
});
const { password, ...others } = user._doc;
res.status(200).json(...others, accessToken,{ message: "Logged in
Successfully"});
} else {
return res.json({ err: "Password Doesn't Match" })
}
}
} catch(err) {
return res.json(err)
}
Upvotes: -1