export const login = async (req, res) => {
const { username, password } = req.body;
try {
// CHECK IF THE USER EXISTS
const user = await prisma.user.findUnique({
where: { username },
});
if (!user) return res.status(400).json({ message: "User Not Found!" });
// CHECK IF THE PASSWORD IS CORRECT
const isPasswordValid = await bcrypt.compare(password, user.password);
if (!isPasswordValid)
return res.status(400).json({ message: "Invalid Credentials!" });
// GENERATE COOKIE TOKEN AND SEND TO THE USER
const age = 1000 * 60 * 60 * 24 * 7;
const token = jwt.sign(
{
id: user.id,
isAdmin: false,
},
process.env.JWT_SECRET_KEY,
{ expiresIn: age }
);
const { password: userPassword, ...userInfo } = user;
res
.cookie("token", token, {
httpOnly: true,
maxAge: age,
})
.status(200)
.json(userInfo);
} catch (err) {
console.log(err);
res.status(500).json({ message: "Failed to login!" });
}
};
I am using this code for generating cookies, which is generating cookies perfectly. But when i try to access the verifyToken middleware from frontend side then it was not working.
When i do
console.log(token);
it showing null value.
export const verifyToken = (req, res, next) => {
const token = req.cookies.token;
console.log(token);
if (!token) return res.status(401).json({ message: "Not Authenticated!" });
jwt.verify(token, process.env.JWT_SECRET_KEY, async (err, payload) => {
if (err) return res.status(403).json({ message: "Token is not Valid!" });
req.userId = payload.id;
next();
});
};
How to solve this problem.
New contributor
Udit Padhan is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.