# merixstudio/django-trench architecture

> Architecture diagram of the GitHub repository merixstudio/django-trench, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2026-04-08). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/merixstudio/django-trench
- Repository: https://github.com/merixstudio/django-trench

## Overview

1. **What this repository is**
   `django-trench` is a reusable Django app, not a standalone service. Its job is to add multi-factor authentication to Django REST Framework apps, with support for two main auth flows: DRF token auth and JWT-based auth.

2. **Public integration surface**
   The package exposes API routes through `trench/urls/`, with separate endpoint sets for token auth and JWT auth. Matching view implementations live under `trench/views/`, so the library can plug into an existing Django project without owning the whole application.

3. **Request handling shape**
   The views are likely thin orchestration layers: they receive REST requests, validate payloads through serializers, invoke command/use-case objects, and return structured responses. This keeps HTTP concerns separate from MFA business logic.

4. **Core MFA domain**
   The persistent MFA state is modeled in `trench/models.py` and managed through Django migrations. This is the source of truth for things like MFA methods, activation status, primary method choice, and backup codes. The root app is a Django app with admin integration via `trench/admin.py`.

5. **Use-case / command layer**
   The `trench/command/` package is the main business-logic boundary. It contains explicit operations such as:
   - authenticating the user’s first factor
   - creating and validating OTPs
   - generating secrets and backup codes
   - activating/deactivating MFA methods
   - selecting a primary MFA method
   This suggests a command-oriented architecture where each endpoint maps to a small, named MFA action.

6. **Backend abstraction for delivering second factors**
   The `trench/backends/` package is the delivery/integration layer. `base.py` and `provider.py` define the backend abstraction, while concrete backends implement delivery via:
   - email
   - SMS APIs
   - Twilio
   - AWS services
   - YubiKey
   - authenticator-app style flows
   This is the main boundary between core MFA logic and external communication services.

7. **OTP and secret generation flow**
   Second-factor setup and verification depend on generated OTPs and secrets. Those concerns are separated into commands rather than being embedded in views or backends, which means the backend is responsible for delivery or device-specific interaction, while the command layer owns the security workflow.

8. **Configuration and lookup**
   `trench/settings.py` and `trench/query/get_mfa_config_by_name.py` indicate that MFA backends and policies are configured declaratively, then resolved at runtime. That means the app is designed to be customized per host project rather than hardcoding a single MFA policy.

9. **Response and serialization boundary**
   `trench/serializers.py`, `trench/responses.py`, and `trench/exceptions.py` define the contract for API payloads and error handling. This keeps the package’s external API predictable for DRF consumers and separates domain failures from transport-level responses.

10. **Email delivery assets**
   The templates under `trench/templates/trench/backends/email/` show that at least the email backend renders both HTML and text code messages. That means email delivery is an integrated part of the library, not delegated entirely to the host app.

11. **Consumer test harness**
   The `testproject/` directory is a full Django project used to exercise the package in realistic conditions. It contains app models, URLs, serializers, migrations, and tests for first-step auth, second-step auth, token login, backends, commands, and query behavior. This is the clearest representation of how a real host project integrates `trench`.

12. **Architecture summary**
   The main data flow is: client request → DRF endpoint in `views/` → serializer validation → command/use-case execution → model/query access → backend delivery or verification → response token/result. The important architectural boundary is between the reusable MFA engine (`models`, `commands`, `backends`) and the host application’s auth stack (`authtoken` or JWT integration via URLs/views).

