const jwt = require("jsonwebtoken"); const asyncHandler = require("express-async-handler"); const { default: mongoose } = require("mongoose"); const Post = require("../models/post.js"); const sameAuthor = asyncHandler(async (req, res, next) => { // get token const token = req.cookies.JWT_TOKEN; // make token with identical user information let opts = { expiresIn: "1d", }; const post = await Post.findById(req.params.postID).lean().exec(); const author = post.author; const userToken = jwt.sign({ author }, 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 = sameAuthor;