Phase 5: Upload — multer, UUID filenames, MIME whitelist, /uploads static

This commit is contained in:
Suslov-MD
2026-08-16 08:07:33 +00:00
parent 62c82da7af
commit 281daa4717
4 changed files with 279 additions and 2 deletions
+5 -2
View File
@@ -8,6 +8,7 @@ import { notFoundHandler } from './middleware/notFound.middleware.js';
import authRouter from './routes/auth.routes.js';
import healthRouter from './routes/health.routes.js';
import newsRouter from './routes/news.routes.js';
import uploadRouter from './routes/upload.routes.js';
/**
* Создаёт и настраивает Express-приложение.
@@ -33,13 +34,15 @@ export function createApp(extraMiddleware?: express.RequestHandler): express.Exp
app.use(json());
app.use(urlencoded({ extended: true }));
// Статические загруженные файлы (Phase 5)
// app.use('/uploads', express.static(env.uploadDir));
// Статические загруженные файлы
// eslint-disable-next-line import-x/no-named-as-default-member -- express.static стандартный API
app.use('/uploads', express.static(env.uploadDir));
// API-маршруты
app.use('/api', healthRouter);
app.use('/api/auth', authRouter);
app.use('/api/news', newsRouter);
app.use('/api/uploads', uploadRouter);
// Дополнительные middleware (тестовые маршруты, заглушки)
if (extraMiddleware) {
@@ -0,0 +1,76 @@
import { randomUUID } from 'node:crypto';
import multer, { type FileFilterCallback } from 'multer';
import { env } from '../config/env.js';
/**
* Разрешённые MIME-типы для загрузки.
*/
const ALLOWED_MIME_TYPES = new Set([
'image/jpeg',
'image/png',
'image/gif',
'image/webp',
'application/pdf',
'application/msword',
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
]);
/**
* Расширения файлов для генерации safe filename.
* Ключ — MIME-тип, значение — расширение.
*/
const MIME_EXTENSIONS: Record<string, string> = {
'image/jpeg': 'jpg',
'image/png': 'png',
'image/gif': 'gif',
'image/webp': 'webp',
'application/pdf': 'pdf',
'application/msword': 'doc',
'application/vnd.openxmlformats-officedocument.wordprocessingml.document': 'docx',
};
/**
* Проверка MIME-типа загружаемого файла.
*
* @param _req — запрос Express
* @param file — файл из multer
* @param cb — callback multer
*/
function checkMimeType(_req: unknown, file: { mimetype: string }, cb: FileFilterCallback): void {
if (ALLOWED_MIME_TYPES.has(file.mimetype)) {
cb(null, true);
} else {
const err = new Error(
`Недопустимый тип файла: ${file.mimetype}. Разрешены: изображения (jpg, png, gif, webp), PDF, Word (doc, docx)`,
);
cb(err);
}
}
/**
* Настройка multer:
* - diskStorage в env.uploadDir
* - UUID-based filenames (без пользовательского имени)
* - MIME whitelist
* - Size limit из env
*/
export const upload = multer({
// eslint-disable-next-line import-x/no-named-as-default-member -- multer.diskStorage стандартный API
storage: multer.diskStorage({
destination: (_req, _file, cb) => {
cb(null, env.uploadDir);
},
filename: (_req, file, cb) => {
// Генерируем безопасное имя: UUID + расширение по MIME
const ext = MIME_EXTENSIONS[file.mimetype] ?? 'bin';
cb(null, `${randomUUID()}.${ext}`);
},
}),
limits: {
fileSize: env.maxUploadSize,
files: 1,
},
fileFilter: checkMimeType,
});
+68
View File
@@ -0,0 +1,68 @@
import { Router, type Request, type Response } from 'express';
import { requireAuth, type AuthenticatedRequest } from '../middleware/auth.middleware.js';
import { upload } from '../middleware/upload.middleware.js';
import { ApiError } from '../utils/ApiError.js';
import { asyncHandler } from '../utils/asyncHandler.js';
const uploadRouter = Router();
/**
* Обёртка для multer: конвертирует multer errors в ApiError (400/413).
*/
function multerHandler(fileFilter: 'file') {
return (req: Request, res: Response, next: (err?: unknown) => void): void => {
upload.single(fileFilter)(req, res, (err: unknown) => {
if (err instanceof ApiError) {
next(err);
return;
}
if (err !== null && err !== undefined) {
// MulterError или ошибка fileFilter
const message = err instanceof Error ? err.message : 'Ошибка загрузки';
const isFileSize = message.includes('File too large');
next(new ApiError(isFileSize ? 413 : 400, 'UPLOAD_ERROR', message));
return;
}
next();
});
};
}
/**
* POST /api/uploads
* Загрузка одного файла. Требует авторизацию.
*
* @returns 201 { file: { name, url } }
* - name: имя файла на диске (UUID.ext)
* - url: путь для доступа /uploads/<name>
*/
uploadRouter.post(
'/',
requireAuth,
multerHandler('file'),
// eslint-disable-next-line @typescript-eslint/require-await -- asyncHandler требует async
asyncHandler(async (req: Request, res: Response) => {
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- req расширен middleware
const authedReq = req as AuthenticatedRequest;
if (!authedReq.user) {
throw new ApiError(401, 'UNAUTHORIZED', 'Требуется авторизация');
}
// Multer устанавливает req.file при успешной загрузке
if (!req.file) {
throw new ApiError(400, 'NO_FILE', 'Файл не был загружен');
}
const fileName = req.file.filename;
res.status(201).json({
file: {
name: fileName,
url: `/uploads/${fileName}`,
},
});
}),
);
export default uploadRouter;