MBO-Tech-IT-Webseite/app/api/familyguard-flyer/route.ts

78 lines
2.3 KiB
TypeScript

import { NextResponse } from "next/server";
import { sendeFlyerBenachrichtigung, sendeFlyerLink } from "@/lib/mailer";
import { createServiceClient } from "@/lib/supabase";
const FLYER_DOWNLOAD_URL = "/downloads/MBO_FamilyGuard_Flyer_01.pdf";
const RATE_LIMIT_WINDOW_MS = 60 * 60 * 1000;
const RATE_LIMIT_MAX = 3;
const requestLog = new Map<string, number[]>();
function isRateLimited(ip: string): boolean {
const now = Date.now();
const timestamps = (requestLog.get(ip) ?? []).filter(
(t) => now - t < RATE_LIMIT_WINDOW_MS
);
if (timestamps.length >= RATE_LIMIT_MAX) {
requestLog.set(ip, timestamps);
return true;
}
timestamps.push(now);
requestLog.set(ip, timestamps);
return false;
}
function getClientIp(request: Request): string {
const forwarded = request.headers.get("x-forwarded-for");
if (forwarded) return forwarded.split(",")[0].trim();
return "unknown";
}
function isValidEmail(email: string): boolean {
return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
}
export async function POST(request: Request) {
if (isRateLimited(getClientIp(request))) {
return NextResponse.json(
{ ok: false, error: "Zu viele Anfragen. Bitte versuchen Sie es später erneut." },
{ status: 429 }
);
}
let body: { email?: string; dsgvoEinwilligung?: boolean };
try {
body = await request.json();
} catch {
return NextResponse.json({ ok: false, error: "Ungültige Anfrage" }, { status: 400 });
}
const email = typeof body.email === "string" ? body.email.trim() : "";
if (!isValidEmail(email)) {
return NextResponse.json(
{ ok: false, error: "Bitte geben Sie eine gültige E-Mail-Adresse ein" },
{ status: 400 }
);
}
if (body.dsgvoEinwilligung !== true) {
return NextResponse.json(
{ ok: false, error: "Bitte stimmen Sie der Datenverarbeitung zu" },
{ status: 400 }
);
}
try {
const db = createServiceClient();
await db.from("flyer_downloads").insert({ email, dsgvo_einwilligung: true });
} catch (err) {
console.error("[FamilyGuard-Flyer] Supabase insert error:", err);
}
await sendeFlyerBenachrichtigung({ email });
sendeFlyerLink({ email }).catch((err) =>
console.error("[FamilyGuard-Flyer] Flyer-Mail an Interessenten fehlgeschlagen:", err)
);
return NextResponse.json({ ok: true, downloadUrl: FLYER_DOWNLOAD_URL });
}