Spaces:
Sleeping
Sleeping
Download backend/src/middleware/validation.js from edichat/edi.chat.test: direct link, hf CLI and curl.
- Browser
- Download file 9.37 kB
-
https://huggingface.co/spaces/edichat/edi.chat.test/resolve/main/backend/src/middleware/validation.js
- Command line
-
hf download hf://spaces/edichat/edi.chat.test/backend/src/middleware/validation.js
-
curl -L -o validation.js https://huggingface.co/spaces/edichat/edi.chat.test/resolve/main/backend/src/middleware/validation.js
9.37 kB
| const { validationResult } = require('express-validator'); | |
| const logger = require('../utils/logger'); | |
| /** | |
| * Middleware to handle validation errors from express-validator | |
| */ | |
| const handleValidationErrors = (req, res, next) => { | |
| const errors = validationResult(req); | |
| if (!errors.isEmpty()) { | |
| const formattedErrors = errors.array().map(error => ({ | |
| field: error.path || error.param, | |
| message: error.msg, | |
| value: error.value, | |
| location: error.location | |
| })); | |
| logger.warn('Validation failed:', { | |
| requestId: req.id, | |
| errors: formattedErrors, | |
| endpoint: `${req.method} ${req.path}`, | |
| ip: req.ip | |
| }); | |
| return res.status(400).json({ | |
| success: false, | |
| error: 'Validation failed', | |
| details: formattedErrors, | |
| message: 'Please check your input and try again' | |
| }); | |
| } | |
| next(); | |
| }; | |
| /** | |
| * Middleware to sanitize and validate request data | |
| */ | |
| const sanitizeInput = (req, res, next) => { | |
| // Remove any null bytes from strings to prevent injection | |
| const sanitizeString = (str) => { | |
| if (typeof str === 'string') { | |
| return str.replace(/\0/g, ''); | |
| } | |
| return str; | |
| }; | |
| // Recursively sanitize object | |
| const sanitizeObject = (obj) => { | |
| if (obj === null || typeof obj !== 'object') { | |
| return sanitizeString(obj); | |
| } | |
| if (Array.isArray(obj)) { | |
| return obj.map(sanitizeObject); | |
| } | |
| const sanitized = {}; | |
| for (const [key, value] of Object.entries(obj)) { | |
| sanitized[key] = sanitizeObject(value); | |
| } | |
| return sanitized; | |
| }; | |
| // Sanitize request body | |
| if (req.body) { | |
| req.body = sanitizeObject(req.body); | |
| } | |
| // Sanitize query parameters | |
| if (req.query) { | |
| req.query = sanitizeObject(req.query); | |
| } | |
| next(); | |
| }; | |
| /** | |
| * Middleware to validate MongoDB ObjectId parameters | |
| */ | |
| const validateObjectId = (paramName = 'id') => { | |
| return (req, res, next) => { | |
| const mongoose = require('mongoose'); | |
| const id = req.params[paramName]; | |
| if (!id) { | |
| return res.status(400).json({ | |
| success: false, | |
| error: `Missing required parameter: ${paramName}` | |
| }); | |
| } | |
| if (!mongoose.Types.ObjectId.isValid(id)) { | |
| return res.status(400).json({ | |
| success: false, | |
| error: `Invalid ${paramName} format`, | |
| message: 'Please provide a valid ID' | |
| }); | |
| } | |
| next(); | |
| }; | |
| }; | |
| /** | |
| * Middleware to validate pagination parameters | |
| */ | |
| const validatePagination = (req, res, next) => { | |
| const { page = 1, limit = 20, sortBy = 'createdAt', sortOrder = 'desc' } = req.query; | |
| // Validate page | |
| const pageNum = parseInt(page, 10); | |
| if (isNaN(pageNum) || pageNum < 1) { | |
| return res.status(400).json({ | |
| success: false, | |
| error: 'Invalid page parameter', | |
| message: 'Page must be a positive integer' | |
| }); | |
| } | |
| // Validate limit | |
| const limitNum = parseInt(limit, 10); | |
| if (isNaN(limitNum) || limitNum < 1 || limitNum > 100) { | |
| return res.status(400).json({ | |
| success: false, | |
| error: 'Invalid limit parameter', | |
| message: 'Limit must be between 1 and 100' | |
| }); | |
| } | |
| // Validate sort order | |
| if (!['asc', 'desc'].includes(sortOrder.toLowerCase())) { | |
| return res.status(400).json({ | |
| success: false, | |
| error: 'Invalid sortOrder parameter', | |
| message: 'Sort order must be "asc" or "desc"' | |
| }); | |
| } | |
| // Set validated values | |
| req.pagination = { | |
| page: pageNum, | |
| limit: limitNum, | |
| skip: (pageNum - 1) * limitNum, | |
| sortBy: sortBy.toString(), | |
| sortOrder: sortOrder.toLowerCase() === 'desc' ? -1 : 1 | |
| }; | |
| next(); | |
| }; | |
| /** | |
| * Middleware to validate date range parameters | |
| */ | |
| const validateDateRange = (req, res, next) => { | |
| const { startDate, endDate } = req.query; | |
| if (startDate) { | |
| const start = new Date(startDate); | |
| if (isNaN(start.getTime())) { | |
| return res.status(400).json({ | |
| success: false, | |
| error: 'Invalid startDate format', | |
| message: 'Please provide a valid ISO date string' | |
| }); | |
| } | |
| req.dateRange = { ...req.dateRange, startDate: start }; | |
| } | |
| if (endDate) { | |
| const end = new Date(endDate); | |
| if (isNaN(end.getTime())) { | |
| return res.status(400).json({ | |
| success: false, | |
| error: 'Invalid endDate format', | |
| message: 'Please provide a valid ISO date string' | |
| }); | |
| } | |
| req.dateRange = { ...req.dateRange, endDate: end }; | |
| } | |
| // Validate date range | |
| if (req.dateRange?.startDate && req.dateRange?.endDate) { | |
| if (req.dateRange.startDate >= req.dateRange.endDate) { | |
| return res.status(400).json({ | |
| success: false, | |
| error: 'Invalid date range', | |
| message: 'Start date must be before end date' | |
| }); | |
| } | |
| // Prevent extremely large date ranges (more than 1 year) | |
| const daysDiff = (req.dateRange.endDate - req.dateRange.startDate) / (1000 * 60 * 60 * 24); | |
| if (daysDiff > 365) { | |
| return res.status(400).json({ | |
| success: false, | |
| error: 'Date range too large', | |
| message: 'Date range cannot exceed 365 days' | |
| }); | |
| } | |
| } | |
| next(); | |
| }; | |
| /** | |
| * Middleware to validate file uploads | |
| */ | |
| const validateFileUpload = (allowedTypes = [], maxSize = 5 * 1024 * 1024) => { | |
| return (req, res, next) => { | |
| if (!req.file && !req.files) { | |
| return next(); | |
| } | |
| const files = req.files || [req.file]; | |
| for (const file of files) { | |
| // Check file size | |
| if (file.size > maxSize) { | |
| return res.status(400).json({ | |
| success: false, | |
| error: 'File too large', | |
| message: `File size must be less than ${Math.round(maxSize / (1024 * 1024))}MB` | |
| }); | |
| } | |
| // Check file type | |
| if (allowedTypes.length > 0 && !allowedTypes.includes(file.mimetype)) { | |
| return res.status(400).json({ | |
| success: false, | |
| error: 'Invalid file type', | |
| message: `Allowed types: ${allowedTypes.join(', ')}` | |
| }); | |
| } | |
| // Validate filename | |
| if (!/^[a-zA-Z0-9._-]+$/.test(file.originalname)) { | |
| return res.status(400).json({ | |
| success: false, | |
| error: 'Invalid filename', | |
| message: 'Filename can only contain letters, numbers, dots, underscores, and hyphens' | |
| }); | |
| } | |
| } | |
| next(); | |
| }; | |
| }; | |
| /** | |
| * Middleware to validate search queries | |
| */ | |
| const validateSearchQuery = (req, res, next) => { | |
| const { q, query } = req.query; | |
| const searchQuery = q || query; | |
| if (!searchQuery) { | |
| return res.status(400).json({ | |
| success: false, | |
| error: 'Missing search query', | |
| message: 'Please provide a search query using "q" or "query" parameter' | |
| }); | |
| } | |
| if (typeof searchQuery !== 'string') { | |
| return res.status(400).json({ | |
| success: false, | |
| error: 'Invalid search query', | |
| message: 'Search query must be a string' | |
| }); | |
| } | |
| if (searchQuery.trim().length < 2) { | |
| return res.status(400).json({ | |
| success: false, | |
| error: 'Search query too short', | |
| message: 'Search query must be at least 2 characters long' | |
| }); | |
| } | |
| if (searchQuery.length > 500) { | |
| return res.status(400).json({ | |
| success: false, | |
| error: 'Search query too long', | |
| message: 'Search query must be less than 500 characters' | |
| }); | |
| } | |
| // Sanitize search query | |
| req.searchQuery = searchQuery.trim(); | |
| next(); | |
| }; | |
| /** | |
| * Middleware to validate UGA-specific data | |
| */ | |
| const validateUGAData = { | |
| ugaId: (req, res, next) => { | |
| const { ugaId } = req.body; | |
| if (ugaId && !/^(81|90|70)\d{7}$/.test(ugaId)) { | |
| return res.status(400).json({ | |
| success: false, | |
| error: 'Invalid UGA ID format', | |
| message: 'UGA ID must be 9 digits starting with 81, 90, or 70' | |
| }); | |
| } | |
| next(); | |
| }, | |
| college: (req, res, next) => { | |
| const validColleges = [ | |
| 'Franklin College of Arts & Sciences', | |
| 'Terry College of Business', | |
| 'College of Engineering', | |
| 'Grady College of Journalism & Mass Communication', | |
| 'College of Education', | |
| 'School of Public and International Affairs', | |
| 'College of Agricultural & Environmental Sciences', | |
| 'College of Veterinary Medicine', | |
| 'College of Public Health', | |
| 'School of Law', | |
| 'College of Pharmacy', | |
| 'College of Social Work', | |
| 'Odum School of Ecology', | |
| 'Graduate School', | |
| 'Other' | |
| ]; | |
| const { college } = req.body; | |
| if (college && !validColleges.includes(college)) { | |
| return res.status(400).json({ | |
| success: false, | |
| error: 'Invalid college', | |
| message: 'Please select a valid UGA college', | |
| validOptions: validColleges | |
| }); | |
| } | |
| next(); | |
| }, | |
| classification: (req, res, next) => { | |
| const validClassifications = [ | |
| 'freshman', 'sophomore', 'junior', 'senior', | |
| 'graduate', 'doctoral', 'faculty', 'staff', 'other' | |
| ]; | |
| const { classification } = req.body; | |
| if (classification && !validClassifications.includes(classification)) { | |
| return res.status(400).json({ | |
| success: false, | |
| error: 'Invalid classification', | |
| message: 'Please select a valid classification', | |
| validOptions: validClassifications | |
| }); | |
| } | |
| next(); | |
| } | |
| }; | |
| module.exports = { | |
| handleValidationErrors, | |
| sanitizeInput, | |
| validateObjectId, | |
| validatePagination, | |
| validateDateRange, | |
| validateFileUpload, | |
| validateSearchQuery, | |
| validateUGAData | |
| }; |