Blame Raw
Cohee · 51ad27fb · · 44 lines (1.6 KB)
2 contributors
1import path from 'node:path';
2
3export const forbiddenRegExp = path.sep === '/' ? /[/\x00]/ : /[/\x00\\]/;
4
5/**
6 * Checks if an object has a toString method.
7 * @param {object} o Object to check
8 * @returns {boolean} True if the object has a toString method, false otherwise
9 */
10function hasToString(o) {
11 return o != null && typeof o.toString === 'function';
12}
13
14/**
15 * Gets a middleware function that validates the field in the request body.
16 * @param {string} fieldName Field name
17 * @returns {import('express').RequestHandler} Middleware function
18 */
19export function getFileNameValidationFunction(fieldName) {
20 /**
21 * Validates the field in the request body.
22 * @param {import('express').Request} req Request object
23 * @param {import('express').Response} res Response object
24 * @param {import('express').NextFunction} next Next middleware
25 */
26 return function validateAvatarUrlMiddleware(req, res, next) {
27 if (req.body && fieldName in req.body && (typeof req.body[fieldName] === 'string' || hasToString(req.body[fieldName]))) {
28 if (forbiddenRegExp.test(req.body[fieldName])) {
29 console.error('An error occurred while validating the request body', {
30 handle: req.user.profile.handle,
31 path: req.originalUrl,
32 field: fieldName,
33 value: req.body[fieldName],
34 });
35 return res.sendStatus(400);
36 }
37 }
38
39 next();
40 };
41}
42
43const avatarUrlValidationFunction = getFileNameValidationFunction('avatar_url');
44export default avatarUrlValidationFunction;