Metadata-Version: 2.4
Name: django-secure-contact-form
Version: 0.3.0
Summary: A secure, customizable Django contact form package with CAPTCHA, honeypot spam protection, and timestamp validation.
Home-page: https://github.com/Gavin-Humphrey/django-secure-contact-form
Author: Gavin Humphrey
Author-email: gavin.humphrey.pro@gmail.com
License: MIT
Classifier: Environment :: Web Environment
Classifier: Framework :: Django
Classifier: Framework :: Django :: 4.0
Classifier: Framework :: Django :: 4.1
Classifier: Framework :: Django :: 4.2
Classifier: Framework :: Django :: 5.0
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.8
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Internet :: WWW/HTTP
Classifier: Topic :: Internet :: WWW/HTTP :: Dynamic Content
Requires-Python: >=3.8
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: Django>=4.0
Requires-Dist: django-simple-captcha>=0.5.14
Requires-Dist: Pillow>=8.0.0
Dynamic: author
Dynamic: author-email
Dynamic: classifier
Dynamic: description
Dynamic: description-content-type
Dynamic: home-page
Dynamic: license
Dynamic: license-file
Dynamic: requires-dist
Dynamic: requires-python
Dynamic: summary

# Django Secure Contact Form Plugin

## Overview

The **Django Secure Contact Form** plugin provides a secure, production-grade, and customizable contact form for Django projects.

It includes:

* **Multi-Layer Spam Defense:** Built-in CAPTCHA, passive honeypots, and signed time-guard submission heuristics.
* **Developer Security Controls:** Configurable security settings via `settings.py` to adapt protection layers per environment.
* **Automated Email Notifications:** Standard Django email backends with DMARC-compliant `Reply-To` headers.
* **Database Persistence:** Safely saves submissions to prevent lost messages when email delivery fails.
* **Customizable Templates:** Complete control over styling, HTML templates, and success layouts.
* **Extensible Architecture:** Easy subclassing of the default models and forms for custom inputs.

---

## What's New in Version 0.3.0

* **Silent Honeypot Trap (`hp_website`):** Captures automated web scrapers and silently redirects them to the success page without saving data or sending emails.
* **Signed Time Guard (`form_rendered_at`):** Detects and rejects sub-3-second automated form submission scripts while using cryptographic signatures to prevent timestamp spoofing.
* **Configurable Security Dictionary (`SECURE_CONTACT_FORM`):** Easily enable or disable CAPTCHA, honeypot, and time-guard settings in `settings.py`.
* **Passive Bot Defense:** Delivers zero-friction spam blocking for real visitors while stopping automated scripts.

---

## Installation

### 1. Install the Package

Install the package from PyPI:

```bash
pip install django-secure-contact-form
```

### 2. Add the Plugin to Your Django Project

Add `django_secure_contact_form` and `captcha` to `INSTALLED_APPS` in your `settings.py`:

```python
INSTALLED_APPS = [
    # Other installed apps...
    "django_secure_contact_form",
    "captcha",
]
```

### 3. Include URLs

In your project's root `urls.py`, include the plugin's URLs:

```python
from django.urls import include, path

urlpatterns = [
    # Other URL patterns...
    path("contact/", include("django_secure_contact_form.urls")),
    path("captcha/", include("captcha.urls")),
]
```

### 4. Apply Migrations

Run the following command to create the required database tables:

```bash
python manage.py migrate
```

---

## Configuration

### 1. Plugin Security Settings (v0.3.0+)

Customize or toggle individual security mechanisms by defining `SECURE_CONTACT_FORM` in `settings.py`.

The following are the default settings:

```python
SECURE_CONTACT_FORM = {
    "HONEYPOT_ENABLED": True,
    "TIME_GUARD_ENABLED": True,
    "MIN_SUBMISSION_TIME": 3,  # Minimum seconds allowed before POST submission
    "CAPTCHA_ENABLED": True,
}
```

| Setting               | Default | Description                                                              |
| --------------------- | ------: | ------------------------------------------------------------------------ |
| `HONEYPOT_ENABLED`    |  `True` | Enables the passive honeypot field.                                      |
| `TIME_GUARD_ENABLED`  |  `True` | Enables the signed time-based submission guard.                          |
| `MIN_SUBMISSION_TIME` |     `3` | Minimum number of seconds allowed between form rendering and submission. |
| `CAPTCHA_ENABLED`     |  `True` | Enables CAPTCHA verification.                                            |

