68 lines
2.1 KiB
TypeScript
68 lines
2.1 KiB
TypeScript
export const dynamic = "force-dynamic";
|
|
|
|
import { z } from "zod";
|
|
import { requireAdmin } from "@/lib/auth/session";
|
|
import { handleAuthError, fail, ok } from "@/lib/api";
|
|
import { getSettings } from "@/lib/settings";
|
|
import { SETTING_KEYS } from "@/lib/constants";
|
|
import { sendSmtpTestEmail } from "@/lib/email/mailer";
|
|
import { readJsonBody, validateMutationRequestOrigin } from "@/lib/security/request";
|
|
|
|
const bodySchema = z.object({
|
|
to: z.string().email("Bitte gültige Empfänger-E-Mail angeben"),
|
|
smtp: z
|
|
.object({
|
|
host: z.string().trim().optional().default(""),
|
|
port: z
|
|
.string()
|
|
.trim()
|
|
.regex(/^\d+$/, "Bitte einen numerischen SMTP-Port eingeben")
|
|
.optional()
|
|
.default("587"),
|
|
user: z.string().trim().optional().default(""),
|
|
pass: z.string().optional().default(""),
|
|
fromName: z.string().trim().optional().default("CalBook"),
|
|
from: z
|
|
.string()
|
|
.trim()
|
|
.refine(
|
|
(value) => value === "" || /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value),
|
|
"Bitte eine gültige Absender-E-Mail eingeben"
|
|
)
|
|
.optional()
|
|
.default("")
|
|
})
|
|
.optional()
|
|
});
|
|
|
|
export async function POST(req: Request) {
|
|
try {
|
|
const originError = validateMutationRequestOrigin(req);
|
|
if (originError) return originError;
|
|
|
|
await requireAdmin();
|
|
const bodyResult = await readJsonBody(req, { maxBytes: 16 * 1024 });
|
|
if (!bodyResult.ok) return bodyResult.response;
|
|
const parsed = bodySchema.safeParse(bodyResult.data);
|
|
|
|
if (!parsed.success) {
|
|
return fail("Ungültige Eingabe", 400, parsed.error.flatten());
|
|
}
|
|
|
|
const settings = await getSettings([SETTING_KEYS.COMPANY_NAME]);
|
|
const result = await sendSmtpTestEmail({
|
|
to: parsed.data.to,
|
|
companyName: settings[SETTING_KEYS.COMPANY_NAME] ?? "CalBook",
|
|
smtp: parsed.data.smtp
|
|
});
|
|
|
|
if (!result.ok) {
|
|
return fail(result.message ?? "SMTP-Test fehlgeschlagen", 400);
|
|
}
|
|
|
|
return ok({ message: "SMTP-Testmail erfolgreich versendet" });
|
|
} catch (error) {
|
|
return handleAuthError(error);
|
|
}
|
|
}
|