I am creating a webtoken for my backend API and to update my database . Even though the token and ID given to it are correct, it's return an error “token not valid” in the POSTMAN. When I checked the console it showed an error stating that “TypeError: Cannot read properties of undefined (reading 'id')”.The code to it is shown below.
const jwt = require("jsonwebtoken");
const verifyToken = (req, res, next) => {
const authHeader = req.headers.token;
if (authHeader) {
const token = authHeader.split("")[1];
jwt.verify(token, process.env.JWT_SEC, (err, user) => {
if (err) res.status(403).json("Token is not valid!");
req.user = user;
next();
});
} else {
return res.status(401).json("YOu are not authenticated!");
}
};
const verifyTokenAndAuthorization = (req, res, next) => {
verifyToken(req, res, () => {
if (req.user.id === req.params.id || req.user.isAdmin) {
next();
} else {
res.status(403).json("You are not allowed to do that!");
}
});
};
module.exports = { verifyToken,verifyTokenAndAuthorization };
the code to the user module is given below
const User = require("../models/User.js");
const { verifyTokenAndAuthorization } = require("./verifyToken.js");
const router = require("express").Router();
//UPDATE
router.put("/:id", verifyTokenAndAuthorization, async (req, res) => {
if (req.body.password) {
req.body.password = CryptoJS.AES.encrypt(
req.body.password,
process.env.PASS_SEC
).toString();
}
try {
const updatedUser = await User.findByIdAndUpdate(
req.params.id,
{ $set: req.body, },
{ new: true }
);
res.status(200).json(updatedUser)
} catch (err) {
res.status(500).json(err);
}
});
module.exports = router;