73 lines
2.5 KiB
JavaScript
73 lines
2.5 KiB
JavaScript
import { Router } from 'express'
|
|
import { readFileSync, writeFileSync, existsSync } from 'fs'
|
|
import { join, dirname } from 'path'
|
|
import { fileURLToPath } from 'url'
|
|
import { Mutex } from 'async-mutex'
|
|
import { newsletterLimiter } from '../middleware/rateLimiter.js'
|
|
import { antiSpam } from '../middleware/antiSpam.js'
|
|
import { createToken, reserveToken, completeToken, releaseToken } from '../services/confirmationToken.js'
|
|
import { sendConfirmationEmail, MailerNotReadyError } from '../services/mailer.js'
|
|
|
|
const __dirname = dirname(fileURLToPath(import.meta.url))
|
|
const SUBS_FILE = join(__dirname, '..', 'data', 'subscribers.json')
|
|
const subsMutex = new Mutex()
|
|
|
|
function loadSubscribers() {
|
|
if (!existsSync(SUBS_FILE)) return []
|
|
try { return JSON.parse(readFileSync(SUBS_FILE, 'utf-8')) }
|
|
catch { return [] }
|
|
}
|
|
|
|
function saveSubscribers(subs) {
|
|
writeFileSync(SUBS_FILE, JSON.stringify(subs, null, 2), 'utf-8')
|
|
}
|
|
|
|
const router = Router()
|
|
|
|
router.post('/', newsletterLimiter, antiSpam, async (req, res) => {
|
|
const { email } = req.body
|
|
if (!email || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
|
|
return res.status(400).json({ errors: { email: 'Gueltige E-Mail erforderlich.' } })
|
|
}
|
|
|
|
const subs = loadSubscribers()
|
|
if (subs.find(s => s.email === email && s.active)) {
|
|
return res.status(409).json({ error: 'Diese E-Mail ist bereits abonniert.' })
|
|
}
|
|
|
|
try {
|
|
const token = await createToken('newsletter', { email }, 48)
|
|
await sendConfirmationEmail(email, 'newsletter', token)
|
|
res.status(201).json({ ok: true, message: 'Bestaetigungs-E-Mail gesendet.' })
|
|
} catch (error) {
|
|
res.status(error instanceof MailerNotReadyError ? 503 : 502).json({ error: 'Die Anfrage konnte derzeit nicht versendet werden.' })
|
|
}
|
|
})
|
|
|
|
router.get('/confirm/:token', async (req, res) => {
|
|
const baseUrl = process.env.BASE_URL || ''
|
|
const entry = await reserveToken(req.params.token)
|
|
if (!entry) return res.redirect(baseUrl + '/bestaetigung?status=error')
|
|
|
|
try {
|
|
await subsMutex.runExclusive(async () => {
|
|
const subs = loadSubscribers()
|
|
if (!subs.find(s => s.email === entry.data.email && s.active)) {
|
|
subs.push({
|
|
email: entry.data.email,
|
|
subscribedAt: new Date().toISOString(),
|
|
active: true,
|
|
})
|
|
saveSubscribers(subs)
|
|
}
|
|
})
|
|
await completeToken(req.params.token)
|
|
res.redirect(baseUrl + '/bestaetigung?status=success')
|
|
} catch {
|
|
await releaseToken(req.params.token)
|
|
res.status(502).redirect(baseUrl + '/bestaetigung?status=error')
|
|
}
|
|
})
|
|
|
|
export default router
|