Add SMTP admin settings and contact form delivery

This commit is contained in:
MOH
2026-03-08 06:27:09 +01:00
parent 993a4673d8
commit 5ca4819bcb
28 changed files with 2087 additions and 55 deletions
+109
View File
@@ -0,0 +1,109 @@
"use server";
import { redirect } from "next/navigation";
import { isRedirectError } from "next/dist/client/components/redirect";
import { z } from "zod";
import { enforceContactRateLimit, verifyTurnstileToken } from "@/lib/contact-guard";
import { getContactProtectionSettings } from "@/lib/app-config";
import { getLocalizedPath, resolveLocale } from "@/lib/locale";
import { sendContactMessage } from "@/lib/mail";
const contactFormSchema = z.object({
locale: z.string().trim().min(1),
name: z.string().trim().min(2).max(120),
email: z.string().trim().email(),
phone: z.string().trim().max(40).optional(),
company: z.string().trim().max(120).optional(),
message: z.string().trim().min(10).max(5000),
turnstileToken: z.string().trim().optional(),
});
const contactErrorMessages = {
ar: {
invalid: "يرجى تعبئة كل الحقول بشكل صحيح.",
failed: "تعذر إرسال الرسالة حالياً.",
blocked: "تم إرسال عدد كبير من الطلبات. حاول لاحقاً.",
verification: "يرجى إكمال التحقق قبل الإرسال.",
},
en: {
invalid: "Please fill all fields correctly.",
failed: "Message could not be sent right now.",
blocked: "Too many requests. Please try again later.",
verification: "Please complete the verification before sending.",
},
de: {
invalid: "Bitte alle Felder korrekt ausfuellen.",
failed: "Nachricht konnte gerade nicht gesendet werden.",
blocked: "Zu viele Anfragen. Bitte spaeter erneut versuchen.",
verification: "Bitte die Verifizierung vor dem Senden abschliessen.",
},
} as const;
function withError(pathname: string, message: string) {
const params = new URLSearchParams();
params.set("error", message);
return `${pathname}?${params.toString()}`;
}
function getStringValue(formData: FormData, key: string) {
const value = formData.get(key);
return typeof value === "string" ? value : "";
}
export async function submitContactFormAction(formData: FormData) {
const locale = resolveLocale(String(formData.get("locale") ?? ""));
const contactPath = getLocalizedPath(locale, "/contact");
try {
const protectionSettings = await getContactProtectionSettings();
const values = contactFormSchema.parse({
locale,
name: getStringValue(formData, "name"),
email: getStringValue(formData, "email"),
phone: getStringValue(formData, "phone"),
company: getStringValue(formData, "company"),
message: getStringValue(formData, "message"),
turnstileToken: getStringValue(formData, "turnstileToken"),
});
await verifyTurnstileToken(protectionSettings, values.turnstileToken ?? "");
await enforceContactRateLimit(protectionSettings);
await sendContactMessage({
locale,
name: values.name,
email: values.email,
phone: values.phone,
company: values.company,
message: values.message,
});
redirect(getLocalizedPath(locale, "/success"));
} catch (error) {
if (isRedirectError(error)) {
throw error;
}
if (error instanceof z.ZodError) {
redirect(withError(contactPath, contactErrorMessages[locale].invalid));
}
if (error instanceof Error && error.message === "Too many contact requests. Please try again later.") {
redirect(withError(contactPath, contactErrorMessages[locale].blocked));
}
if (
error instanceof Error &&
(error.message === "Turnstile verification is required." ||
error.message === "Turnstile verification failed." ||
error.message === "Turnstile verification request failed.")
) {
redirect(withError(contactPath, contactErrorMessages[locale].verification));
}
console.error("Contact form delivery failed.", error);
redirect(withError(contactPath, contactErrorMessages[locale].failed));
}
}
+36 -29
View File
@@ -1,24 +1,27 @@
import type { Metadata } from "next";
import { Mail, MapPin, Phone } from "lucide-react";
import Link from "next/link";
import { getTranslations } from "next-intl/server";
import { Container } from "@/components/layout/container";
import { PageHero } from "@/components/layout/page-hero";
import { MotionFade } from "@/components/motion-fade";
import { FlashMessage } from "@/components/root/flash-message";
import { ContactForm } from "@/components/site/contact-form";
import { buildLocalizedMetadata } from "@/lib/metadata";
import { getPublicContactProtectionSettings } from "@/lib/app-config";
import { getLocalizedPath, resolveLocale } from "@/lib/locale";
import { AppCard } from "@/components/ui/app-card";
import { Button } from "@/components/ui/button";
import { CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { submitContactFormAction } from "./actions";
type ContactPageProps = {
params: {
locale: string;
};
searchParams?: {
error?: string;
};
};
export async function generateMetadata({
@@ -35,9 +38,15 @@ export async function generateMetadata({
});
}
export default async function ContactPage({ params: { locale } }: ContactPageProps) {
export default async function ContactPage({
params: { locale },
searchParams,
}: ContactPageProps) {
const localeKey = resolveLocale(locale);
const t = await getTranslations({ locale: localeKey, namespace: "contactPage" });
const [t, protection] = await Promise.all([
getTranslations({ locale: localeKey, namespace: "contactPage" }),
getPublicContactProtectionSettings(),
]);
return (
<>
@@ -72,29 +81,27 @@ export default async function ContactPage({ params: { locale } }: ContactPagePro
<MotionFade delay={0.05}>
<AppCard>
<CardContent className="pt-6">
<form className="grid gap-4">
<Label className="grid gap-2">
{t("name")}
<Input type="text" placeholder={t("name")} />
</Label>
<Label className="grid gap-2">
{t("email")}
<Input type="email" placeholder={t("email")} />
</Label>
<Label className="grid gap-2">
{t("message")}
<Textarea rows={5} placeholder={t("message")} />
</Label>
<div className="flex flex-wrap gap-3">
<Button type="button">{t("submit")}</Button>
<Button asChild variant="outline">
<Link href={getLocalizedPath(localeKey, "/success")}>{t("preview")}</Link>
</Button>
{searchParams?.error ? (
<div className="mb-4">
<FlashMessage type="error" message={searchParams.error} />
</div>
</form>
) : null}
<ContactForm
action={submitContactFormAction}
locale={localeKey}
previewHref={getLocalizedPath(localeKey, "/success")}
protection={protection}
copy={{
name: t("name"),
email: t("email"),
phone: t("phone"),
company: t("company"),
message: t("message"),
note: t("note"),
submit: t("submit"),
preview: t("preview"),
}}
/>
</CardContent>
</AppCard>
</MotionFade>
+28 -16
View File
@@ -4,7 +4,6 @@ import Link from "next/link";
import { getTranslations } from "next-intl/server";
import { Container } from "@/components/layout/container";
import { PageHero } from "@/components/layout/page-hero";
import { MotionFade } from "@/components/motion-fade";
import { buildLocalizedMetadata } from "@/lib/metadata";
import { getLocalizedPath, resolveLocale } from "@/lib/locale";
@@ -38,27 +37,40 @@ export default async function SuccessPage({ params: { locale } }: SuccessPagePro
return (
<>
<PageHero title={t("title")} description={t("text")} />
<section className="hero-surface hero-page relative isolate overflow-hidden pb-12 pt-24 sm:pt-28 lg:pb-16 lg:pt-32">
<Container size="narrow" className="text-center">
<MotionFade className="w-full">
<div className="mx-auto flex max-w-[42rem] flex-col items-center">
<CheckCircle2 className="h-14 w-14 text-status-success" />
<p className="mt-5 text-sm font-medium tracking-[-0.02em] text-foreground/58">
{t("title")}
</p>
<h1 className="mt-4 text-balance text-4xl font-semibold leading-[0.9] tracking-[-0.07em] text-foreground sm:text-5xl lg:text-[4.5rem]">
{t("title")}
</h1>
<p className="mx-auto mt-5 max-w-[32rem] text-sm leading-6 text-foreground/64 sm:text-base">
{t("text")}
</p>
<div className="mt-8 flex flex-wrap items-center justify-center gap-3">
<Button asChild>
<Link href={getLocalizedPath(localeKey)}>{t("home")}</Link>
</Button>
<Button asChild variant="outline">
<Link href={getLocalizedPath(localeKey, "/contact")}>{t("contact")}</Link>
</Button>
</div>
</div>
</MotionFade>
</Container>
</section>
<Container size="narrow" className="pb-12 lg:pb-16">
<MotionFade className="w-full">
<MotionFade className="w-full" delay={0.06}>
<AppCard level={3}>
<CardContent className="p-8 text-center">
<CheckCircle2 className="mx-auto h-12 w-12 text-status-success" />
<h1 className="mt-4 text-3xl font-semibold text-foreground sm:text-4xl">
{t("title")}
</h1>
<p className="mx-auto mt-3 max-w-2xl text-base text-muted-foreground">
<p className="mx-auto max-w-2xl text-base text-muted-foreground">
{t("text")}
</p>
<div className="mt-6 flex flex-wrap items-center justify-center gap-3">
<Button asChild>
<Link href={getLocalizedPath(localeKey)}>{t("home")}</Link>
</Button>
<Button asChild variant="outline">
<Link href={getLocalizedPath(localeKey, "/contact")}>{t("contact")}</Link>
</Button>
</div>
</CardContent>
</AppCard>
</MotionFade>
+5 -1
View File
@@ -21,5 +21,9 @@ export const metadata: Metadata = {
};
export default function RootLayout({ children }: RootLayoutProps) {
return <div className="font-latin">{children}</div>;
return (
<div dir="ltr" lang="de" className="font-latin">
{children}
</div>
);
}
+1
View File
@@ -24,6 +24,7 @@ const copy = {
uiKit: "UI Kit",
media: "Media",
siteSettings: "SEO",
smtp: "SMTP",
portfolio: "Portfolio",
logout: "Ausloggen",
backToSite: "Zur Website",
+113
View File
@@ -0,0 +1,113 @@
"use server";
import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";
import { isRedirectError } from "next/dist/client/components/redirect";
import { clearAdminSessionCookie, isAdminAuthenticated } from "@/lib/admin-auth";
import {
getMailSettings,
updateMailSettings,
} from "@/lib/app-config";
import { sendTestEmail } from "@/lib/mail";
import type { MailSettings } from "@/lib/mail-settings";
function ensureAdmin() {
if (!isAdminAuthenticated()) {
clearAdminSessionCookie();
redirect("/root");
}
}
function withMessage(pathname: string, type: "success" | "error", message: string) {
const params = new URLSearchParams();
params.set(type, message);
return `${pathname}?${params.toString()}`;
}
function parsePort(value: string) {
const port = Number.parseInt(value, 10);
if (!Number.isInteger(port) || port <= 0) {
throw new Error("SMTP port must be a positive number.");
}
return port;
}
function parseMailSettingsFormData(
formData: FormData,
existingSettings: MailSettings,
): MailSettings {
const host = String(formData.get("smtpHost") ?? "").trim();
const portValue = String(formData.get("smtpPort") ?? "").trim();
const username = String(formData.get("smtpUsername") ?? "").trim();
const password = String(formData.get("smtpPassword") ?? "");
const fromEmail = String(formData.get("mailFromEmail") ?? "").trim();
const fromName = String(formData.get("mailFromName") ?? "").trim();
const contactRecipient = String(formData.get("mailContactRecipient") ?? "").trim();
const testRecipient = String(formData.get("mailTestRecipient") ?? "").trim();
return {
smtp: {
host,
port: parsePort(portValue || String(existingSettings.smtp.port)),
secure: formData.get("smtpSecure") === "on",
username,
password: password.trim() ? password : existingSettings.smtp.password,
},
sender: {
email: fromEmail,
name: fromName,
},
recipients: {
contact: contactRecipient,
test: testRecipient,
},
};
}
export async function saveMailSettingsAction(formData: FormData) {
ensureAdmin();
try {
const existingMailSettings = await getMailSettings();
const nextMailSettings = parseMailSettingsFormData(formData, existingMailSettings);
await updateMailSettings(nextMailSettings);
revalidatePath("/root/smtp");
redirect(withMessage("/root/smtp", "success", "SMTP Einstellungen gespeichert."));
} catch (error) {
if (isRedirectError(error)) {
throw error;
}
const message =
error instanceof Error
? error.message
: "SMTP Einstellungen konnten nicht gespeichert werden.";
redirect(withMessage("/root/smtp", "error", message));
}
}
export async function sendTestEmailAction() {
ensureAdmin();
try {
await sendTestEmail();
redirect(withMessage("/root/smtp", "success", "Test-E-Mail gesendet."));
} catch (error) {
if (isRedirectError(error)) {
throw error;
}
const message =
error instanceof Error
? error.message
: "Test-E-Mail konnte nicht gesendet werden.";
redirect(withMessage("/root/smtp", "error", message));
}
}
+110
View File
@@ -0,0 +1,110 @@
"use server";
import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";
import { isRedirectError } from "next/dist/client/components/redirect";
import { clearAdminSessionCookie, isAdminAuthenticated } from "@/lib/admin-auth";
import {
getContactProtectionSettings,
updateContactProtectionSettings,
} from "@/lib/app-config";
import type { ContactProtectionSettings } from "@/lib/contact-protection";
function ensureAdmin() {
if (!isAdminAuthenticated()) {
clearAdminSessionCookie();
redirect("/root");
}
}
function withMessage(pathname: string, type: "success" | "error", message: string) {
const params = new URLSearchParams();
params.set(type, message);
return `${pathname}?${params.toString()}`;
}
function parseCount(value: string, fallback: number, label: string) {
const parsed = Number.parseInt(value || String(fallback), 10);
if (!Number.isInteger(parsed) || parsed <= 0) {
throw new Error(`${label} must be a positive number.`);
}
return parsed;
}
function parseContactProtectionFormData(
formData: FormData,
existingSettings: ContactProtectionSettings,
): ContactProtectionSettings {
const turnstileEnabled = formData.get("turnstileEnabled") === "on";
const turnstileSiteKey = String(formData.get("turnstileSiteKey") ?? "").trim();
const turnstileSecretKey = String(formData.get("turnstileSecretKey") ?? "");
const rateLimitEnabled = formData.get("contactRateLimitEnabled") === "on";
if (turnstileEnabled && !turnstileSiteKey) {
throw new Error("Turnstile site key is required when Turnstile is enabled.");
}
if (turnstileEnabled && !turnstileSecretKey.trim() && !existingSettings.turnstile.secretKey) {
throw new Error("Turnstile secret key is required when Turnstile is enabled.");
}
return {
turnstile: {
enabled: turnstileEnabled,
siteKey: turnstileSiteKey,
secretKey: turnstileSecretKey.trim()
? turnstileSecretKey
: existingSettings.turnstile.secretKey,
},
rateLimit: {
enabled: rateLimitEnabled,
maxRequests: parseCount(
String(formData.get("contactRateLimitMaxRequests") ?? ""),
existingSettings.rateLimit.maxRequests,
"Rate limit max requests",
),
windowMinutes: parseCount(
String(formData.get("contactRateLimitWindowMinutes") ?? ""),
existingSettings.rateLimit.windowMinutes,
"Rate limit window minutes",
),
},
};
}
export async function saveContactProtectionSettingsAction(formData: FormData) {
ensureAdmin();
try {
const existingSettings = await getContactProtectionSettings();
const nextSettings = parseContactProtectionFormData(formData, existingSettings);
await updateContactProtectionSettings(nextSettings);
revalidatePath("/root/smtp/contact-protection");
revalidatePath("/contact");
revalidatePath("/ar/contact");
revalidatePath("/en/contact");
redirect(
withMessage(
"/root/smtp/contact-protection",
"success",
"Contact Protection gespeichert.",
),
);
} catch (error) {
if (isRedirectError(error)) {
throw error;
}
const message =
error instanceof Error
? error.message
: "Contact Protection konnte nicht gespeichert werden.";
redirect(withMessage("/root/smtp/contact-protection", "error", message));
}
}
+85
View File
@@ -0,0 +1,85 @@
import { redirect } from "next/navigation";
import { MotionFade } from "@/components/motion-fade";
import { ContactProtectionForm } from "@/components/root/contact-protection-form";
import { FlashMessage } from "@/components/root/flash-message";
import { RootDashboardShell } from "@/components/root/root-dashboard-shell";
import { clearAdminSessionCookie, isAdminAuthenticated } from "@/lib/admin-auth";
import { getContactProtectionFormValues } from "@/lib/app-config";
import { saveContactProtectionSettingsAction } from "./actions";
export const dynamic = "force-dynamic";
const copy = {
title: "Contact Protection",
subtitle: "Turnstile und Rate Limiting fuer das Kontaktformular.",
overview: "Uebersicht",
maintenance: "Wartungsmodus",
uiKit: "UI Kit",
media: "Media",
siteSettings: "SEO",
smtp: "SMTP",
contactProtection: "Contact Protection",
portfolio: "Portfolio",
logout: "Ausloggen",
backToSite: "Zur Website",
};
type RootSMTPProtectionPageProps = {
searchParams?: {
success?: string;
error?: string;
};
};
export default async function RootSMTPProtectionPage({
searchParams,
}: RootSMTPProtectionPageProps) {
if (!isAdminAuthenticated()) {
redirect("/root");
}
async function logoutAction() {
"use server";
clearAdminSessionCookie();
redirect("/root");
}
const settings = await getContactProtectionFormValues();
return (
<RootDashboardShell
copy={copy}
active="smtp"
smtpChild="contact-protection"
logoutAction={logoutAction}
headerTitle={copy.title}
headerDescription={copy.subtitle}
saveFormId="contact-protection-form"
reloadDocumentOnSave
>
<div className="space-y-6">
{searchParams?.success ? (
<MotionFade delay={0.1}>
<FlashMessage type="success" message={searchParams.success} />
</MotionFade>
) : null}
{searchParams?.error ? (
<MotionFade delay={0.12}>
<FlashMessage type="error" message={searchParams.error} />
</MotionFade>
) : null}
<MotionFade delay={0.16}>
<ContactProtectionForm
action={saveContactProtectionSettingsAction}
initialSettings={settings}
/>
</MotionFade>
</div>
</RootDashboardShell>
);
}
+91
View File
@@ -0,0 +1,91 @@
import { redirect } from "next/navigation";
import { MotionFade } from "@/components/motion-fade";
import { FlashMessage } from "@/components/root/flash-message";
import { RootDashboardShell } from "@/components/root/root-dashboard-shell";
import { SMTPSettingsForm } from "@/components/root/smtp-settings-form";
import { Button } from "@/components/ui/button";
import { clearAdminSessionCookie, isAdminAuthenticated } from "@/lib/admin-auth";
import { getMailSettingsFormValues } from "@/lib/app-config";
import { saveMailSettingsAction, sendTestEmailAction } from "./actions";
export const dynamic = "force-dynamic";
const copy = {
title: "SMTP",
subtitle: "Mailserver, Absender und Testempfaenger verwalten.",
overview: "Uebersicht",
maintenance: "Wartungsmodus",
uiKit: "UI Kit",
media: "Media",
siteSettings: "SEO",
smtp: "SMTP",
contactProtection: "Contact Protection",
portfolio: "Portfolio",
logout: "Ausloggen",
backToSite: "Zur Website",
};
type RootSMTPPageProps = {
searchParams?: {
success?: string;
error?: string;
};
};
export default async function RootSMTPPage({ searchParams }: RootSMTPPageProps) {
if (!isAdminAuthenticated()) {
redirect("/root");
}
async function logoutAction() {
"use server";
clearAdminSessionCookie();
redirect("/root");
}
const mailSettings = await getMailSettingsFormValues();
return (
<RootDashboardShell
copy={copy}
active="smtp"
smtpChild="settings"
logoutAction={logoutAction}
headerTitle={copy.title}
headerDescription={copy.subtitle}
saveFormId="smtp-settings-form"
reloadDocumentOnSave
headerActions={(
<form action={sendTestEmailAction}>
<Button type="submit" variant="outline">
Send test email
</Button>
</form>
)}
>
<div className="space-y-6">
{searchParams?.success ? (
<MotionFade delay={0.1}>
<FlashMessage type="success" message={searchParams.success} />
</MotionFade>
) : null}
{searchParams?.error ? (
<MotionFade delay={0.12}>
<FlashMessage type="error" message={searchParams.error} />
</MotionFade>
) : null}
<MotionFade delay={0.16}>
<SMTPSettingsForm
action={saveMailSettingsAction}
initialSettings={mailSettings}
/>
</MotionFade>
</div>
</RootDashboardShell>
);
}