stage 1
This commit is contained in:
@@ -0,0 +1,35 @@
|
||||
/*
|
||||
* Parameter validation middleware. Each route parameter is checked against
|
||||
* a safe pattern to prevent unexpected input from reaching database queries.
|
||||
* The whitelist approach rejects obviously invalid identifiers early, keeping
|
||||
* service-layer code cleaner.
|
||||
*/
|
||||
|
||||
const SAFE_CODE_PATTERN = /^[a-zA-Z0-9_-]{1,100}$/;
|
||||
const SAFE_UUID_PATTERN = /^[a-f0-9-]{36}$/;
|
||||
|
||||
export function validateParam(paramName, { pattern = null } = {}) {
|
||||
const resolvedPattern = pattern || (paramName.toLowerCase().includes('id') ? SAFE_UUID_PATTERN : SAFE_CODE_PATTERN);
|
||||
|
||||
return (req, res, next) => {
|
||||
const value = req.params[paramName];
|
||||
|
||||
if (!value || !resolvedPattern.test(value)) {
|
||||
return res.status(400).json({ message: `Invalid parameter: ${paramName}` });
|
||||
}
|
||||
|
||||
next();
|
||||
};
|
||||
}
|
||||
|
||||
export function validateNumericParam(paramName) {
|
||||
return (req, res, next) => {
|
||||
const value = Number(req.params[paramName]);
|
||||
|
||||
if (!Number.isFinite(value) || value < 0) {
|
||||
return res.status(400).json({ message: `Invalid numeric parameter: ${paramName}` });
|
||||
}
|
||||
|
||||
next();
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user