38 lines
1.5 KiB
JavaScript
38 lines
1.5 KiB
JavaScript
const express = require('express');
|
|
const router = express.Router();
|
|
const pool = global.db_pool;
|
|
const log = global.log;
|
|
const fs = require('fs');
|
|
const path = require('path');
|
|
|
|
router.get("/:fileId/:authToken", async (req, res) => {
|
|
const { fileId, authToken } = req.params;
|
|
const [auth] = await pool.query('SELECT * FROM fileAuth WHERE token = ?', [authToken]);
|
|
if (!auth) return res.status(403).send("Invalid token");
|
|
const [product] = await pool.query('SELECT * FROM products WHERE file = ? AND id = ?', [fileId, auth.product]);
|
|
if (!auth || !product) return res.status(404).send("File not found");
|
|
log.info("Auth and product found")
|
|
if (auth.expires < Date.now()) {
|
|
res.status(403).send("Token expired");
|
|
return pool.query('DELETE FROM fileAuth WHERE token = ?', [authToken]);
|
|
}
|
|
const safeFileId = path.basename(product.file);
|
|
const filePath = path.join(__dirname, '../productFiles', safeFileId);
|
|
if (!fs.existsSync(filePath)) return res.status(404).send("File not found");
|
|
log.info("File exists!")
|
|
res.setHeader('Content-Disposition', `attachment; filename=${product.file}.${product.fileType}`);
|
|
res.sendFile(filePath, (err) => {
|
|
if (err) {
|
|
log.error(`Error sending file: ${err}`);
|
|
res.status(500).send("Error sending file");
|
|
return;
|
|
}
|
|
// File sent successfully, delete auth
|
|
pool.query('DELETE FROM fileAuth WHERE token = ?', [authToken]).catch(err => {
|
|
log.error(`Error deleting file auth: ${err}`);
|
|
});
|
|
log.info(`File ${product.file} sent successfully`);
|
|
});
|
|
})
|
|
|
|
module.exports = router; |