added
This commit is contained in:
1 parent
38ae828d82
commit
6dda00181f
29 files changed
+1185
-339
No files matched your search
+37
-2
@@ -7,13 +7,17 @@ Required environment variables:
|
||||
SMTP_PASSWORD
|
||||
CONTACT_TO_EMAIL
|
||||
CONTACT_FROM_EMAIL
|
||||
RECAPTCHA_SECRET_KEY
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import smtplib
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
from email.message import EmailMessage
|
||||
|
||||
from fastapi import FastAPI, Form, HTTPException, Request
|
||||
@@ -32,6 +36,35 @@ def require_env(name: str) -> str:
|
||||
return value
|
||||
|
||||
|
||||
def verify_recaptcha(token: str, remote_ip: str) -> None:
|
||||
if not token:
|
||||
raise HTTPException(status_code=400, detail="CAPTCHA verification required")
|
||||
|
||||
payload = urllib.parse.urlencode(
|
||||
{
|
||||
"secret": require_env("RECAPTCHA_SECRET_KEY"),
|
||||
"response": token,
|
||||
"remoteip": remote_ip,
|
||||
}
|
||||
).encode("utf-8")
|
||||
|
||||
verify_request = urllib.request.Request(
|
||||
"https://www.google.com/recaptcha/api/siteverify",
|
||||
data=payload,
|
||||
headers={"Content-Type": "application/x-www-form-urlencoded"},
|
||||
method="POST",
|
||||
)
|
||||
|
||||
try:
|
||||
with urllib.request.urlopen(verify_request, timeout=10) as response:
|
||||
result = json.loads(response.read().decode("utf-8"))
|
||||
except Exception as exc:
|
||||
raise HTTPException(status_code=502, detail="CAPTCHA verification failed") from exc
|
||||
|
||||
if not result.get("success"):
|
||||
raise HTTPException(status_code=400, detail="Invalid CAPTCHA")
|
||||
|
||||
|
||||
@app.get("/api/contact/healthz")
|
||||
def healthz() -> dict[str, str]:
|
||||
return {"status": "ok"}
|
||||
@@ -44,6 +77,7 @@ def send_contact(
|
||||
email: str = Form(...),
|
||||
message: str = Form(...),
|
||||
company: str = Form(""),
|
||||
recaptcha_response: str = Form("", alias="g-recaptcha-response"),
|
||||
) -> JSONResponse:
|
||||
if company:
|
||||
return JSONResponse({"ok": True})
|
||||
@@ -59,6 +93,9 @@ def send_contact(
|
||||
if not message or len(message) > 5000:
|
||||
raise HTTPException(status_code=400, detail="Invalid message")
|
||||
|
||||
client_ip = request.client.host if request.client else "unknown"
|
||||
verify_recaptcha(recaptcha_response, client_ip)
|
||||
|
||||
smtp_host = require_env("SMTP_HOST")
|
||||
smtp_port = int(os.getenv("SMTP_PORT", "587"))
|
||||
smtp_user = require_env("SMTP_USER")
|
||||
@@ -66,8 +103,6 @@ def send_contact(
|
||||
contact_to = require_env("CONTACT_TO_EMAIL")
|
||||
contact_from = require_env("CONTACT_FROM_EMAIL")
|
||||
|
||||
client_ip = request.client.host if request.client else "unknown"
|
||||
|
||||
email_message = EmailMessage()
|
||||
email_message["Subject"] = f"iNDX Earth contact form: {name}"
|
||||
email_message["From"] = contact_from
|
||||
|
||||
Reference in new issue
Block a user