const fs = require('fs').promises; const path = require('path'); /** * Middleware kiểm tra giới hạn lưu trữ của người dùng * Dựa trên cấu trúc storage (used/quota) và role mới. */ const checkQuota = async (req, res, next) => { if (!req.user) return res.status(401).json({ message: 'Vui lòng đăng nhập' }); // Admin được miễn trừ kiểm tra dung lượng if (req.user.role === 'admin') return next(); // Lấy dữ liệu từ req.user (đã được authMiddleware nạp từ DB) const used = req.user.storage?.used || 0; const quota = req.user.storage?.quota || 0; const newFileSize = req.file ? req.file.size : 0; // Kiểm tra nếu tổng dung lượng sau khi upload vượt quá hạn mức if (used + newFileSize > quota) { // Xóa ngay file tạm vừa được multer lưu vào disk để giải phóng tài nguyên server if (req.file && req.file.path) { await fs.unlink(req.file.path).catch(err => console.error('[Quota Middleware] Lỗi xóa file tạm:', err.message) ); } return res.status(403).json({ message: 'Dung lượng lưu trữ của bạn đã hết hoặc không đủ để thực hiện thao tác này.', storage: { used: `${(used / (1024 * 1024)).toFixed(2)} MB`, quota: `${(quota / (1024 * 1024)).toFixed(2)} MB`, required: `${(newFileSize / (1024 * 1024)).toFixed(2)} MB` } }); } next(); }; module.exports = { checkQuota };