From 35ba0b2694079a168d29e2eb05dd226f363496dc Mon Sep 17 00:00:00 2001 From: Dorian Niemiec Date: Sat, 7 Sep 2024 12:26:34 +0200 Subject: [PATCH] fix: implement hCaptcha verification and remove "captchaToken" field from email messages --- app/api/contact/route.ts | 35 +++++++++++++++++++++++++++++------ 1 file changed, 29 insertions(+), 6 deletions(-) diff --git a/app/api/contact/route.ts b/app/api/contact/route.ts index 459c581..27c419b 100644 --- a/app/api/contact/route.ts +++ b/app/api/contact/route.ts @@ -27,12 +27,14 @@ const generateEmailContent = (data: Record) => { const htmlData = Object.entries(data).reduce( (str, [key, val]) => str + - `

${escapeHtml( - CONTACT_MESSAGE_FIELDS[key] || key - )}

${escapeHtml(val).replace( - /\n/g, - "
" - )}

`, + (key == "captchaToken" + ? "" + : `

${escapeHtml( + CONTACT_MESSAGE_FIELDS[key] || key + )}

${escapeHtml(val).replace( + /\n/g, + "
" + )}

`), "" ); @@ -106,6 +108,27 @@ export async function POST(req: NextRequest) { const data = await req.json(); console.log(data); + // Verify hCaptcha token + const hcaptchaResponse = await fetch( + `https://api.hcaptcha.com/siteverify`, + { + method: "POST", + headers: { + "Content-Type": "application/x-www-form-urlencoded" + }, + body: `secret=${process.env.HCAPTCHA_SECRET}&response=${data.captchaToken}` + } + ); + + const hcaptchaData = await hcaptchaResponse.json(); + + if (!hcaptchaData.success) { + return NextResponse.json( + { message: "Captcha verification failed." }, + { status: 400 } + ); + } + await transporter.sendMail({ ...mailOptions, ...generateEmailContent(data),