const s3 = require('../middleware/Storage') const express = require('express'); const router = express.Router(); const path = require('path') const multer = require('multer') const dotenv = require('dotenv'); const { uuid } = require('uuidv4'); const shortid = require('shortid'); const storage = multer.memoryStorage(); const upload = multer({ storage: storage }); dotenv.config(); const authenticateAPIKey = (req, res, next) => { const userKey = req.headers['x-api-key']; const uploadSec = process.env.UPLOAD_SEC; if (userKey && userKey === uploadSec) { return next(); } else { return res.status(403).json({ error: 'Forbidden' }); } }; router.post('/upload', authenticateAPIKey, upload.single('file'), async (req, res) => { try { const file = req.file; const uuidGen = uuid() const fileID = shortid.generate() const fileName = `${fileID}${path.extname(file.originalname)}`; const key = `attachments/${uuidGen}/` + fileName; const fileUrl = `${process.env.R2_DOMAIN}/${key}`; const params = { Bucket: process.env.R2_BUCKET, Key: key, Body: file.buffer, ContentType: file.mimetype, ACL: 'public-read', }; await s3.upload(params).promise(); res.json({ url: `${fileUrl}` }); } catch (error) { console.error(error); res.status(500).json({ error: 'Upload error.' }); } }); module.exports = router;