sightbox/website/backend/routes/contact.py

78 lines
2.5 KiB
Python

"""
POST /api/contact — the homepage's "Request a demo" form. This site used
to call the main app's backend for this; now that the website is a fully
standalone deployment, it sends through this backend's own Resend account
instead, so it has zero runtime dependency on apps/bi/backend.
Data flow:
JSON {name, email, organization?, message?} → validated (required
fields, length caps, whitespace/newline-normalized, HTML-escaped
before going into the email body) → services/email_service.send_email()
→ 202 response
"""
import html
import logging
from flask import Blueprint, jsonify, request
from config import Config
from middleware.rate_limit import limiter
from services.email_service import send_email
logger = logging.getLogger(__name__)
contact_bp = Blueprint("contact", __name__)
_MAX_NAME_LENGTH = 200
_MAX_EMAIL_LENGTH = 200
_MAX_ORG_LENGTH = 200
_MAX_MESSAGE_LENGTH = 2000
def _clean(value: str, max_length: int) -> str:
return " ".join((value or "").split())[:max_length]
@contact_bp.route("/api/contact", methods=["POST"])
@limiter.limit(lambda: f"{Config.RATELIMIT_PER_HOUR} per hour")
def submit_contact():
"""
Accepts a "Request a demo" submission from the marketing homepage.
Data flow: see module docstring.
"""
body = request.get_json(silent=True) or {}
name = _clean(body.get("name"), _MAX_NAME_LENGTH)
email = _clean(body.get("email"), _MAX_EMAIL_LENGTH)
organization = _clean(body.get("organization"), _MAX_ORG_LENGTH)
message = _clean(body.get("message"), _MAX_MESSAGE_LENGTH)
if not name:
return jsonify({"error": "name is required"}), 400
if not email or "@" not in email or "." not in email.split("@")[-1]:
return jsonify({"error": "a valid email is required"}), 400
body_parts = [
f"<p><strong>Name:</strong> {html.escape(name)}</p>",
f"<p><strong>Email:</strong> {html.escape(email)}</p>",
]
if organization:
body_parts.append(f"<p><strong>Organization:</strong> {html.escape(organization)}</p>")
if message:
body_parts.append(f"<p><strong>Message:</strong><br>{html.escape(message)}</p>")
try:
send_email(
to=Config.SALES_EMAIL,
subject=f"Demo request from {name}",
html_body="".join(body_parts),
reply_to=email,
)
except Exception:
logger.exception("Failed to send 'Request a demo' notification")
return jsonify({"error": "Could not send your request — please try again shortly."}), 502
return jsonify({"status": "sent"}), 202