Files
Checkmate/Server/middleware/verifyOwnership.js
T

51 lines
1.4 KiB
JavaScript
Raw Normal View History

2024-10-15 11:57:37 +08:00
import logger from "../utils/logger.js";
import { errorMessages } from "../utils/messages.js";
2024-05-24 13:44:42 -07:00
const SERVICE_NAME = "verifyOwnership";
const verifyOwnership = (Model, paramName) => {
2024-10-17 12:07:30 +08:00
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) {
2024-10-24 15:28:13 +08:00
logger.error({
message: errorMessages.VERIFY_OWNER_NOT_FOUND,
2024-10-17 12:07:30 +08:00
service: SERVICE_NAME,
2024-10-24 15:28:13 +08:00
method: "verifyOwnership",
2024-10-17 12:07:30 +08:00
});
const error = new Error(errorMessages.VERIFY_OWNER_NOT_FOUND);
error.status = 404;
throw error;
}
2024-05-24 13:44:42 -07:00
2024-10-17 12:07:30 +08:00
// Special case for User model, as it will not have a `userId` field as other docs will
if (Model.modelName === "User") {
if (userId.toString() !== doc._id.toString()) {
const error = new Error(errorMessages.VERIFY_OWNER_UNAUTHORIZED);
error.status = 403;
throw error;
}
next();
return;
}
2024-07-02 10:20:10 -07:00
2024-10-17 12:07:30 +08:00
// If the userID does not match the document's userID, return a 403 error
if (userId.toString() !== doc.userId.toString()) {
const error = new Error(errorMessages.VERIFY_OWNER_UNAUTHORIZED);
error.status = 403;
throw error;
}
next();
return;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "verifyOwnership";
next(error);
return;
}
};
2024-05-24 13:44:42 -07:00
};
2024-10-15 11:57:37 +08:00
export { verifyOwnership };