express-blog-api/middleware/sameUser.js
2023-09-27 22:26:37 -07:00

22 lines
596 B
JavaScript

const jwt = require("jsonwebtoken");
const sameUser = (req, res, next) => {
// get token
const token = req.cookies.JWT_TOKEN;
// make token with identical user information
let opts = {
expiresIn: "1d",
};
const username = req.params.username;
const userToken = jwt.sign({ username }, process.env.SECRET_KEY, opts);
// compare the two, if the token does not match then the action is unauthorized
if (token != userToken) {
return res.status(403).json({
message: "Not authorized!",
});
}
// otherwise all good
return next();
};
module.exports = sameUser;