Update v1.0.0-beta.13
All checks were successful
continuous-integration/drone/push Build is passing

Several modifications made to the API and several bug fixes
This commit is contained in:
2024-06-02 18:13:28 +02:00
parent f2d244c95a
commit ce8f1bbbac
21 changed files with 1228 additions and 170 deletions

View File

@@ -1,16 +1,166 @@
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;
let configFile = fs.readFileSync(path.join(__dirname, '../../../data', 'setup.json'), 'utf-8')
let config = JSON.parse(configFile)[0];
const bodyParser = require('body-parser');
const crypto = require('crypto');
const os = require('os');
const { getUserData, getSetupData } = require('../../../Middlewares/watcherMiddleware');
router.post('/', authMiddleware, (req, res) => {
const { backgroundUrl } = req.body;
let setupData = getSetupData();
let userData = getUserData();
router.use(bodyParser.json());
if (!backgroundUrl) {
return res.status(400).json({ message: 'Background URL missing.' });
/**
* @swagger
* /dashboard/getfilefolder/{folderName}?token={token}:
* post:
* security:
* - bearerAuth: []
* tags:
* - Folder
* summary: Get files and folders in a specific folder
* description: This route allows you to get the files and folders in a specific folder. It requires a valid JWT token in the Authorization header.
* parameters:
* - in: path
* name: folderName
* required: true
* schema:
* type: string
* description: The name of the folder
* - 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:
* files:
* type: array
* items:
* type: object
* properties:
* name:
* type: string
* type:
* type: string
* 401:
* description: Unauthorized
* content:
* application/json:
* schema:
* type: object
* properties:
* message:
* type: string
* 404:
* description: The specified folder does not exist
* content:
* application/json:
* schema:
* type: object
* properties:
* error:
* type: string
* 500:
* description: Internal server error
* content:
* application/json:
* schema:
* type: object
* properties:
* 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.json'), '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) {
req.user = user;
req.userData = user;
next();
} else {
return res.status(401).json({ message: 'Unauthorized' });
}
});
}
res.cookie('background', backgroundUrl, { httpOnly: true });
res.status(200).json({ message: 'Background updated successfully.' });
router.get('/wallpaper', authenticateToken, (req, res) => {
fs.readFile(path.join(__dirname, '../../../data', 'user.json'), 'utf8', (err, data) => {
if (err) {
return res.status(500).send('Error reading the file');
}
const users = JSON.parse(data);
const user = users.find(u => u.token === req.userData.token);
res.json({ wallpaper: user.wallpaper || null });
});
});
router.post('/wallpaper', authenticateToken, (req, res) => {
const newWallpaper = req.body.wallpaper;
fs.readFile(path.join(__dirname, '../../../data', 'user.json'), 'utf8', (err, data) => {
if (err) {
return res.status(500).send('Error reading the file');
}
let users = JSON.parse(data);
const userIndex = users.findIndex(u => u.token === req.userData.token);
if (userIndex !== -1) {
users[userIndex].wallpaper = newWallpaper;
fs.writeFile(path.join(__dirname, '../../../data', 'user.json'), JSON.stringify(users, null, 2), (err) => {
if (err) {
return res.status(500).send('Error writing to the file');
}
res.send('Wallpaper updated');
});
} else {
res.status(401).send('Unauthorized');
}
});
});
module.exports = router;

View File

@@ -18,49 +18,129 @@ let setupData = getSetupData();
let userData = getUserData();
router.use(bodyParser.json());
/**
* @swagger
* /dashboard/deletefile?token={token}:
* post:
* security:
* - bearerAuth: []
* tags:
* - File
* summary: Delete a specific file for a user
* description: This route allows you to delete a specific file for a user. It requires a valid JWT token in the Authorization header.
* requestBody:
* required: true
* content:
* application/json:
* schema:
* type: object
* properties:
* filename:
* type: string
* description: The name of the file to delete
* 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:
* status:
* type: string
* message:
* type: string
* 400:
* description: Bad Request
* content:
* application/json:
* schema:
* type: object
* properties:
* error:
* type: string
* 401:
* description: Unauthorized
* content:
* application/json:
* schema:
* type: object
* properties:
* message:
* type: string
* 404:
* description: The specified file does not exist
* content:
* application/json:
* schema:
* type: object
* properties:
* status:
* type: string
* message:
* type: string
* 500:
* description: Internal server error
* content:
* application/json:
* schema:
* type: object
* properties:
* error:
* type: string
*/
function authenticateToken(req, res, next) {
let token = null;
const authHeader = req.headers['authorization'];
if (authHeader) {
token = authHeader.split(' ')[1];
token = authHeader.split(' ')[1];
} else if (req.query.token) {
token = req.query.token;
token = req.query.token;
}
if (token == null) {
if (req.user) {
return next();
} else {
return res.status(401).json({ message: 'Unauthorized' });
}
if (!token) {
return res.status(401).json({ message: 'Unauthorized: No token provided' });
}
fs.readFile(path.join(__dirname, '../../../data', 'user.json'), '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) {
if (err) {
console.error('Error reading user.json:', err);
return res.status(500).json({ message: 'Internal server error' });
}
const users = JSON.parse(data);
const user = users.find(u => u.token === token);
if (!user) {
return res.status(401).json({ message: 'Unauthorized: Invalid token' });
}
req.user = user;
req.userData = 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.post('/', authenticateToken, (req, res) => {
if (!req.userData) {
return res.status(401).json({ message: 'Authentication failed.' });
}
const userId = req.userData.name;
const { filename } = req.body;
@@ -90,6 +170,7 @@ router.post('/', authenticateToken, (req, res) => {
fs.unlinkSync(filePath);
return true;
} catch (error) {
console.error('Error deleting file:', error);
return false;
}
}
@@ -107,9 +188,9 @@ router.post('/', authenticateToken, (req, res) => {
}
});
const ncpAsync = (source, destination) => {
const userFolderPath = path.join('cdn-files', userId);
if (!source.startsWith(userFolderPath) || !destination.startsWith(userFolderPath)) {
if (!source.startsWith('cdn-files') || !destination.startsWith('cdn-files')) {
throw new Error('Unauthorized directory access attempt');
}

View File

@@ -18,31 +18,166 @@ let setupData = getSetupData();
let userData = getUserData();
router.use(bodyParser.json());
/**
* @swagger
* /dashboard/deletefolder/{folderName}?token={token}:
* post:
* security:
* - bearerAuth: []
* tags:
* - Folder
* summary: Delete a specific file in folder for a user
* description: This route allows you to delete a specific file for a user. It requires a valid JWT token in the Authorization header.
* requestBody:
* required: true
* content:
* application/json:
* schema:
* type: object
* properties:
* filename:
* type: string
* description: The name of the file to delete
* parameters:
* - in: path
* name: folderName
* required: true
* schema:
* type: string
* description: The name of the folder
* - in: header
* name: Authorization
* required: true
* schema:
* type: string
* description: The JWT token of your account to have access
* responses:
* 200:
* description: Folder successfully deleted.
* content:
* application/json:
* schema:
* type: object
* properties:
* deleted:
* type: boolean
* success:
* type: string
* 400:
* description: Bad Request
* content:
* application/json:
* schema:
* type: object
* properties:
* error:
* type: string
* 401:
* description: Unauthorized
* content:
* application/json:
* schema:
* type: object
* properties:
* message:
* type: string
* 403:
* description: You do not have permission to delete this folder.
* content:
* application/json:
* schema:
* type: object
* properties:
* error:
* type: string
* 404:
* description: The specified folder does not exist.
* content:
* application/json:
* schema:
* type: object
* properties:
* error:
* type: string
* 500:
* description: Error deleting the folder.
* content:
* application/json:
* schema:
* type: object
* properties:
* error:
* type: string
*/
function authenticateToken(req, res, next) {
authMiddleware(req, res, function(err) {
if (!err) {
return 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) {
return res.status(401).json({ message: 'Unauthorized' });
}
fs.readFile(path.join(__dirname, '../../../data', 'user.json'), '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) {
req.user = user;
req.userData = 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.' });
res.status(400).json({ error: 'Bad Request. The request cannot be fulfilled due to bad syntax or missing parameters.' });
});
router.delete('/:folderName', authMiddleware, (req, res) => {
const userId = req.userData.name;
const folderName = req.params.folderName;
const userFolderPath = path.join('cdn-files', userId);
const folderPath = path.join(userFolderPath, folderName);
router.delete('/:folderName', authenticateToken, (req, res) => {
if (!fs.existsSync(folderPath)) {
return res.status(404).json({ error: 'Le dossier spécifié n\'existe pas.' });
}
const userId = req.userData ? req.userData.name : null;
if (!userId) {
return res.status(401).json({ error: 'Unauthorized' });
}
const folderName = req.params.folderName;
const userFolderPath = path.join('cdn-files', userId);
const folderPath = path.join(userFolderPath, folderName);
if (!folderPath.startsWith(userFolderPath)) {
return res.status(403).json({ error: 'Vous n\'avez pas la permission de supprimer ce dossier.' });
}
if (!fs.existsSync(folderPath)) {
return res.status(404).json({ error: 'The specified folder does not exist.' });
}
fs.rmdir(folderPath, { recursive: true }, (err) => {
if (err) {
console.error(err);
return res.status(500).json({ error: 'Erreur lors de la suppression du dossier.' });
}
res.json({ deleted: true, success: 'Dossier supprimé avec succès.' });
});
if (!folderPath.startsWith(userFolderPath)) {
return res.status(403).json({ error: 'You do not have permission to delete this folder.' });
}
fs.rmdir(folderPath, { recursive: true }, (err) => {
if (err) {
return res.status(500).json({ error: 'Error deleting the folder.' });
}
res.json({ deleted: true, success: 'Folder successfully deleted.' });
});
});
module.exports = router;

View File

@@ -18,6 +18,83 @@ let setupData = getSetupData();
let userData = getUserData();
router.use(bodyParser.json());
/**
* @swagger
* /dashboard/getfile?token={token}:
* post:
* security:
* - bearerAuth: []
* tags:
* - File
* summary: Get file information
* description: This route allows you to get information about a specific file. It requires a valid JWT token in the Authorization header.
* requestBody:
* required: true
* content:
* application/json:
* schema:
* type: object
* properties:
* fileLink:
* type: string
* description: The link of the file to get information about
* 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:
* Id:
* type: string
* fileName:
* type: string
* 400:
* description: Bad Request
* content:
* application/json:
* schema:
* type: object
* properties:
* error:
* type: string
* 401:
* description: Unauthorized
* content:
* application/json:
* schema:
* type: object
* properties:
* message:
* type: string
* 404:
* description: The specified file does not exist or no information found for the file
* content:
* application/json:
* schema:
* type: object
* properties:
* error:
* type: string
* 500:
* description: Error reading the file
* content:
* application/json:
* schema:
* type: object
* properties:
* error:
* type: string
*/
router.get('/', (req, res) => {
res.status(400).json({ error: 'Bad Request. The request cannot be fulfilled due to bad syntax or missing parameters.' });
});

View File

@@ -20,6 +20,84 @@ let setupData = getSetupData();
let userData = getUserData();
router.use(bodyParser.json());
/**
* @swagger
* /dashboard/movefile?token={token}:
* post:
* security:
* - bearerAuth: []
* tags:
* - File
* summary: Move file to a different folder
* description: This route allows you to move a file to a different folder. It requires a valid JWT token in the Authorization header.
* requestBody:
* required: true
* content:
* application/json:
* schema:
* type: object
* properties:
* fileName:
* type: string
* description: The name of the file to be moved
* folderName:
* type: string
* description: The name of the destination folder
* 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:
* error:
* type: string
* 401:
* description: Unauthorized
* content:
* application/json:
* schema:
* type: object
* properties:
* message:
* type: string
* 403:
* description: Unauthorized directory access attempt
* content:
* application/json:
* schema:
* type: object
* properties:
* error:
* type: string
* 500:
* description: Error moving the file
* content:
* application/json:
* schema:
* type: object
* properties:
* error:
* type: string
*/
function authenticateToken(req, res, next) {
let token = null;
const authHeader = req.headers['authorization'];
@@ -120,16 +198,25 @@ router.post('/', authenticateToken, async (req, res) => {
router.post('/:folderName', authenticateToken, async (req, res) => {
const fileName = req.body.fileName;
const newFolderName = req.body.folderName;
let newFolderName = req.body.newFolderName;
const oldFolderName = req.params.folderName;
const userId = req.user && req.user._json ? req.userData.name : undefined;
const userName = req.body.userName;
console.log('fileName:', fileName);
console.log('newFolderName:', newFolderName);
console.log('oldFolderName:', oldFolderName);
console.log('userName:', userName);
if (!fileName || !userId || !oldFolderName || !newFolderName) {
console.error('fileName, userId, oldFolderName, or newFolderName is undefined');
if (newFolderName === 'root') {
newFolderName = '';
}
if (fileName === undefined || userName === undefined || oldFolderName === undefined || newFolderName === undefined) {
console.error('fileName, userName, oldFolderName, or newFolderName is undefined');
return res.status(500).send('Error moving the file.');
}
const userDir = path.join(process.cwd(), 'cdn-files', userId);
const userDir = path.join(process.cwd(), 'cdn-files', userName);
const sourcePath = path.join(userDir, oldFolderName, fileName);
const destinationDir = path.join(userDir, newFolderName);
const destinationPath = path.join(destinationDir, fileName);

View File

@@ -18,42 +18,112 @@ let setupData = getSetupData();
let userData = getUserData();
router.use(bodyParser.json());
/**
* @swagger
* /dashboard/newfolder?token={token}:
* post:
* security:
* - bearerAuth: []
* tags:
* - Folder
* summary: Create a new folder
* description: This route allows you to create a new folder. It requires a valid JWT token in the Authorization header.
* requestBody:
* required: true
* content:
* application/json:
* schema:
* type: object
* properties:
* folderName:
* type: string
* description: The name of the new folder
* 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 creating the folder
* 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' });
authMiddleware(req, res, function(err) {
if (!err) {
return next();
}
}
fs.readFile(path.join(__dirname, '../../../data', 'user.json'), 'utf8', (err, data) => {
if (err) {
console.error('Error reading user.json:', err);
return res.status(401).json({ message: 'Unauthorized' });
let token = null;
const authHeader = req.headers['authorization'];
if (authHeader) {
token = authHeader.split(' ')[1];
} else if (req.query.token) {
token = req.query.token;
}
const users = JSON.parse(data);
const user = users.find(u => u.token === token);
if (user) {
req.user = user;
req.userData = user;
next();
} else {
return res.status(401).json({ message: 'Unauthorized' });
if (token == null) {
return res.status(401).json({ message: 'Unauthorized' });
}
});
fs.readFile(path.join(__dirname, '../../../data', 'user.json'), '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) {
req.user = user;
req.userData = user;
next();
} else {
return res.status(401).json({ message: 'Unauthorized' });
}
});
});
}
router.get('/', (req, res) => {
@@ -62,12 +132,10 @@ router.get('/', (req, res) => {
router.post('/', authenticateToken, (req, res) => {
try {
logger.info('Received POST request to create a new folder.');
const userId = req.userData.name;
const userId = req.user.name;
let { folderName } = req.body;
logger.info('Received folderName:', folderName);
if (!folderName || typeof folderName !== 'string') {
ErrorLogger.error('Invalid folderName:', folderName);
@@ -83,7 +151,6 @@ router.post('/', authenticateToken, (req, res) => {
const folderPath = path.join('cdn-files', userId, folderName);
if (fs.existsSync(folderPath)) {
logger.info('Folder already exists:', folderPath);
return res.status(400).json({ message: 'Folder already exists.' });
}
@@ -92,7 +159,6 @@ router.post('/', authenticateToken, (req, res) => {
ErrorLogger.error(err);
return res.status(500).json({ message: 'Error creating folder.', error: err });
}
logger.info('Folder created successfully:', folderPath);
res.status(200).json({ message: 'Folder created successfully.' });
});
} catch (error) {

View File

@@ -18,45 +18,163 @@ 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.json'), '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 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).send('Both currentName and newName must be provided.');
}
if (!currentName || !newName) {
return res.status(400).json('Both currentName and newName must be provided.');
}
const currentPath = path.join('cdn-files', userId || '', currentName);
const newPath = path.join('cdn-files', userId, newName);
const userDir = path.join('cdn-files', userId);
const currentPath = path.join(userDir, filePath, currentName);
const newPath = path.join(userDir, filePath, newName);
try {
await fs.promises.rename(currentPath, newPath);
if (!currentPath.startsWith(userDir) || !newPath.startsWith(userDir)) {
ErrorLogger.error('Unauthorized directory access attempt');
return res.status(403).json('Unauthorized directory access attempt');
}
const data = await fs.promises.readFile(path.join(__dirname, '../../../data', 'file_info.json'), 'utf-8')
let fileInfo = JSON.parse(data);
try {
await fs.promises.rename(currentPath, newPath);
let found = false;
for (let i = 0; i < fileInfo.length; i++) {
if (fileInfo[i].fileName === currentName) {
fileInfo[i].fileName = newName;
found = true;
break;
}
}
const data = await fs.promises.readFile(path.join(__dirname, '../../../data', 'file_info.json'), 'utf8');
let fileInfo = JSON.parse(data);
if (found) {
await fs.promises.writeFile(path.join(__dirname, '../../../data', 'file_info.json'), JSON.stringify(fileInfo, null, 2), 'utf8');
}
let found = false;
for (let i = 0; i < fileInfo.length; i++) {
if (fileInfo[i].fileName === currentName) {
fileInfo[i].fileName = newName;
found = true;
break;
}
}
res.status(200).send('L\'opération a été effectuée avec succès.');
} catch (err) {
console.error(err);
return res.status(500).send('Erreur lors du changement de nom du fichier.');
}
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) => {
@@ -65,7 +183,7 @@ router.post('/:filePath*', authMiddleware, async (req, res) => {
const filePath = path.join(req.params.filePath, req.params[0] || '');
if (!currentName || !newName) {
return res.status(400).send('Both currentName and newName must be provided.');
return res.status(400).json('Both currentName and newName must be provided.');
}
const userDir = path.join('cdn-files', userId);
@@ -74,7 +192,7 @@ router.post('/:filePath*', authMiddleware, async (req, res) => {
if (!currentPath.startsWith(userDir) || !newPath.startsWith(userDir)) {
ErrorLogger.error('Unauthorized directory access attempt');
return res.status(403).send('Unauthorized directory access attempt');
return res.status(403).json('Unauthorized directory access attempt');
}
try {
@@ -96,10 +214,10 @@ router.post('/:filePath*', authMiddleware, async (req, res) => {
await fs.promises.writeFile(path.join(__dirname, '../../../data', 'file_info.json'), JSON.stringify(fileInfo, null, 2), 'utf8');
}
res.status(200).send('L\'opération a été effectuée avec succès.');
res.status(200).json('Operation was successful.');
} catch (err) {
console.error(err);
return res.status(500).send('Erreur lors du changement de nom du fichier.');
return res.status(500).json('Error renaming the file.');
}
});

View File

@@ -18,6 +18,82 @@ 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'];

View File

@@ -17,6 +17,85 @@ let setupData = getSetupData();
let userData = getUserData();
router.use(bodyParser.json());
/**
* @swagger
* /dashboard/getfile?token={token}:
* post:
* security:
* - bearerAuth: []
* tags:
* - File
* summary: Get files and folders in a specific folder
* description: This route allows you to delete a specific file for a user. It requires a valid JWT token in the Authorization header.
* requestBody:
* required: true
* content:
* application/json:
* schema:
* type: object
* properties:
* filename:
* type: string
* description: The name of the file to delete
* 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:
* status:
* type: string
* message:
* type: string
* 400:
* description: Bad Request
* content:
* application/json:
* schema:
* type: object
* properties:
* error:
* type: string
* 401:
* description: Unauthorized
* content:
* application/json:
* schema:
* type: object
* properties:
* message:
* type: string
* 404:
* description: The specified file does not exist
* content:
* application/json:
* schema:
* type: object
* properties:
* status:
* type: string
* message:
* type: string
* 500:
* description: Internal server error
* content:
* application/json:
* schema:
* type: object
* properties:
* error:
* type: string
*/
function authenticateToken(req, res, next) {
let token = null;
const authHeader = req.headers['authorization'];

View File

@@ -0,0 +1,158 @@
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;
let configFile = fs.readFileSync(path.join(__dirname, '../../../data', 'setup.json'), 'utf-8')
let config = JSON.parse(configFile)[0];
const bodyParser = require('body-parser');
const crypto = require('crypto');
const os = require('os');
const { getUserData, getSetupData } = require('../../../Middlewares/watcherMiddleware');
let setupData = getSetupData();
let userData = getUserData();
router.use(bodyParser.json());
/**
* @swagger
* /dashboard/getfilefolder/{folderName}?token={token}:
* post:
* security:
* - bearerAuth: []
* tags:
* - Folder
* summary: Get files and folders in a specific folder
* description: This route allows you to get the files and folders in a specific folder. It requires a valid JWT token in the Authorization header.
* parameters:
* - in: path
* name: folderName
* required: true
* schema:
* type: string
* description: The name of the folder
* - 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:
* files:
* type: array
* items:
* type: object
* properties:
* name:
* type: string
* type:
* type: string
* 401:
* description: Unauthorized
* content:
* application/json:
* schema:
* type: object
* properties:
* message:
* type: string
* 404:
* description: The specified folder does not exist
* content:
* application/json:
* schema:
* type: object
* properties:
* error:
* type: string
* 500:
* description: Internal server error
* content:
* application/json:
* schema:
* type: object
* properties:
* 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.json'), '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) {
req.user = user;
req.userData = user;
next();
} else {
return res.status(401).json({ message: 'Unauthorized' });
}
});
}
router.post('/:folderName', authenticateToken, async (req, res) => {
const userName = req.userData.name;
const folderName = req.params.folderName;
const downloadDir = path.join('cdn-files', userName, folderName);
if (!fs.existsSync(downloadDir)) {
return res.status(404).json({ error: 'The specified folder does not exist.' });
}
try {
const files = await fs.promises.readdir(downloadDir);
const fileDetails = files.map(file => {
const filePath = path.join(downloadDir, file);
const stats = fs.statSync(filePath);
const fileType = stats.isDirectory() ? 'folder' : 'file';
return {
name: file,
type: fileType
};
});
res.json({ files: fileDetails });
} catch (err) {
console.error('Error reading directory:', err);
res.status(500).json({ error: err.message });
}
});
module.exports = router;