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 { loggers } = require('winston'); const ncp = require('ncp').ncp; const configFile = fs.readFileSync(path.join(__dirname, '../../../data', 'setup.json'), 'utf-8') const config = JSON.parse(configFile); const bodyParser = require('body-parser'); const crypto = require('crypto'); const os = require('os'); const { getUserData, getSetupData } = require('../../../Middlewares/watcherMiddleware'); const { logger, logRequestInfo, ErrorLogger, authLogger } = require('../../../config/logs'); let setupData = getSetupData(); let userData = getUserData(); router.use(bodyParser.json()); /** * @swagger * /dashboard/rename?token={token}: * post: * security: * - bearerAuth: [] * tags: * - File * summary: Rename a file * description: This route allows you to rename a file. It requires a valid JWT token in the Authorization header. * requestBody: * required: true * content: * application/json: * schema: * type: object * properties: * currentName: * type: string * description: The current name of the file * newName: * type: string * description: The new name for the file * parameters: * - in: header * name: Authorization * required: true * schema: * type: string * description: The JWT token of your account to have access * responses: * 200: * description: Success * content: * application/json: * schema: * type: object * properties: * message: * type: string * 400: * description: Bad Request * content: * application/json: * schema: * type: object * properties: * message: * type: string * 401: * description: Unauthorized * content: * application/json: * schema: * type: object * properties: * message: * type: string * 500: * description: Error renaming the file * content: * application/json: * schema: * type: object * properties: * message: * type: string * error: * type: string */ function authenticateToken(req, res, next) { let token = null; const authHeader = req.headers['authorization']; if (authHeader) { token = authHeader.split(' ')[1]; } else if (req.query.token) { token = req.query.token; } if (token == null) { if (req.user) { return next(); } else { return res.status(401).json({ message: 'Unauthorized' }); } } fs.readFile(path.join(__dirname, '../../../data', 'user.jso,'), 'utf8', (err, data) => { if (err) { console.error('Error reading user.json:', err); return res.status(401).json({ message: 'Unauthorized' }); } const users = JSON.parse(data); const user = users.find(u => u.token === token); if (user) { console.log('User found:', user); req.user = user; req.userData = user; next(); } else { console.log('No user found for token:', token); return res.status(401).json({ message: 'Unauthorized' }); } }); } router.get('/', (req, res) => { res.status(400).json({ error: 'Bad Request. The request cannot be fulfilled due to bad syntax or missing parameters.' }); }); router.post('/', authMiddleware, async (req, res) => { const userId = req.userData.name; const { currentName, newName } = req.body; const filePath = path.join(req.params.filePath || '', req.params[0] || ''); if (!currentName || !newName) { return res.status(400).json('Both currentName and newName must be provided.'); } const userDir = path.join('cdn-files', userId); const currentPath = path.join(userDir, filePath, currentName); const newPath = path.join(userDir, filePath, newName); if (!currentPath.startsWith(userDir) || !newPath.startsWith(userDir)) { ErrorLogger.error('Unauthorized directory access attempt'); return res.status(403).json('Unauthorized directory access attempt'); } try { await fs.promises.rename(currentPath, newPath); const data = await fs.promises.readFile(path.join(__dirname, '../../../data', 'file_info.json'), 'utf8'); let fileInfo = JSON.parse(data); let found = false; for (let i = 0; i < fileInfo.length; i++) { if (fileInfo[i].fileName === currentName) { fileInfo[i].fileName = newName; found = true; break; } } if (found) { await fs.promises.writeFile(path.join(__dirname, '../../../data', 'file_info.json'), JSON.stringify(fileInfo, null, 2), 'utf8'); } res.status(200).json('Operation was successful.'); } catch (err) { console.error(err); return res.status(500).json('Error renaming the file.'); } }); router.post('/:filePath*', authMiddleware, async (req, res) => { const userId = req.userData.name; const { currentName, newName } = req.body; const filePath = path.join(req.params.filePath, req.params[0] || ''); if (!currentName || !newName) { return res.status(400).json('Both currentName and newName must be provided.'); } const userDir = path.join('cdn-files', userId); const currentPath = path.join(userDir, filePath, currentName); const newPath = path.join(userDir, filePath, newName); if (!currentPath.startsWith(userDir) || !newPath.startsWith(userDir)) { ErrorLogger.error('Unauthorized directory access attempt'); return res.status(403).json('Unauthorized directory access attempt'); } try { await fs.promises.rename(currentPath, newPath); const data = await fs.promises.readFile(path.join(__dirname, '../../../data', 'file_info.json'), 'utf8'); let fileInfo = JSON.parse(data); let found = false; for (let i = 0; i < fileInfo.length; i++) { if (fileInfo[i].fileName === currentName) { fileInfo[i].fileName = newName; found = true; break; } } if (found) { await fs.promises.writeFile(path.join(__dirname, '../../../data', 'file_info.json'), JSON.stringify(fileInfo, null, 2), 'utf8'); } res.status(200).json('Operation was successful.'); } catch (err) { console.error(err); return res.status(500).json('Error renaming the file.'); } }); module.exports = router;