# Recipe: custom domains in a Django app

Let the users of a Django app connect their own domain with Cnamio: a session view, the connect window in a template, and a webhook view. Uses the Python server SDK (`pip install cnamio`, Python 3.9+, standard library only). The full guide is https://cnamio.com/agent-onboarding/SKILL.md.

## 1. Install and configure

```bash
pip install cnamio
```

Or vendor the single module instead: `curl -s https://cnamio.com/sdk/cnamio.py -o cnamio.py`.
```bash
CNAMIO_APPLICATION_ID=app_…
CNAMIO_SECRET=cnm_sk_…        # server only, never committed
CNAMIO_OWNERSHIP_KEY=…        # any long random secret of yours
CNAMIO_WEBHOOK_SECRET=…
```

No account yet? A coding agent can call the MCP tool `start_signup` (or `POST https://api.cnamio.com/v1/agent/signup`) with your email, and work in the sandbox until you open the verification link.

## 2. Views: `domains/views.py`

```python
import json
import os

from cnamio import Cnamio, CnamioError, records_for_user, verify_webhook
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse, JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST

cnamio = Cnamio()  # reads CNAMIO_APPLICATION_ID and CNAMIO_SECRET


def records_for(user_id):
    # A CNAME to your hosting plus a TXT only this user can satisfy.
    return records_for_user(target="customers.yourapp.com", user_id=user_id, ownership_key=os.environ["CNAMIO_OWNERSHIP_KEY"])


@login_required
@require_POST
def cnamio_session(request):
    try:
        return JsonResponse(cnamio.create_session(user_id=request.user.pk, dns_records=records_for(request.user.pk)))
    except CnamioError:
        return JsonResponse({"error": "cnamio_unavailable"}, status=502)


@csrf_exempt  # signed by Cnamio instead of a CSRF token
@require_POST
def cnamio_webhook(request):
    if not verify_webhook(request.body, request.headers, os.environ.get("CNAMIO_WEBHOOK_SECRET")):
        return HttpResponse(status=401)
    event = json.loads(request.body)
    # Idempotent by event["id"]: the same event may arrive again.
    if event["type"] == "domain.added":
        mark_domain_connected(event["user_id"], event["domain"])  # your code
    elif event["type"] == "domain.propagation.timeout":
        mark_domain_failed(event["user_id"], event["domain"])
    return HttpResponse(status=200)
```

```python
# urls.py
from django.urls import path
from domains import views

urlpatterns = [
    path("api/cnamio/session", views.cnamio_session),
    path("webhooks/cnamio", views.cnamio_webhook),
]
```

## 3. Connect button: in a template

```html
<script src="https://connect.cnamio.com/sdk/v1.js"></script>
<button id="connect-domain">Connect your domain</button>
<script>
  document.getElementById('connect-domain').addEventListener('click', async () => {
    const r = await fetch('/api/cnamio/session', { method: 'POST', headers: { 'X-CSRFToken': '{{ csrf_token }}' } });
    if (!r.ok) return alert('Custom domains are unavailable right now.');
    window.cnamio.connectDomain({ ...(await r.json()), applicationName: 'Your App', locale: 'en' });
  });
</script>
```

## 4. Headless (management commands, agents)

```python
records = records_for(user.pk)
check = cnamio.check_domain("shop.customer.com", records)  # provider, setupType, connectMethods, conflicts
if "api_token" in check["connectMethods"] and provider_token:
    job = cnamio.connect_automatic("shop.customer.com", records, provider_token, user_id=user.pk)
else:
    job = cnamio.connect("shop.customer.com", records, user_id=user.pk)  # exact records to show the user
print(cnamio.status(job["job_id"])["status"])
```

## 5. Check it

With the test application's credentials every domain goes to the sandbox provider: `shop.example.com` connects at once, `conflict.example.com` shows a conflict, `pending.example.com` never propagates. Register the webhook with `cnamio.manage.set_webhook_url("https://yourapp.com/webhooks/cnamio")` and send a signed test with `cnamio.manage.test_webhook()`.
