This commit is contained in:
@@ -2,20 +2,20 @@ const express = require('express');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const router = express.Router();
|
||||
const fileUpload = require('express-fileupload');
|
||||
const authMiddleware = require('../../../Middlewares/authMiddleware');
|
||||
const bodyParser = require('body-parser');
|
||||
const crypto = require('crypto');
|
||||
const os = require('os');
|
||||
const osUtils = require('os-utils');
|
||||
const Convert = require('ansi-to-html');
|
||||
const convert = new Convert();
|
||||
const { getUserData, getSetupData } = require('../../../Middlewares/watcherMiddleware');
|
||||
const { logger } = require('../../../config/logs');
|
||||
|
||||
// Utilitaires pour la gestion des services
|
||||
const services = {
|
||||
fileCleanup: require('../../../services/fileCleanupService'),
|
||||
reportManager: require('../../../services/reportService')
|
||||
};
|
||||
|
||||
router.use(bodyParser.json());
|
||||
|
||||
// Fonction de nettoyage des objets
|
||||
function clean(obj) {
|
||||
for (var propName in obj) {
|
||||
for (let propName in obj) {
|
||||
if (obj[propName] === null || obj[propName] === undefined || obj[propName] === '') {
|
||||
delete obj[propName];
|
||||
} else if (typeof obj[propName] === 'object') {
|
||||
@@ -27,6 +27,7 @@ function clean(obj) {
|
||||
}
|
||||
}
|
||||
|
||||
// Validation des IPs
|
||||
function validateIP(ip) {
|
||||
if (!ip) return false;
|
||||
|
||||
@@ -46,9 +47,9 @@ function validateIP(ip) {
|
||||
}
|
||||
|
||||
function isIPv4(ip) {
|
||||
const ipv4Regex = /^(\d{1,3}\.){3}\d{1,3}$/;
|
||||
const ipv4Regex = /^\d{1,3}(\.\d{1,3}){3}$/;
|
||||
if (!ipv4Regex.test(ip)) return false;
|
||||
|
||||
|
||||
const parts = ip.split('.');
|
||||
return parts.every(part => {
|
||||
const num = parseInt(part);
|
||||
@@ -61,42 +62,111 @@ function isIPv6(ip) {
|
||||
return ipv6Regex.test(ip);
|
||||
}
|
||||
|
||||
router.get('/', (req, res) => {
|
||||
res.status(400).json({ error: 'Bad Request. The request cannot be fulfilled due to bad syntax or missing parameters.' });
|
||||
});
|
||||
// Fonction pour activer ou désactiver un service
|
||||
async function handleServices(newConfig, oldConfig) {
|
||||
if (!newConfig.services) return;
|
||||
|
||||
router.post('/', authMiddleware, async (req, res) => {
|
||||
try {
|
||||
let setup = JSON.parse(fs.readFileSync(path.join(__dirname, '../../../data', 'setup.json'), 'utf-8'));
|
||||
|
||||
if (req.body.allowedIps) {
|
||||
const ipsArray = Array.isArray(req.body.allowedIps) ? req.body.allowedIps : [req.body.allowedIps];
|
||||
|
||||
req.body.allowedIps = ipsArray
|
||||
.filter(ip => ip && ip.trim())
|
||||
.filter(ip => validateIP(ip.trim()))
|
||||
.map(ip => ip.trim());
|
||||
|
||||
console.log('IPs validées:', req.body.allowedIps);
|
||||
for (const [serviceName, serviceConfig] of Object.entries(newConfig.services)) {
|
||||
const service = services[serviceName];
|
||||
if (!service) {
|
||||
logger.warn(`Service ${serviceName} not found`);
|
||||
continue;
|
||||
}
|
||||
|
||||
clean(req.body);
|
||||
setup[0] = {
|
||||
...setup[0],
|
||||
...req.body
|
||||
};
|
||||
const oldServiceConfig = oldConfig?.services?.[serviceName] || {};
|
||||
const wasEnabled = oldServiceConfig.enabled === 'on'; // ancien état
|
||||
const isEnabled = serviceConfig.enabled === 'on'; // nouvel état
|
||||
|
||||
fs.writeFileSync(
|
||||
path.join(__dirname, '../../../data', 'setup.json'),
|
||||
JSON.stringify(setup, null, 2),
|
||||
'utf-8'
|
||||
);
|
||||
try {
|
||||
logger.info(`Processing service ${serviceName}: wasEnabled=${wasEnabled}, isEnabled=${isEnabled}`);
|
||||
|
||||
res.redirect('/dpanel/dashboard/admin/settingsetup');
|
||||
} catch (err) {
|
||||
console.error('Erreur lors de la mise à jour de la configuration:', err);
|
||||
res.status(500).send('Server Error');
|
||||
if (isEnabled && !wasEnabled) {
|
||||
await service.updateConfig(serviceConfig);
|
||||
await service.start();
|
||||
} else if (!isEnabled && wasEnabled) {
|
||||
await service.stop();
|
||||
} else if (isEnabled && wasEnabled &&
|
||||
JSON.stringify(serviceConfig) !== JSON.stringify(oldServiceConfig)) {
|
||||
await service.stop();
|
||||
await service.updateConfig(serviceConfig);
|
||||
await service.start();
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error(`Error handling service ${serviceName}:`, error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Mise à jour de la configuration et gestion des services
|
||||
async function handleServicesUpdate(newConfig, oldConfig) {
|
||||
if (!newConfig.services) return;
|
||||
|
||||
for (const [serviceName, serviceConfig] of Object.entries(newConfig.services)) {
|
||||
const oldServiceConfig = oldConfig?.services?.[serviceName] || {};
|
||||
await handleServices(serviceName, serviceConfig, oldServiceConfig);
|
||||
}
|
||||
}
|
||||
|
||||
// Route principale pour mettre à jour la configuration
|
||||
router.post('/', async (req, res) => {
|
||||
try {
|
||||
const setupPath = path.join(__dirname, '../../../data', 'setup.json');
|
||||
const oldConfig = JSON.parse(fs.readFileSync(setupPath, 'utf-8'))[0];
|
||||
|
||||
// Validation et traitement des IPs autorisées
|
||||
if (req.body.allowedIps) {
|
||||
let ipsToProcess = Array.isArray(req.body.allowedIps) ? req.body.allowedIps : req.body.allowedIps[""] || [];
|
||||
req.body.allowedIps = ipsToProcess.filter(ip => validateIP(ip.trim())).map(ip => ip.trim());
|
||||
}
|
||||
|
||||
['ldap', 'discord'].forEach(service => {
|
||||
if (req.body[service] && !req.body[service].enabled) {
|
||||
req.body[service] = { enabled: 'off' };
|
||||
}
|
||||
});
|
||||
|
||||
// Traitement des services
|
||||
if (req.body.services) {
|
||||
for (const [key, value] of Object.entries(req.body.services)) {
|
||||
if (typeof value === 'string') {
|
||||
req.body.services[key] = { enabled: 'off', schedule: value }; // Par défaut 'off' et ajouter un schedule si nécessaire
|
||||
}
|
||||
|
||||
// Si l'état n'est pas 'on' ou 'off', on le met à 'off'
|
||||
if (value.enabled !== 'on' && value.enabled !== 'off') {
|
||||
req.body.services[key].enabled = 'off';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Traitement des logs
|
||||
if (req.body.logs) {
|
||||
req.body.logs = {
|
||||
enabled: req.body.logs.enabled || "on",
|
||||
excludePaths: Array.isArray(req.body.logs.excludePaths) ? req.body.logs.excludePaths : [],
|
||||
includeOnly: Array.isArray(req.body.logs.includeOnly) ? req.body.logs.includeOnly : [],
|
||||
levels: Array.isArray(req.body.logs.levels) ? req.body.logs.levels : []
|
||||
};
|
||||
}
|
||||
|
||||
// Fusion des anciennes et nouvelles configurations
|
||||
const newConfig = { ...oldConfig, ...req.body };
|
||||
clean(newConfig);
|
||||
|
||||
// Mise à jour des services
|
||||
await handleServicesUpdate(newConfig, oldConfig);
|
||||
|
||||
// Sauvegarde de la nouvelle configuration
|
||||
fs.writeFileSync(setupPath, JSON.stringify([newConfig], null, 2));
|
||||
|
||||
res.status(200).json({ message: 'Configuration mise à jour avec succès.' });
|
||||
} catch (error) {
|
||||
logger.error('Erreur lors de la mise à jour de la configuration:', error);
|
||||
res.status(500).json({ error: 'Erreur interne du serveur.' });
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
|
||||
module.exports = router;
|
||||
|
||||
@@ -3,6 +3,7 @@ const fs = require('fs');
|
||||
const path = require('path');
|
||||
const multiparty = require('multiparty');
|
||||
const router = express.Router();
|
||||
const bcrypt = require('bcrypt');
|
||||
|
||||
// Limite de taille de fichier à 10 Go
|
||||
const MAX_FILE_SIZE = 10 * 1024 * 1024 * 1024; // 10 Go
|
||||
@@ -19,7 +20,7 @@ router.post('/', (req, res) => {
|
||||
maxFilesSize: MAX_FILE_SIZE,
|
||||
});
|
||||
|
||||
form.parse(req, (err, fields, files) => {
|
||||
form.parse(req, async (err, fields, files) => {
|
||||
if (err) {
|
||||
console.error('Error parsing the file:', err);
|
||||
return res.status(400).send('Error during the file upload');
|
||||
@@ -30,12 +31,20 @@ router.post('/', (req, res) => {
|
||||
}
|
||||
|
||||
const file = files.file[0];
|
||||
// Modifier le chemin pour être relatif à la racine
|
||||
const userDir = path.join(process.cwd(), 'cdn-files', req.user.name);
|
||||
|
||||
// Utiliser le nom sécurisé fourni par le client
|
||||
const filename = fields.filename ? fields.filename[0] : file.originalFilename;
|
||||
const filePath = path.join(userDir, filename);
|
||||
|
||||
// Récupérer les champs supplémentaires
|
||||
const expiryDate = fields.expiryDate ? fields.expiryDate[0] : '';
|
||||
const password = fields.password ? fields.password[0] : '';
|
||||
|
||||
// Hasher le mot de passe si présent
|
||||
const saltRounds = 10;
|
||||
let hashedPassword = '';
|
||||
if (password) {
|
||||
hashedPassword = await bcrypt.hash(password, saltRounds);
|
||||
}
|
||||
|
||||
// Crée le répertoire s'il n'existe pas
|
||||
if (!fs.existsSync(userDir)) {
|
||||
@@ -48,7 +57,7 @@ router.post('/', (req, res) => {
|
||||
|
||||
readStream.pipe(writeStream);
|
||||
|
||||
readStream.on('end', () => {
|
||||
readStream.on('end', async () => {
|
||||
// Supprimer le fichier temporaire
|
||||
fs.unlinkSync(file.path);
|
||||
|
||||
@@ -57,6 +66,35 @@ router.post('/', (req, res) => {
|
||||
if (!fileNamePattern.test(filename)) {
|
||||
console.warn('Le fichier uploadé ne suit pas le format de nom sécurisé attendu:', filename);
|
||||
}
|
||||
|
||||
// Mettre à jour file_info.json si password ou expiryDate présent
|
||||
if (expiryDate || password) {
|
||||
const fileInfo = {
|
||||
fileName: filename,
|
||||
expiryDate: expiryDate,
|
||||
password: hashedPassword,
|
||||
Id: req.user.id,
|
||||
path: filePath
|
||||
};
|
||||
|
||||
try {
|
||||
let data = [];
|
||||
const fileInfoPath = path.join(__dirname, '../../../data', 'file_info.json');
|
||||
|
||||
if (fs.existsSync(fileInfoPath)) {
|
||||
const existingData = await fs.promises.readFile(fileInfoPath, 'utf8');
|
||||
data = JSON.parse(existingData);
|
||||
if (!Array.isArray(data)) {
|
||||
data = [];
|
||||
}
|
||||
}
|
||||
|
||||
data.push(fileInfo);
|
||||
await fs.promises.writeFile(fileInfoPath, JSON.stringify(data, null, 2));
|
||||
} catch (error) {
|
||||
console.error('Error updating file_info.json:', error);
|
||||
}
|
||||
}
|
||||
|
||||
res.status(200).send({
|
||||
message: 'File uploaded successfully.',
|
||||
|
||||
Reference in New Issue
Block a user