23 lines
705 B
JavaScript
23 lines
705 B
JavaScript
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;
|
|
// extract username from token
|
|
const username = jwt.verify(token, process.env.SECRET_KEY).username;
|
|
// get post
|
|
const post = await Post.findById(req.params.postID).lean().exec();
|
|
// if different usernames
|
|
if (username !== post.author) {
|
|
return res.status(403).json({
|
|
message: "Not authorized!",
|
|
});
|
|
}
|
|
// otherwise all good
|
|
return next();
|
|
});
|
|
|
|
module.exports = sameAuthor;
|