fix security and import validation
This commit is contained in:
+29
-2
@@ -58,7 +58,7 @@ function validateRequired(obj, fields) {
|
||||
|
||||
function validateNumber(value, field, min, max) {
|
||||
const num = Number(value);
|
||||
if (isNaN(num)) {
|
||||
if (!Number.isFinite(num)) {
|
||||
throw new AppError(`${field} 必须是数字`, 400);
|
||||
}
|
||||
if (min !== undefined && num < min) {
|
||||
@@ -80,6 +80,11 @@ function validateString(value, field, maxLength) {
|
||||
return value.trim();
|
||||
}
|
||||
|
||||
function optionalString(value, field, maxLength) {
|
||||
if (value === undefined || value === null || value === '') return null;
|
||||
return validateString(String(value), field, maxLength);
|
||||
}
|
||||
|
||||
function validateInList(value, field, list) {
|
||||
if (!list.includes(value)) {
|
||||
throw new AppError(`${field} 值无效`, 400);
|
||||
@@ -87,6 +92,24 @@ function validateInList(value, field, list) {
|
||||
return value;
|
||||
}
|
||||
|
||||
function validatePage(value, defaultValue = 1) {
|
||||
return Math.max(1, Number.parseInt(value, 10) || defaultValue);
|
||||
}
|
||||
|
||||
function validateLimit(value, defaultValue, maxLimit) {
|
||||
const limit = Number.parseInt(value, 10) || defaultValue;
|
||||
return Math.min(Math.max(1, limit), maxLimit);
|
||||
}
|
||||
|
||||
function validateIsoDate(value, field) {
|
||||
if (value === undefined || value === null || value === '') return new Date().toISOString();
|
||||
const date = new Date(value);
|
||||
if (Number.isNaN(date.getTime())) {
|
||||
throw new AppError(`${field} 格式无效`, 400);
|
||||
}
|
||||
return date.toISOString();
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
AppError,
|
||||
getMonthRange,
|
||||
@@ -94,5 +117,9 @@ module.exports = {
|
||||
validateRequired,
|
||||
validateNumber,
|
||||
validateString,
|
||||
validateInList
|
||||
optionalString,
|
||||
validateInList,
|
||||
validatePage,
|
||||
validateLimit,
|
||||
validateIsoDate
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user