218 lines
6.7 KiB
JavaScript
218 lines
6.7 KiB
JavaScript
const express = require('express');
|
|
const router = express.Router();
|
|
const path = require('path');
|
|
const fs = require('fs').promises;
|
|
const mime = require('mime-types');
|
|
const { logger, ErrorLogger } = require('../config/logs');
|
|
const bcrypt = require('bcrypt');
|
|
const saltRounds = 10;
|
|
|
|
const baseDir = 'cdn-files';
|
|
|
|
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) {
|
|
const files = await fs.readdir(dir, { withFileTypes: true });
|
|
|
|
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');
|
|
let fileInfoArray;
|
|
try {
|
|
fileInfoArray = JSON.parse(data);
|
|
} catch (error) {
|
|
console.error('Error parsing file_info.json:', error);
|
|
}
|
|
|
|
if (!Array.isArray(fileInfoArray)) {
|
|
console.error('fileInfoArray is not an array');
|
|
fileInfoArray = [];
|
|
}
|
|
|
|
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 fileContent = await fs.readFile(filePath);
|
|
let mimeType = mime.lookup(filePath);
|
|
|
|
if (!mimeType) {
|
|
if (filePath.endsWith('.txt')) {
|
|
mimeType = 'text/plain';
|
|
} else if (filePath.endsWith('.pdf')) {
|
|
mimeType = 'application/pdf';
|
|
}
|
|
}
|
|
|
|
if (mimeType) {
|
|
res.setHeader('Content-Type', mimeType);
|
|
}
|
|
|
|
if (mimeType === 'text/plain') {
|
|
res.end(fileContent);
|
|
} else {
|
|
res.send(fileContent);
|
|
}
|
|
|
|
if (fileInfo) {
|
|
req.session.passwordVerified = false;
|
|
}
|
|
} catch (err) {
|
|
ErrorLogger.error('Error reading file:', err);
|
|
return 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');
|
|
let fileInfoArray;
|
|
try {
|
|
fileInfoArray = JSON.parse(data);
|
|
} catch (error) {
|
|
console.error('Error parsing file_info.json:', error);
|
|
}
|
|
|
|
if (!Array.isArray(fileInfoArray)) {
|
|
console.error('fileInfoArray is not an array');
|
|
fileInfoArray = [];
|
|
}
|
|
|
|
const fileInfo = fileInfoArray.find(info => info.fileName === filename && info.Id === userId);
|
|
|
|
if (!fileInfo) {
|
|
return res.json({ success: false, message: 'File not found' });
|
|
}
|
|
|
|
if (bcrypt.compareSync(enteredPassword, fileInfo.password)) {
|
|
req.session.passwordVerified = true;
|
|
const filePath = await findFileInUserDir(userId, filename);
|
|
const fileContent = await fs.readFile(filePath);
|
|
let mimeType = mime.lookup(filePath);
|
|
|
|
if (!mimeType) {
|
|
if (filePath.endsWith('.txt')) {
|
|
mimeType = 'text/plain';
|
|
} else if (filePath.endsWith('.pdf')) {
|
|
mimeType = 'application/pdf';
|
|
}
|
|
}
|
|
|
|
res.json({ success: true, fileContent: fileContent.toString('base64'), mimeType });
|
|
} else {
|
|
res.json({ success: false, message: 'Incorrect password' });
|
|
}
|
|
} catch (err) {
|
|
ErrorLogger.error('Error reading file:', err);
|
|
return res.status(500).send('Error reading file.');
|
|
}
|
|
});
|
|
|
|
async function deleteExpiredFiles() {
|
|
let data = await fs.readFile(path.join(__dirname, '../data', 'file_info.json'), 'utf8');
|
|
let fileInfoArray;
|
|
try {
|
|
fileInfoArray = JSON.parse(data);
|
|
} catch (error) {
|
|
console.error('Error parsing file_info.json:', error);
|
|
}
|
|
|
|
if (!Array.isArray(fileInfoArray)) {
|
|
console.error('fileInfoArray is not an array');
|
|
fileInfoArray = [];
|
|
}
|
|
|
|
const now = new Date();
|
|
let newFileInfoArray = [];
|
|
|
|
for (let i = 0; i < fileInfoArray.length; i++) {
|
|
const fileInfo = fileInfoArray[i];
|
|
let expiryDate;
|
|
if (fileInfo.expiryDate && fileInfo.expiryDate.trim() !== '') {
|
|
expiryDate = new Date(fileInfo.expiryDate);
|
|
} else {
|
|
continue;
|
|
}
|
|
|
|
if (expiryDate < now) {
|
|
const samaccountname = await getSamAccountNameFromUserId(fileInfo.userId);
|
|
const userDir = path.join(baseDir, samaccountname);
|
|
const filePath = path.join(userDir, fileInfo.fileName);
|
|
try {
|
|
await fs.unlink(filePath);
|
|
} catch (err) {
|
|
ErrorLogger.error('Error deleting file:', err);
|
|
}
|
|
} else {
|
|
newFileInfoArray.push(fileInfo);
|
|
}
|
|
}
|
|
|
|
try {
|
|
await fs.writeFile(path.join(__dirname, '../data', 'file_info.json'), JSON.stringify(newFileInfoArray, null, 2), 'utf8');
|
|
} catch (err) {
|
|
ErrorLogger.error('Error writing to file_info.json:', err);
|
|
}
|
|
}
|
|
|
|
setInterval(deleteExpiredFiles, 24 * 60 * 60 * 1000);
|
|
|
|
module.exports = router; |