44 lines
2.0 KiB
JavaScript
44 lines
2.0 KiB
JavaScript
import { Router } from 'express'
|
|
import { existsSync, readdirSync } from 'fs'
|
|
import { join, dirname } from 'path'
|
|
import { fileURLToPath } from 'url'
|
|
import { resourceLimiter } from '../middleware/rateLimiter.js'
|
|
import { antiSpam } from '../middleware/antiSpam.js'
|
|
import { sendStakeholderNotification, MailerNotReadyError } from '../services/mailer.js'
|
|
|
|
const __dirname = dirname(fileURLToPath(import.meta.url))
|
|
const RESOURCES_DIR = join(__dirname, '..', '..', 'public', 'resources')
|
|
|
|
export function getAvailableResourceIds() {
|
|
if (!existsSync(RESOURCES_DIR)) return []
|
|
return readdirSync(RESOURCES_DIR, { withFileTypes: true })
|
|
.filter(entry => entry.isFile() && entry.name.endsWith('.pdf') && entry.name !== 'speaker-cv-andre-knie.pdf')
|
|
.map(entry => entry.name.slice(0, -4))
|
|
}
|
|
|
|
const router = Router()
|
|
|
|
router.post('/', resourceLimiter, antiSpam, async (req, res) => {
|
|
const { name, email, company, resource_id } = req.body
|
|
const errors = {}
|
|
if (!name || name.trim().length === 0) errors.name = 'Name ist erforderlich.'
|
|
if (name && name.length > 100) errors.name = 'Max. 100 Zeichen.'
|
|
if (!email || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) errors.email = 'Gültige E-Mail erforderlich.'
|
|
if (!company || company.trim().length === 0) errors.company = 'Unternehmen ist erforderlich.'
|
|
if (company && company.length > 150) errors.company = 'Max. 150 Zeichen.'
|
|
if (!resource_id || !getAvailableResourceIds().includes(resource_id)) {
|
|
errors.resource_id = 'Diese Ressource ist derzeit nicht verfügbar.'
|
|
}
|
|
|
|
if (Object.keys(errors).length > 0) return res.status(400).json({ errors })
|
|
|
|
try {
|
|
await sendStakeholderNotification('resource-download', { name, email, company, resource_id })
|
|
res.status(202).json({ ok: true, message: 'Danke! Wir prüfen die Anfrage und melden uns bei dir.' })
|
|
} catch (error) {
|
|
res.status(error instanceof MailerNotReadyError ? 503 : 502).json({ error: 'Die Anfrage konnte derzeit nicht übermittelt werden.' })
|
|
}
|
|
})
|
|
|
|
export default router
|