Files
CDN-APP-INSIDER/routes/Dpanel/API/Upload.js
Dinawo aaff0ed4ea
All checks were successful
continuous-integration/drone/push Build is passing
Urgent correction of version v1.0.0-beta.14 due to crash issues when acting on the CDN.
We would like to apologize for the inconvenience caused and we would like to thank you for the quick report.
2024-07-12 18:07:19 +02:00

206 lines
6.4 KiB
JavaScript

const express = require('express');
const fs = require('fs');
const path = require('path');
const router = express.Router();
const fileUpload = require('express-fileupload');
const { loggers } = require('winston');
const ncp = require('ncp');
const util = require('util');
const configFile = fs.readFileSync(path.join(__dirname, '../../../data', 'setup.json'), 'utf-8')
const config = JSON.parse(configFile);
const bodyParser = require('body-parser');
const jwt = require('jsonwebtoken');
const authMiddleware = require('../../../Middlewares/authMiddleware');
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
* /dpanel/upload?token={token}:
* post:
* security:
* - bearerAuth: []
* tags:
* - File
* summary: Upload a file
* description: This route allows you to upload a file. It requires a valid JWT token in the Authorization header.
* requestBody:
* required: true
* content:
* multipart/form-data:
* schema:
* type: object
* properties:
* file:
* type: string
* format: binary
* description: The file to upload
* expiryDate:
* type: string
* format: date-time
* description: The expiry date of the file
* password:
* type: string
* description: The password to protect 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 uploading 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.jso,:', err);
return res.status(401).json({ message: 'Unauthorized' });
}
const users = JSON.parse(data);
const user = users.find(u => u.token === token);
if (user) {
req.user = user;
next();
} else {
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.use(fileUpload({
limits: { fileSize: 15 * 1024 * 1024 * 1024 },
}));
router.post('/', authenticateToken, async (req, res) => {
try {
if (!req.files || Object.keys(req.files).length === 0) {
return res.status(400).send('5410 - Download error, please try again later.');
}
const file = req.files.file;
const userId = req.user.name;
const Id = req.user.id;
const uploadDir = path.join('cdn-files', userId);
const originalFileName = file.name;
const domain = config.domain || 'mydomain.com';
let expiryDate = req.body.expiryDate;
let password = req.body.password;
if (!fs.existsSync(uploadDir)) {
fs.mkdirSync(uploadDir, { recursive: true });
}
file.mv(path.join(uploadDir, originalFileName), async (err) => {
if (err) {
console.error(err);
return res.status(500).send({ message: 'Error downloading file.' });
}
const fileExtension = path.extname(originalFileName).toLowerCase();
const bcrypt = require('bcrypt');
const saltRounds = 10;
let hashedPassword = '';
if (password) {
hashedPassword = bcrypt.hashSync(password, saltRounds);
}
const fileInfo = {
fileName: originalFileName,
expiryDate: expiryDate || '',
password: hashedPassword,
Id: Id,
path: path.join(uploadDir, originalFileName)
};
if (expiryDate || password) {
let data = [];
if (fs.existsSync(path.join(__dirname, '../../../data', 'file_info.json'))) {
const existingData = await fs.promises.readFile(path.join(__dirname, '../../../data', 'file_info.json'), 'utf8');
data = JSON.parse(existingData);
if (!Array.isArray(data)) {
data = [];
}
}
data.push(fileInfo);
await fs.promises.writeFile(path.join(__dirname, '../../../data', 'file_info.json'), JSON.stringify(data, null, 2));
}
res.status(200).send({ message: 'Your file has been successfully uploaded.' });
});
} catch (error) {
console.error(error);
return res.status(500).send({ message: 'Error downloading file.' });
}
});
module.exports = router;