# Add Email Verification to a Django REST Framework Project

Yes. An agent adds a verify-email flow on Django's token generator and the project's Email model, keeps unverified accounts from logging in, tests it and opens a PR.

[Run this on Rush](https://cloud.getrush.ai/run/add-email-verification/django-rest-framework/). Opens the console with this prompt ready to send, in a Project that has your repository.

## What the agent does

The agent reads how accounts are made and mailed before it adds a step between the two. In a project shaped like HackSoftware/Django-Styleguide-Example, `requirements/base.txt` pins `Django` 5.2.7, `djangorestframework` 3.16.1, `drf-jwt` 1.19.2 and `celery` 5.5.3, and `requirements/local.txt` adds `pytest` 8.4.2 with `pytest-django`, `mypy` 1.18.2 with the Django and DRF stubs, and `ruff` 0.14.0. `users/models.py` defines `BaseUser` with `email` as `USERNAME_FIELD`, `is_active` defaulting to `True`, and a `jwt_key` UUID. `users/apis.py` exposes `UserCreateApi` at `users/create/`: an `InputSerializer` of `email` and `password`, a call to `user_create` in `users/services.py`, and an active account from the first second, with no mail sent. `authentication/apis.py` has `UserSessionLoginApi` built on Django's `authenticate()` and `UserJwtLoginApi` on `ObtainJSONWebTokenView`; `users/selectors.py` returns `is_active` in the login data. The `emails` app has an `Email` model with `READY`, `SENDING`, `SENT` and `FAILED` states and an `email_send_all` service that flips rows to `SENDING` and queues the Celery task on commit; `config/settings/email_sending.py` uses the console backend when `EMAIL_SENDING_STRATEGY` is `local`. `config/settings/cors.py` defines `BASE_FRONTEND_URL`, default `http://localhost:3000`, and `config/django/base.py` sets `EXCEPTION_HANDLER` to `drf_default_with_modifications_exception_handler`, which turns a Django `ValidationError` into a 400.

The gate is `is_active`, which Django's `ModelBackend` already enforces: `authenticate()` returns `None` for an inactive user, so both login routes answer 400 until the address is verified and no view needs a new check. `UserCreateApi` passes `is_active=False` to `user_create`, whose signature already takes it, so the service and its tests in `users/tests/services/test_user_create.py` are untouched. Two services land in `authentication/services.py`. `email_verification_send(*, user)` builds a token with a small `EmailVerificationTokenGenerator(PasswordResetTokenGenerator)` whose `_make_hash_value` adds `is_active` to the hash, so a link stops working the moment it is used, encodes the primary key with `urlsafe_base64_encode`, composes `BASE_FRONTEND_URL` plus `/verify-email/<uid>/<token>`, creates an `Email` row and hands it to `email_send_all`, so delivery goes through the same Celery task and retry the project already has. `email_verification_confirm(*, uid, token)` decodes the uid, checks the token, sets `is_active` to `True` and saves; a bad uid or a stale token raises Django's `ValidationError`, which the configured handler maps to a 400. No field is added and no migration ships.

The APIs follow the house style in `authentication/apis.py`: an `APIView` with a nested `InputSerializer`, a call into a service, a plain `Response`. `EmailVerificationConfirmApi` takes `uid` and `token`; `EmailVerificationResendApi` takes one `EmailField` and always answers 200, doing nothing for an unknown or already active address so the endpoint cannot be used to learn which emails exist. They mount under `auth/verify-email/confirm/` and `auth/verify-email/resend/` in a `verify-email` namespace, so `reverse('api:authentication:verify-email:confirm')` works the way the login tests use `reverse`. Type hints are complete so `mypy --config mypy.ini styleguide_example/` passes with the stubs.

Tests go in `authentication/tests/apis/test_email_verification.py` in the shape of `test_user_login.py`: `TestCase` with `APIClient`. One test posts to `users/create/`, asserts exactly one `Email` row and an inactive user, tries both login routes and asserts 400, pulls the uid and token out of the row's `plain_text`, posts them to the confirm URL, and logs in through `session/login/` and `jwt/login/` with 200. Others cover a tampered token, a second use of the same link after confirmation, a resend for an unknown email that creates no row, and a resend for a verified account that creates none either. Before pushing, the agent runs `ruff check .`, `mypy --config mypy.ini styleguide_example/` and `pytest`, the three commands in `.github/workflows/django.yml`, and pastes the results into the pull request.

## Start it with one API call

`POST https://api.phoenix.so/o/{org}/sessions`

```json
{
  "agent": "claude",
  "input": "Add email verification to this Django REST Framework project and open a pull request. Read styleguide_example/api/urls.py, users/apis.py, users/services.py, users/models.py, users/selectors.py, authentication/apis.py, authentication/services.py, authentication/urls.py, authentication/tests/apis/test_user_login.py, emails/models.py, emails/services.py, api/exception_handlers.py, config/django/base.py, config/settings/cors.py, config/settings/email_sending.py, mypy.ini and .github/workflows/django.yml first. Make UserCreateApi create the user with is_active=False. Add email_verification_send(*, user) and email_verification_confirm(*, uid, token) to authentication/services.py: a PasswordResetTokenGenerator subclass whose hash includes is_active, urlsafe_base64_encode for the uid, a link built from BASE_FRONTEND_URL plus /verify-email/<uid>/<token>, an Email row sent through email_send_all, and on confirm set is_active to True; raise Django's ValidationError for a bad uid or token. Add EmailVerificationConfirmApi (uid, token) and EmailVerificationResendApi (email, always 200, no row for an unknown or active address) in the existing APIView style with nested InputSerializers, mounted at auth/verify-email/confirm/ and auth/verify-email/resend/ under a verify-email namespace. Write authentication/tests/apis/test_email_verification.py covering create then both logins refused, confirm from the uid and token in the Email row then both logins accepted, a tampered token, a reused link, and resend for unknown and verified addresses. Run ruff check ., mypy --config mypy.ini styleguide_example/ and pytest, and paste the results in the pull request. Do not add a model field, a migration or a dependency, and do not change the login endpoints.",
  "resources": [
    {
      "url": "https://github.com/your-org/your-app"
    }
  ]
}
```

1. **Get an API key.** In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
2. **Send the request.** POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
3. **Read what came back.** Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.

## What comes back

What comes back is a pull request that edits `users/apis.py`, `authentication/services.py`, `authentication/apis.py` and `authentication/urls.py`, adds `authentication/tests/apis/test_email_verification.py`, and touches no model and no migration. The description lists the two URLs and their bodies, explains why resend always answers 200, and pastes the `ruff`, `mypy` and `pytest` output.

On a repository with the `Django application` workflow, the pull request builds the Docker image and runs `ruff check`, `mypy` and `py.test` inside it, then runs the same three against a Postgres service, so a missing type hint or a failing flow test shows in both jobs.

A reviewer checks that an existing `create_superuser` and the admin still make active accounts, that the token lifetime, Django's `PASSWORD_RESET_TIMEOUT`, suits a signup link, that the link uses `BASE_FRONTEND_URL` so the frontend owns the page, and that the email text reads well. Then they add the frontend page at `/verify-email/<uid>/<token>`.

## Run it on every API that registers users by email

A team with several Django REST Framework services sends one `POST /o/{org}/sessions` per repository with this prompt and that repository in `resources`. Each run reads its own user model and mail path, so a project that sends with `send_mail` directly gets that instead of an `Email` row, and a project with a verified flag already on the model gets the flag set instead of `is_active`, and each run opens its own pull request.

Give the API key a `webhook_url` and Rush POSTs `run.completed` when each turn ends, with the `session_url` to read the pull request and the test output from.

## Why run it on Rush?

Email verification is security code with two easy mistakes: a resend endpoint that reveals which addresses exist, and a link that keeps working after it has been used. In a Rush sandbox the agent runs the project's own `pytest` with the full flow, create, refused login, confirm, accepted login, reused link refused, and keeps the output in the run's record, so the pull request shows those properties checked rather than asserted.

The change reuses what the project already has, Django's token generator, the `Email` model and its Celery task, the `is_active` check inside `authenticate()`, so there is no new dependency, no migration and nothing for a reviewer to learn. The same request works on any Django REST Framework project with a custom user model.

## Frequently asked questions

### Why gate on is_active instead of a new field?

Because `ModelBackend.authenticate()` already refuses inactive users, so both the session and the JWT login refuse an unverified account without a new check in either view, and no migration is needed. A project that uses `is_active` for suspension too gets a separate `email_verified_at` field instead, and the pull request says which it chose.

### Why does the resend endpoint return 200 for an unknown email?

So the response does not say whether an account exists. The service returns early for an unknown or already active address and creates no `Email` row; the tests for both cases assert the 200 and the empty table.

### Can a verification link be used twice?

No. The token generator hashes `is_active` along with the fields `PasswordResetTokenGenerator` already uses, so the token made before confirmation no longer verifies once the account is active. The test posts the same uid and token twice and asserts the second answer is 400.

### Where does the link point?

To `BASE_FRONTEND_URL` plus `/verify-email/<uid>/<token>`, the setting already used for CORS, so the frontend renders a page and posts the two values to `auth/verify-email/confirm/`. Change the path in one place in `email_verification_send` if your frontend uses another route.

## More Django REST Framework jobs

- [Add Health Checks to a Django REST Framework API](https://getrush.ai/run/add-health-checks/django-rest-framework/)
- [Add Idempotency Keys to a Django REST Framework API](https://getrush.ai/run/add-idempotency-keys/django-rest-framework/)
- [Add OpenAPI Docs to a Django REST Framework API](https://getrush.ai/run/add-openapi-docs/django-rest-framework/)

## The same job on other stacks

- [Add Email Verification to a Filament Panel from a Linear Issue](https://getrush.ai/run/add-email-verification/filament/)
- [Add Email Verification to a FastAPI App on SQLModel](https://getrush.ai/run/add-email-verification/sqlmodel/)
- [Add Email Verification to an AdonisJS App](https://getrush.ai/run/add-email-verification/adonisjs/)

## Keep reading

- [How a Rush run works on your repository, from request to pull request](https://getrush.ai/cloud/)
- [Compare cloud agents, agent sandboxes and AI code review](https://getrush.ai/compare/)
- [Rush pricing: Free, Pro and Max](https://getrush.ai/pricing/)