> **Note:** The time guard is a behavioral heuristic and should not be considered standalone proof that a visitor is human.

### 2. Email Configuration

Configure the standard Django email settings in your project's `settings.py`.

Set `CONTACT_FORM_RECIPIENT_EMAIL` to specify where contact form submissions should be delivered.

```python
# ------------------------------------------------------------------------------
# Email Settings
# ------------------------------------------------------------------------------

# For Local Testing (Console Output)
EMAIL_BACKEND = "django.core.mail.backends.console.EmailBackend"

# For Production (SMTP Example)
# EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend"
# EMAIL_HOST = "smtp.gmail.com"
# EMAIL_PORT = 587
# EMAIL_USE_TLS = True
# EMAIL_HOST_USER = "your_email@gmail.com"
# EMAIL_HOST_PASSWORD = "your_app_password"

# Default Sender Email (Required for email headers)
DEFAULT_FROM_EMAIL = "webmaster@yourdomain.com"

# Recipient Address for Contact Form Submissions
CONTACT_FORM_RECIPIENT_EMAIL = "admin@yourdomain.com"
```

> **Note:** For production environments, use environment variables or a secrets manager for sensitive values such as `EMAIL_HOST_PASSWORD`.

### 3. CAPTCHA Configuration

The plugin uses `django-simple-captcha`. If `CAPTCHA_ENABLED` is set to `True`, you can customize the CAPTCHA appearance in `settings.py`:

```python
# CAPTCHA Customization Settings

CAPTCHA_IMAGE_SIZE = (110, 50)
CAPTCHA_FONT_SIZE = 30
CAPTCHA_LETTER_ROTATION = (-30, 30)
CAPTCHA_BACKGROUND_COLOR = "#ffffff"
CAPTCHA_NOISE_FUNCTIONS = (
    "captcha.helpers.noise_arcs",
    "captcha.helpers.noise_dots",
)
```

---

## How Spam Protection Works

This plugin protects your site against automated spam through three distinct layers.

### 1. Passive Honeypot Trap

The form injects an invisible `hp_website` input field using `display: none !important;`. Human visitors cannot normally see or interact with it.

If an automated bot fills in this field, the view performs a **silent drop** by redirecting the client to the success page while:

* Skipping database storage
* Skipping email generation
* Suppressing error feedback that could help bot developers adapt their scripts

### 2. Time-Based Submission Guard

When the form renders, a timestamp token (`form_rendered_at`) is cryptographically signed using Django's `django.core.signing.Signer` and embedded as a hidden field.

#### Tamper Prevention vs. Human Proof

The cryptographic signature guarantees that the timestamp was generated by your Django backend and has not been altered by the client.

The `MIN_SUBMISSION_TIME` check, which defaults to **3 seconds**, acts as a **behavioral heuristic** to identify rapid automated submissions.

#### Operation

If a POST submission arrives faster than the configured threshold, it is flagged as potential automated activity and rejected.

> **Note:** The time guard is intended as a speed heuristic to eliminate low-effort automated traffic. It is not standalone proof of human identity.

### 3. Visual CAPTCHA

When enabled, `django-simple-captcha` provides a direct interactive challenge for environments requiring active verification alongside the passive anti-spam mechanisms.

Together, these layers provide defense-in-depth protection against automated contact-form spam.

---

## Customization

### Template Customization

You can override the default templates with your own design.

### 1. Create the Template Directory

Inside your project's `templates` directory, create a directory named `django_secure_contact_form`:

```text
my_project/
└── templates/
    └── django_secure_contact_form/
        ├── contact_form.html
        ├── contact_success.html
        └── email_template.html
```

### 2. Template Overview

| Template               | Description                                                    |
| ---------------------- | -------------------------------------------------------------- |
| `contact_form.html`    | Renders the contact form and validation/error messages.        |
| `contact_success.html` | Displayed after a successful form submission or honeypot drop. |
| `email_template.html`  | HTML layout used for outgoing contact notification emails.     |

### 3. Template Error Handling

Ensure your custom `contact_form.html` properly renders backend and form errors:

