sanket3280/code-execution
0
1const mongoose = require('mongoose');2 3/**4 * Middleware to validate MongoDB ObjectId in route parameters5 * 6 * This middleware checks if a route parameter contains a valid MongoDB ObjectId7 * before allowing the request to proceed to the route handler.8 * 9 * @param {string} paramName - The name of the parameter to validate (default: 'id')10 * @returns {Function} Express middleware function11 * 12 * @example13 * // Validate the 'id' parameter14 * router.get('/:id', validateObjectId(), handler);15 * 16 * // Validate a custom parameter name17 * router.get('/:challengeId', validateObjectId('challengeId'), handler);18 */19function validateObjectId(paramName = 'id') {20 return (req, res, next) => {21 const id = req.params[paramName];22 23 // Check if parameter exists24 if (!id) {25 console.warn(`[Validation] Missing ${paramName} parameter`, {26 route: req.path,27 method: req.method,28 ip: req.ip29 });30 return res.status(400).json({31 message: `${paramName} parameter is required`,32 error: 'MISSING_PARAMETER'33 });34 }35 36 // Check for common invalid string values37 if (id === 'undefined' || id === 'null') {38 console.warn(`[Validation] Invalid ${paramName} value: ${id}`, {39 route: req.path,40 method: req.method,41 ip: req.ip,42 userAgent: req.get('user-agent')43 });44 return res.status(400).json({45 message: `Invalid ${paramName} value`,46 error: 'INVALID_PARAMETER'47 });48 }49 50 // Validate ObjectId format using mongoose51 if (!mongoose.Types.ObjectId.isValid(id)) {52 console.warn(`[Validation] Invalid ObjectId format for ${paramName}: ${id}`, {53 route: req.path,54 method: req.method,55 ip: req.ip56 });57 return res.status(400).json({58 message: `Invalid ${paramName} format`,59 error: 'INVALID_ID_FORMAT'60 });61 }62 63 // All validations passed, proceed to next middleware/handler64 next();65 };66}67 68module.exports = { validateObjectId };69 