Files
Checkmate/Server/middleware/verifyOwnership.js
T

36 lines
1.1 KiB
JavaScript
Raw Normal View History

2024-05-24 13:44:42 -07:00
const logger = require("../utils/logger");
const SERVICE_NAME = "verifyOwnership";
const { errorMessages } = require("../utils/messages");
2024-05-24 13:44:42 -07:00
const verifyOwnership = (Model, paramName) => {
return async (req, res, next) => {
const userId = req.user._id;
const documentId = req.params[paramName];
try {
const doc = await Model.findById(documentId);
//If the document is not found, return a 404 error
if (!doc) {
logger.error(errorMessages.VERIFY_OWNER_NOT_FOUND, {
2024-05-24 13:44:42 -07:00
service: SERVICE_NAME,
});
const error = new Error(errorMessages.VERIFY_OWNER_NOT_FOUND);
2024-05-27 10:47:14 -07:00
error.status = 404;
throw error;
2024-05-24 13:44:42 -07:00
}
// If the userID does not match the document's userID, return a 403 error
if (userId.toString() !== doc.userId.toString()) {
console.log(userId.toString(), doc.userId.toString());
const error = new Error(errorMessages.VERIFY_OWNER_UNAUTHORIZED);
2024-05-27 10:47:14 -07:00
error.status = 403;
throw error;
2024-05-24 13:44:42 -07:00
}
next();
} catch (error) {
2024-05-27 10:47:14 -07:00
error.service = SERVICE_NAME;
next(error);
2024-05-24 13:44:42 -07:00
}
};
};
module.exports = { verifyOwnership };