fcsc_ipi_backend/app/controllers/logController.js
2025-12-30 11:41:07 +05:30

67 lines
1.9 KiB
JavaScript

// controllers/logController.js
const fs = require('fs').promises;
const path = require('path');
const LOG_DIR = path.join(__dirname, '../writable/logs');
exports.viewLogs = async (req, res) => {
try {
const files = await fs.readdir(LOG_DIR);
const logFiles = files.filter(file => file.endsWith('.log')).sort().reverse();
res.render('logs/viewer', {
title: 'Log Viewer',
logFiles
});
} catch (error) {
console.error('Error reading log directory:', error);
res.status(500).render('error', {
message: 'Unable to load log files',
error
});
}
};
exports.getLogContent = async (req, res) => {
try {
const { filename } = req.params;
const filePath = path.join(LOG_DIR, filename);
// Security check: ensure the file is within LOG_DIR
const realPath = await fs.realpath(filePath);
if (!realPath.startsWith(await fs.realpath(LOG_DIR))) {
return res.status(403).json({ error: 'Access denied' });
}
const content = await fs.readFile(filePath, 'utf-8');
const lines = content.split('\n').filter(line => line.trim());
res.json({
filename,
content,
lines: lines.reverse(), // Most recent first
lineCount: lines.length
});
} catch (error) {
console.error('Error reading log file:', error);
res.status(500).json({ error: 'Unable to read log file' });
}
};
exports.downloadLog = async (req, res) => {
try {
const { filename } = req.params;
const filePath = path.join(LOG_DIR, filename);
// Security check
const realPath = await fs.realpath(filePath);
if (!realPath.startsWith(await fs.realpath(LOG_DIR))) {
return res.status(403).send('Access denied');
}
res.download(filePath);
} catch (error) {
console.error('Error downloading log file:', error);
res.status(500).send('Unable to download log file');
}
};