All checks were successful
continuous-integration/drone/push Build is passing
✨ New Features: - Dynamic permission-based context menus for files and folders - Support for collaborative folder access control - Upload to specific folders including shared folders - Changelog modal for version updates - Improved dark mode synchronization 🐛 Bug Fixes: - Fixed context menu displaying incorrect options - Fixed CSS !important override preventing dynamic menu behavior - Fixed folder collaboration permission checks - Fixed breadcrumb navigation with empty segments - Fixed "Premature close" error loop in attachments - Fixed missing user variable in admin routes - Fixed avatar loading COEP policy issues 🔒 Security: - Added security middleware (CSRF, rate limiting, input validation) - Fixed collaboration folder access validation - Improved shared folder permission handling 🎨 UI/UX Improvements: - Removed Actions column from folder view - Context menu now properly hides/shows based on permissions - Better visual feedback for collaborative folders - Improved upload flow with inline modals 🧹 Code Quality: - Added collaboration data to folder routes - Refactored context menu logic for better maintainability - Added debug logging for troubleshooting - Improved file upload handling with chunking support
170 lines
5.9 KiB
JavaScript
170 lines
5.9 KiB
JavaScript
const express = require('express');
|
|
const router = express.Router();
|
|
const path = require('path');
|
|
const fs = require('fs').promises;
|
|
const fsStandard = require('fs');
|
|
const mime = require('mime-types');
|
|
const { logger, ErrorLogger } = require('../config/logs');
|
|
const bcrypt = require('bcrypt');
|
|
const compression = require('compression');
|
|
const { pipeline } = require('stream/promises'); // Utilisation du pipeline moderne
|
|
const baseDir = 'cdn-files';
|
|
|
|
// Middleware de compression gzip
|
|
router.use(compression());
|
|
|
|
async function getSamAccountNameFromUserId(userId) {
|
|
const data = await fs.readFile(path.join(__dirname, '../data', 'user.json'), 'utf8');
|
|
const users = JSON.parse(data);
|
|
const user = users.find(user => user.id === userId);
|
|
if (user) {
|
|
return user.name;
|
|
} else {
|
|
throw new Error('User not found');
|
|
}
|
|
}
|
|
|
|
async function findFileInUserDir(userId, filename) {
|
|
const samaccountname = await getSamAccountNameFromUserId(userId);
|
|
const userDir = path.join(baseDir, samaccountname);
|
|
return findFileInDir(userDir, filename);
|
|
}
|
|
|
|
async function findFileInDir(dir, filename) {
|
|
let files;
|
|
try {
|
|
files = await fs.readdir(dir, { withFileTypes: true });
|
|
} catch (err) {
|
|
return null; // Directory does not exist
|
|
}
|
|
|
|
for (const file of files) {
|
|
const filePath = path.join(dir, file.name);
|
|
|
|
if (file.name === filename && file.isFile()) {
|
|
return filePath;
|
|
} else if (file.isDirectory()) {
|
|
const found = await findFileInDir(filePath, filename);
|
|
if (found) {
|
|
return found;
|
|
}
|
|
}
|
|
}
|
|
|
|
return null;
|
|
}
|
|
|
|
router.get('/:userId', (req, res) => {
|
|
res.render('unauthorized');
|
|
});
|
|
|
|
router.get('/:userId/:filename', async (req, res) => {
|
|
const { userId, filename } = req.params;
|
|
|
|
try {
|
|
const filePath = await findFileInUserDir(userId, filename);
|
|
if (!filePath) {
|
|
return res.render('file-not-found');
|
|
}
|
|
|
|
const data = await fs.readFile(path.join(__dirname, '../data', 'file_info.json'), 'utf8');
|
|
const fileInfoArray = JSON.parse(data);
|
|
|
|
const fileInfo = fileInfoArray.find(info => info.fileName === filename && info.Id === userId);
|
|
if (fileInfo) {
|
|
const expiryDate = new Date(fileInfo.expiryDate);
|
|
const now = new Date();
|
|
|
|
if (expiryDate < now) {
|
|
await fs.unlink(filePath);
|
|
return res.render('file-expired');
|
|
}
|
|
|
|
if (fileInfo.password && !req.session.passwordVerified) {
|
|
return res.render('password-check', { userId, filename });
|
|
}
|
|
}
|
|
|
|
const mimeType = mime.lookup(filePath) || 'application/octet-stream';
|
|
const range = req.headers.range;
|
|
const stats = await fs.stat(filePath);
|
|
const fileSize = stats.size;
|
|
|
|
if (range) {
|
|
const [start, end] = range.replace(/bytes=/, '').split('-');
|
|
const chunkStart = parseInt(start, 10);
|
|
const chunkEnd = end ? parseInt(end, 10) : fileSize - 1;
|
|
|
|
if (chunkStart >= fileSize || chunkEnd >= fileSize) {
|
|
res.setHeader('Content-Range', `bytes */${fileSize}`);
|
|
return res.status(416).send('Requested Range Not Satisfiable');
|
|
}
|
|
|
|
res.status(206);
|
|
res.setHeader('Content-Range', `bytes ${chunkStart}-${chunkEnd}/${fileSize}`);
|
|
res.setHeader('Accept-Ranges', 'bytes');
|
|
res.setHeader('Content-Length', chunkEnd - chunkStart + 1);
|
|
res.setHeader('Content-Type', mimeType);
|
|
|
|
const readStream = fsStandard.createReadStream(filePath, { start: chunkStart, end: chunkEnd });
|
|
await pipeline(readStream, res); // Utilisation de pipeline avec await pour éviter les erreurs
|
|
} else {
|
|
res.setHeader('Content-Length', fileSize);
|
|
res.setHeader('Content-Type', mimeType);
|
|
|
|
const readStream = fsStandard.createReadStream(filePath);
|
|
await pipeline(readStream, res);
|
|
}
|
|
} catch (err) {
|
|
// Ne pas logger les fermetures prématurées côté client (comportement normal)
|
|
// Cela se produit quand l'utilisateur annule le téléchargement, ferme le navigateur, etc.
|
|
if (err.code !== 'ERR_STREAM_PREMATURE_CLOSE' && err.code !== 'ECONNRESET' && err.code !== 'EPIPE') {
|
|
ErrorLogger.error('Error handling request:', err);
|
|
}
|
|
if (!res.headersSent) {
|
|
res.status(500).send('Error reading file.');
|
|
}
|
|
}
|
|
});
|
|
|
|
router.post('/:userId/:filename', async (req, res) => {
|
|
const { userId, filename } = req.params;
|
|
const enteredPassword = req.body.password;
|
|
|
|
try {
|
|
const data = await fs.readFile(path.join(__dirname, '../data', 'file_info.json'), 'utf8');
|
|
const fileInfoArray = JSON.parse(data);
|
|
|
|
const fileInfo = fileInfoArray.find(info => info.fileName === filename && info.Id === userId);
|
|
|
|
if (!fileInfo) {
|
|
return res.json({ success: false, message: 'File not found' });
|
|
}
|
|
|
|
const passwordMatch = await bcrypt.compare(enteredPassword, fileInfo.password);
|
|
if (passwordMatch) {
|
|
req.session.passwordVerified = true;
|
|
|
|
const filePath = await findFileInUserDir(userId, filename);
|
|
const mimeType = mime.lookup(filePath) || 'application/octet-stream';
|
|
const readStream = fsStandard.createReadStream(filePath);
|
|
|
|
let fileContent = '';
|
|
for await (const chunk of readStream) {
|
|
fileContent += chunk.toString('base64');
|
|
}
|
|
|
|
res.json({ success: true, fileContent, mimeType });
|
|
} else {
|
|
res.json({ success: false, message: 'Incorrect password' });
|
|
}
|
|
} catch (err) {
|
|
ErrorLogger.error('Error reading file:', err);
|
|
if (!res.headersSent) {
|
|
res.status(500).send('Error reading file.');
|
|
}
|
|
}
|
|
});
|
|
|
|
module.exports = router;
|