Main entry points: [`trench/views/base.py`](https://github.com/merixstudio/django-trench/blob/develop/trench/views/base.py) (Base View), [`trench/models.py`](https://github.com/merixstudio/django-trench/blob/develop/trench/models.py) (MFA Models), [`trench/backends/provider.py`](https://github.com/merixstudio/django-trench/blob/develop/trench/backends/provider.py) (Provider API), [`trench/command/create_secret.py`](https://github.com/merixstudio/django-trench/blob/develop/trench/command/create_secret.py) (Secrets & Codes)

## Diagram (Mermaid)

```mermaid
flowchart TD

subgraph group_trench_core["Trench app"]
  node_urls_base["Base URLs<br/>route wiring<br/>[base.py]"]
  node_urls_token["Token URLs<br/>route wiring<br/>[authtoken.py]"]
  node_urls_jwt["JWT URLs<br/>route wiring<br/>[jwt.py]"]
  node_view_base["Base View<br/>request orchestration<br/>[base.py]"]
  node_view_token["Token View<br/>REST view<br/>[authtoken.py]"]
  node_view_jwt["JWT View<br/>REST view<br/>[jwt.py]"]
  node_serializers["Serializers<br/>payload schema<br/>[serializers.py]"]
  node_responses["Responses<br/>response format<br/>[responses.py]"]
  node_exceptions["Exceptions<br/>error contract<br/>[exceptions.py]"]
  node_models[("MFA Models<br/>domain state<br/>[models.py]")]
  node_settings["Settings<br/>configuration<br/>[settings.py]"]
  node_query_cfg["Config Query<br/>lookup"]
  node_cmd_auth["Authenticate User<br/>command"]
  node_cmd_second["Second Factor<br/>command"]
  node_cmd_methods["MFA Methods<br/>command set"]
  node_cmd_secrets["Secrets & Codes<br/>command set<br/>[create_secret.py]"]
  node_backend_base["Backend Base<br/>backend abstraction<br/>[base.py]"]
  node_backend_provider["Provider API<br/>backend abstraction<br/>[provider.py]"]
  node_backend_delivery["Delivery Backends<br/>delivery adapters<br/>[basic_mail.py]"]
  node_email_templates["Email Templates<br/>rendered assets<br/>[code.txt]"]
  node_admin["Admin<br/>[admin.py]"]
end

subgraph group_testproject["Test project"]
  node_test_urls["Test URLs<br/>host wiring<br/>[urls.py]"]
  node_test_serializers["Test Serializers<br/>host schema<br/>[serializers.py]"]
  node_test_models[("Test Models<br/>host domain<br/>[models.py]")]
end

node_urls_base -->|"routes"| node_view_base
node_urls_token -->|"routes"| node_view_token
node_urls_jwt -->|"routes"| node_view_jwt
node_view_base -->|"validates"| node_serializers
node_view_base -->|"returns"| node_responses
node_view_base -->|"raises"| node_exceptions
node_view_base -->|"invokes"| node_cmd_auth
node_view_base -->|"invokes"| node_cmd_second
node_cmd_auth -->|"reads/writes"| node_models
node_cmd_second -->|"reads/writes"| node_models
node_cmd_methods -->|"manages"| node_models
node_cmd_secrets -->|"creates"| node_models
node_cmd_secrets -->|"uses"| node_backend_base
node_backend_base -->|"extends"| node_backend_provider
node_backend_provider -->|"implements"| node_backend_delivery
node_backend_delivery -->|"renders"| node_email_templates
node_settings -->|"resolves"| node_query_cfg
node_query_cfg -->|"selects"| node_backend_provider
node_admin -->|"manages"| node_models
node_test_urls -->|"integrates"| node_urls_token
node_test_urls -->|"integrates"| node_urls_jwt
node_test_serializers -.->|"mirrors"| node_serializers
node_test_models -.->|"extends"| node_models

click node_urls_base "https://github.com/merixstudio/django-trench/blob/develop/trench/urls/base.py"
click node_urls_token "https://github.com/merixstudio/django-trench/blob/develop/trench/urls/authtoken.py"
click node_urls_jwt "https://github.com/merixstudio/django-trench/blob/develop/trench/urls/jwt.py"
click node_view_base "https://github.com/merixstudio/django-trench/blob/develop/trench/views/base.py"
click node_view_token "https://github.com/merixstudio/django-trench/blob/develop/trench/views/authtoken.py"
click node_view_jwt "https://github.com/merixstudio/django-trench/blob/develop/trench/views/jwt.py"
click node_serializers "https://github.com/merixstudio/django-trench/blob/develop/trench/serializers.py"
click node_responses "https://github.com/merixstudio/django-trench/blob/develop/trench/responses.py"
click node_exceptions "https://github.com/merixstudio/django-trench/blob/develop/trench/exceptions.py"
click node_models "https://github.com/merixstudio/django-trench/blob/develop/trench/models.py"
click node_settings "https://github.com/merixstudio/django-trench/blob/develop/trench/settings.py"
click node_query_cfg "https://github.com/merixstudio/django-trench/blob/develop/trench/query/get_mfa_config_by_name.py"
click node_cmd_auth "https://github.com/merixstudio/django-trench/blob/develop/trench/command/authenticate_user.py"
click node_cmd_second "https://github.com/merixstudio/django-trench/blob/develop/trench/command/authenticate_second_factor.py"
click node_cmd_methods "https://github.com/merixstudio/django-trench/blob/develop/trench/command/create_mfa_method.py"
click node_cmd_secrets "https://github.com/merixstudio/django-trench/blob/develop/trench/command/create_secret.py"
click node_backend_base "https://github.com/merixstudio/django-trench/blob/develop/trench/backends/base.py"
click node_backend_provider "https://github.com/merixstudio/django-trench/blob/develop/trench/backends/provider.py"
click node_backend_delivery "https://github.com/merixstudio/django-trench/blob/develop/trench/backends/basic_mail.py"
click node_email_templates "https://github.com/merixstudio/django-trench/blob/develop/trench/templates/trench/backends/email/code.txt"
click node_admin "https://github.com/merixstudio/django-trench/blob/develop/trench/admin.py"
click node_test_urls "https://github.com/merixstudio/django-trench/blob/develop/testproject/testapp/urls.py"
click node_test_serializers "https://github.com/merixstudio/django-trench/blob/develop/testproject/testapp/serializers.py"
click node_test_models "https://github.com/merixstudio/django-trench/blob/develop/testproject/testapp/models.py"

classDef toneNeutral fill:#f8fafc,stroke:#334155,stroke-width:1.5px,color:#0f172a
classDef toneBlue fill:#dbeafe,stroke:#2563eb,stroke-width:1.5px,color:#172554
classDef toneAmber fill:#fef3c7,stroke:#d97706,stroke-width:1.5px,color:#78350f
classDef toneMint fill:#dcfce7,stroke:#16a34a,stroke-width:1.5px,color:#14532d
classDef toneRose fill:#ffe4e6,stroke:#e11d48,stroke-width:1.5px,color:#881337
classDef toneIndigo fill:#e0e7ff,stroke:#4f46e5,stroke-width:1.5px,color:#312e81
classDef toneTeal fill:#ccfbf1,stroke:#0f766e,stroke-width:1.5px,color:#134e4a
class node_urls_base,node_urls_token,node_urls_jwt,node_view_base,node_view_token,node_view_jwt,node_serializers,node_responses,node_exceptions,node_models,node_settings,node_query_cfg,node_cmd_auth,node_cmd_second,node_cmd_methods,node_cmd_secrets,node_backend_base,node_backend_provider,node_backend_delivery,node_email_templates,node_admin toneBlue
class node_test_urls,node_test_serializers,node_test_models toneAmber
```

## Components

### Trench app

Reusable Django app providing MFA domain, commands, backends, and DRF integration.

- [Base URLs](https://github.com/merixstudio/django-trench/blob/develop/trench/urls/base.py): route wiring · Shared endpoint definitions for the reusable MFA API. · `trench/urls/base.py`
- [Token URLs](https://github.com/merixstudio/django-trench/blob/develop/trench/urls/authtoken.py): route wiring · DRF token-auth MFA endpoints. · `trench/urls/authtoken.py`
- [JWT URLs](https://github.com/merixstudio/django-trench/blob/develop/trench/urls/jwt.py): route wiring · JWT-auth MFA endpoints. · `trench/urls/jwt.py`
- [Base View](https://github.com/merixstudio/django-trench/blob/develop/trench/views/base.py): request orchestration · Shared REST orchestration for MFA endpoints. · `trench/views/base.py`
- [Token View](https://github.com/merixstudio/django-trench/blob/develop/trench/views/authtoken.py): REST view · Token-auth endpoint implementation. · `trench/views/authtoken.py`
- [JWT View](https://github.com/merixstudio/django-trench/blob/develop/trench/views/jwt.py): REST view · JWT-auth endpoint implementation. · `trench/views/jwt.py`
- [Serializers](https://github.com/merixstudio/django-trench/blob/develop/trench/serializers.py): payload schema · Request and response validation for MFA API payloads. · `trench/serializers.py`
- [Responses](https://github.com/merixstudio/django-trench/blob/develop/trench/responses.py): response format · Structured API response helpers. · `trench/responses.py`
- [Exceptions](https://github.com/merixstudio/django-trench/blob/develop/trench/exceptions.py): error contract · Domain and API exception types. · `trench/exceptions.py`
- [MFA Models](https://github.com/merixstudio/django-trench/blob/develop/trench/models.py): domain state · Persistent MFA state and activation data. · `trench/models.py`
- [Settings](https://github.com/merixstudio/django-trench/blob/develop/trench/settings.py): configuration · Declarative MFA backend and policy configuration. · `trench/settings.py`
- [Config Query](https://github.com/merixstudio/django-trench/blob/develop/trench/query/get_mfa_config_by_name.py): lookup · Resolves MFA configuration by name at runtime. · `trench/query/get_mfa_config_by_name.py`
- [Authenticate User](https://github.com/merixstudio/django-trench/blob/develop/trench/command/authenticate_user.py): command · First-factor authentication use case. · `trench/command/authenticate_user.py`
- [Second Factor](https://github.com/merixstudio/django-trench/blob/develop/trench/command/authenticate_second_factor.py): command · Verifies second-factor credentials and OTPs. · `trench/command/authenticate_second_factor.py`
- [MFA Methods](https://github.com/merixstudio/django-trench/blob/develop/trench/command/create_mfa_method.py): command set · Create, activate, deactivate, and select primary MFA methods. · `trench/command/create_mfa_method.py`
- [Secrets & Codes](https://github.com/merixstudio/django-trench/blob/develop/trench/command/create_secret.py): command set · Generates secrets, OTPs, and backup codes. · `trench/command/create_secret.py`
- [Backend Base](https://github.com/merixstudio/django-trench/blob/develop/trench/backends/base.py): backend abstraction · Core interface for delivering or integrating second factors. · `trench/backends/base.py`
- [Provider API](https://github.com/merixstudio/django-trench/blob/develop/trench/backends/provider.py): backend abstraction · Backend provider contract and shared integration layer. · `trench/backends/provider.py`
- [Delivery Backends](https://github.com/merixstudio/django-trench/blob/develop/trench/backends/basic_mail.py): delivery adapters · Concrete backends for email, SMS, Twilio, AWS, YubiKey, and app-style flows. · `trench/backends/basic_mail.py`
- [Email Templates](https://github.com/merixstudio/django-trench/blob/develop/trench/templates/trench/backends/email/code.txt): rendered assets · HTML and text templates for email-based codes. · `trench/templates/trench/backends/email/code.txt`
- [Admin](https://github.com/merixstudio/django-trench/blob/develop/trench/admin.py): Django admin · Admin integration for managing MFA state. · `trench/admin.py`

### Test project

Host Django project used to exercise the package in realistic integrations.

- [Test URLs](https://github.com/merixstudio/django-trench/blob/develop/testproject/testapp/urls.py): host wiring · Example project URL configuration for integration testing. · `testproject/testapp/urls.py`
- [Test Serializers](https://github.com/merixstudio/django-trench/blob/develop/testproject/testapp/serializers.py): host schema · Example host serializers used by the test project. · `testproject/testapp/serializers.py`
- [Test Models](https://github.com/merixstudio/django-trench/blob/develop/testproject/testapp/models.py): host domain · Example host models used to validate integration behavior. · `testproject/testapp/models.py`

## Connections

- Base URLs → Base View: routes · Shared route definitions point to the base orchestration layer
- Token URLs → Token View: routes · Token endpoints map to token-auth views
- JWT URLs → JWT View: routes · JWT endpoints map to JWT views
- Base View → Serializers: validates · Views validate request payloads through serializers
- Base View → Responses: returns · Views format structured responses
- Base View → Exceptions: raises · Domain failures are surfaced as API exceptions
- Base View → Authenticate User: invokes · Endpoints start the authentication flow through commands
- Base View → Second Factor: invokes · Endpoints verify second factor through commands
- Authenticate User → MFA Models: reads/writes · Authentication commands inspect and update MFA state
- Second Factor → MFA Models: reads/writes · Second-factor verification depends on persisted MFA data
- MFA Methods → MFA Models: manages · Method commands create and update MFA method records
- Secrets & Codes → MFA Models: creates · Secret and code commands derive security material stored in the MFA domain
- Secrets & Codes → Backend Base: uses · Code generation feeds backend delivery or device workflows
- Backend Base → Provider API: extends · Provider contract builds on the backend abstraction
- Provider API → Delivery Backends: implements · Concrete adapters provide email, SMS, Twilio, AWS, and YubiKey delivery
- Delivery Backends → Email Templates: renders · Email backend uses templates for code messages
- Settings → Config Query: resolves · Configured backend names are looked up at runtime
- Config Query → Provider API: selects · Configuration lookup chooses a backend/provider implementation
- Admin → MFA Models: manages · Admin UI exposes the MFA domain model
- Test URLs → Token URLs: integrates · Test project wires the package into a host URL config
- Test URLs → JWT URLs: integrates · Test project exercises JWT endpoint wiring
- Test Serializers → Serializers: mirrors · Host serializers validate integration contracts
- Test Models → MFA Models: extends · Test project models demonstrate host-side storage patterns
