const express = require('express'); const fs = require('fs'); const path = require('path'); const multer = require('multer'); const db = require('../db'); const asyncHandler = require('../middleware/asyncHandler'); const router = express.Router(); const ALLOWED_FILE_TYPES = { 'application/pdf': ['.pdf'], 'image/jpeg': ['.jpg', '.jpeg'], 'image/png': ['.png'], 'application/msword': ['.doc'], 'application/vnd.openxmlformats-officedocument.wordprocessingml.document': ['.docx'], }; function fileFilter(req, file, cb) { const allowedExtensions = Object.values(ALLOWED_FILE_TYPES).flat(); const ext = path.extname(file.originalname).toLowerCase(); if (allowedExtensions.includes(ext) && ALLOWED_FILE_TYPES[file.mimetype]) { cb(null, true); } else { cb(new Error(`Dateityp nicht erlaubt: ${ext}. Erlaubt sind: PDF, JPG, PNG, DOC, DOCX`), false); } } const storage = multer.diskStorage({ destination: (req, file, cb) => cb(null, 'uploads/'), filename: (req, file, cb) => { const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9); cb(null, uniqueSuffix + path.extname(file.originalname)); }, }); const upload = multer({ storage, fileFilter, limits: { fileSize: 10 * 1024 * 1024 } }); // Upload document for a schaltung (mounted as /api/schaltungen/:id/dokumente by server.js) router.post('/schaltungen/:id/dokumente', upload.single('document'), asyncHandler(async (req, res) => { const schaltung_id = req.params.id; const file = req.file; if (!file) return res.status(400).json({ error: 'Keine Datei hochgeladen' }); const cleanup = () => { fs.unlink(file.path, (e) => { if (e) console.error('Cleanup error:', e.message); }); }; const schaltung = await db.get('SELECT id FROM schaltungen WHERE id = ?', [schaltung_id]); if (!schaltung) { cleanup(); return res.status(404).json({ error: 'Schaltung nicht gefunden' }); } try { const result = await db.run( `INSERT INTO dokumente (schaltung_id, filename, original_filename, filepath, filesize, mimetype) VALUES (?, ?, ?, ?, ?, ?)`, [schaltung_id, file.filename, file.originalname, file.path, file.size, file.mimetype] ); res.json({ id: result.lastID, message: 'Dokument erfolgreich hochgeladen', filename: file.originalname }); } catch (err) { cleanup(); throw err; } })); // List documents for a schaltung router.get('/schaltungen/:id/dokumente', asyncHandler(async (req, res) => { const rows = await db.all('SELECT * FROM dokumente WHERE schaltung_id = ?', [req.params.id]); res.json(rows); })); // Download single document router.get('/dokumente/:id/download', asyncHandler(async (req, res) => { const row = await db.get('SELECT * FROM dokumente WHERE id = ?', [req.params.id]); if (!row) return res.status(404).json({ error: 'Dokument nicht gefunden' }); const filepath = req.app.locals.safeUploadPath(row.filepath); if (!filepath) { console.error(`Path traversal attempt or invalid path for document ${row.id}: ${row.filepath}`); return res.status(400).json({ error: 'Ungültiger Dateipfad' }); } res.download(filepath, row.original_filename); })); // Delete document router.delete('/dokumente/:id', asyncHandler(async (req, res) => { const row = await db.get('SELECT * FROM dokumente WHERE id = ?', [req.params.id]); if (!row) return res.status(404).json({ error: 'Dokument nicht gefunden' }); await db.run('DELETE FROM dokumente WHERE id = ?', [req.params.id]); const filepath = req.app.locals.safeUploadPath(row.filepath); if (filepath) { fs.unlink(filepath, (err) => { if (err) console.error('Fehler beim Löschen der Datei:', err.message); }); } else { console.error(`Skipping file delete - invalid path: ${row.filepath}`); } res.json({ message: 'Dokument erfolgreich gelöscht' }); })); module.exports = router;