```html
{% load static %}

<!-- Display Backend / Email Dispatch Errors -->
{% if error_message %}
    <div class="errors">
        <p><strong>Error:</strong> {{ error_message }}</p>
    </div>
{% endif %}

<!-- Display Non-Field Form Errors -->
{% if form.non_field_errors %}
    <div class="errors">
        {% for error in form.non_field_errors %}
            <p>{{ error }}</p>
        {% endfor %}
    </div>
{% endif %}

<form method="post" action="{% url 'contact' %}">
    {% csrf_token %}

    {{ form.as_p }}

    <button type="submit">Send</button>
</form>
```

### 4. Add Custom Styling

For example:

```css
body {
    font-family: Arial, sans-serif;
    background-color: #f7f7f7;
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 100vh;
    margin: 0;
}

form {
    background-color: #ffffff;
    padding: 2rem;
    border-radius: 0.5rem;
    box-shadow: 0 0 0.625rem rgba(0, 0, 0, 0.1);
    max-width: 30rem;
    width: 100%;
}

input[type="text"],
input[type="email"],
textarea {
    width: 100%;
    padding: 0.625rem;
    margin: 0.625rem 0;
    border: 1px solid #cccccc;
    border-radius: 0.25rem;
    box-sizing: border-box;
}

button {
    background-color: #007bff;
    color: #ffffff;
    border: none;
    padding: 0.625rem;
    border-radius: 0.25rem;
    cursor: pointer;
    width: 100%;
}

button:hover {
    background-color: #0056b3;
}

.errors {
    color: #721c24;
    background-color: #f8d7da;
    border: 1px solid #f5c6cb;
    padding: 10px;
    border-radius: 4px;
    margin-bottom: 1rem;
}
```

---

## Extending and Customizing the Model and Form

### Standard Implementation

For standard usage, including the plugin's URLs in your project's `urls.py` automatically connects the default view and form.

No additional view code is required.

### Custom Fields and Forms

If you need additional fields, you can extend the default `ContactMessage` model and `ContactForm`.

### 1. Extend the `ContactMessage` Model

```python
from django.db import models

from django_secure_contact_form.models import ContactMessage


class CustomContactMessage(ContactMessage):
    phone_number = models.CharField(
        max_length=20,
        blank=True,
        null=True,
    )
```

### 2. Extend the `ContactForm`

```python
from django import forms

from django_secure_contact_form.forms import ContactForm
from .models import CustomContactMessage


class CustomContactForm(ContactForm):
    phone_number = forms.CharField(required=False)

    class Meta(ContactForm.Meta):
        model = CustomContactMessage
        fields = ContactForm.Meta.fields + ["phone_number"]
```

> **Note:** If you extend the model, you will need to create and apply Django migrations for your custom model.

---

## Testing and Troubleshooting

### 1. Start the Development Server

Run:

```bash
python manage.py runserver
```

### 2. Test Form Submissions

Navigate to:

`http://127.0.0.1:8000/contact/`

Fill out the form with test data and submit it.

If you are using Django's console email backend:

```python
EMAIL_BACKEND = "django.core.mail.backends.console.EmailBackend"
```

the generated email will be displayed directly in your terminal.

### 3. Test Spam Protection Features

#### Test the Honeypot

Inspect the rendered HTML using your browser's Developer Tools (`F12`) and locate:

```html
<input name="hp_website">
```

Enter dummy text into the field and submit the form.

The application should redirect to the success page without:

* Saving a database record
* Sending an email
* Exposing that the submission was detected as spam

#### Test the Time Guard

Load the contact form and attempt to submit it in less than **3 seconds**, or less than your configured `MIN_SUBMISSION_TIME`.

The submission should trigger the form's submission-speed validation error.

### Troubleshooting Tips

#### Static Files Not Loading

Run:

```bash
python manage.py collectstatic
```

Also verify that your `STATIC_URL` and other static-file settings are correctly configured in `settings.py`.

#### CAPTCHA Image Errors

Ensure Pillow is installed in your virtual environment:

```bash
pip install pillow
```

#### Form Fails Silently

If you have overridden `contact_form.html`, ensure that it renders both the backend error message and Django form errors:

```django
{% if error_message %}
    <p>{{ error_message }}</p>
{% endif %}

{{ form.errors }}
```

---

## License

This project is licensed under the **MIT License**. See the [`LICENSE`](LICENSE) file for details.
