Skip to main content

dj-auth

A reusable Django app providing production-ready authentication out of the box:

  • Email login — email/password auth via django-allauth, no username required
  • Passkeys — WebAuthn/FIDO2 passkey login (biometrics, hardware keys)
  • TOTP / 2FA — authenticator app support with recovery codes
  • Social auth — Google and GitHub OAuth preconfigured, others easy to add
  • Polished UI — Tailwind CSS templates for login, signup, MFA settings, and more
  • Zero models — no migrations; drop it into any project without touching your schema
  • Typed — ships a py.typed marker, so your mypy sees real signatures rather than Any
  • Internal API — optional node-to-node user lookup for multi-node projects, with a route restriction that keeps it off the public internet
  • System checks — warns you at startup if required dependencies are misconfigured

Quick Start

1. Install

# From PyPI (published as "ybz-dj-auth"; the importable package is still dj_auth)
pip install ybz-dj-auth

# Or install directly from GitHub:

# Latest commit on main
pip install git+https://github.com/damycra/dj-auth.git

# Specific tagged release (recommended for reproducible builds)
pip install git+https://github.com/damycra/dj-auth.git@v0.1.0

# Or download the wheel from a GitHub Release and install locally
pip install ybz_dj_auth-0.2.1-py3-none-any.whl

2. Add to INSTALLED_APPS

Important: dj_auth must appear before allauth and all allauth.* entries. Django's template loader searches apps in order — if allauth comes first, its own unstyled built-in templates shadow dj_auth's styled overrides. manage.py check will warn you (dj_auth.W004) if the ordering is wrong.

INSTALLED_APPS = [
    # ... Django built-ins ...
    "django.contrib.sites",       # required by allauth

    "dj_auth",                    # must come before allauth

    "allauth",
    "allauth.account",
    "allauth.socialaccount",      # optional: social login
    "allauth.mfa",                # optional: MFA / passkeys

    # ... your apps ...
]

allauth.socialaccount and allauth.mfa are genuinely optional: the login and signup pages detect whether they are installed and simply omit the social-login buttons / passkey button when they're not. manage.py check emits a warning (dj_auth.W001 / dj_auth.W002) so you know the feature is unavailable.

3. Configure MIDDLEWARE

Add AccountMiddleware after SessionMiddleware:

MIDDLEWARE = [
    ...
    "django.contrib.sessions.middleware.SessionMiddleware",
    ...
    "allauth.account.middleware.AccountMiddleware",
]

4. Configure AUTHENTICATION_BACKENDS

AUTHENTICATION_BACKENDS = [
    "django.contrib.auth.backends.ModelBackend",           # keep for admin
    "allauth.account.auth_backends.AuthenticationBackend", # required by allauth
]

5. Include URLs

# config/urls.py
from django.urls import include, path

urlpatterns = [
    path("accounts/", include("dj_auth.urls")),
    # ... your other URLs ...
]

6. Run migrations

python manage.py migrate

That's it. Visit /accounts/login/ to see the login page.

Configuration

dj_auth injects sensible defaults on startup via AppConfig.ready(). These are standard allauth and Django settings — no special DJ_AUTH_* namespace. Override any of them in your project's settings.py using the normal allauth setting names.

Setting Default Description
ACCOUNT_LOGIN_METHODS {"email"} Login with email only (no username)
ACCOUNT_SIGNUP_FIELDS ["email*", "password1*", "password2*"] Signup form fields
ACCOUNT_EMAIL_VERIFICATION "optional" "mandatory", "optional", or "none"
LOGIN_REDIRECT_URL "/" Where to go after login
LOGOUT_REDIRECT_URL "/" Where to go after logout
MFA_SUPPORTED_TYPES ["totp", "recovery_codes", "webauthn"] Enabled MFA methods
MFA_PASSKEY_LOGIN_ENABLED True Show passkey login button
MFA_PASSKEY_SIGNUP_ENABLED False Allow passkey signup (requires mandatory email verification)
MFA_WEBAUTHN_ALLOW_INSECURE_ORIGIN True Allow HTTP in development — set to False in production
SOCIALACCOUNT_PROVIDERS {} Social provider credentials (see below)
SITE_ID 1 Django sites framework site ID

Template Overriding

dj_auth ships templates inside the package (dj_auth/templates/). Django's template loader checks project-level DIRS first, so you can override any template by placing a file at the same path in your project's template directory.

Overriding base.html

The main layout is base.html. Key blocks:

Block Required Purpose
content yes Main page content — all auth pages render here
head_title no Page <title> text
extra_head no Additional <head> content (CSS links, meta tags)
nav no Entire navigation bar
nav_logo_href no Logo link href (default: /)
nav_logo_content no Logo icon + site name HTML
nav_links no Right-side nav items
footer no Page footer
extra_body no Scripts before </body>

To customise the layout, create templates/base.html in your project (which takes priority over the package's version via Django's DIRS setting). You can start from scratch or copy dj_auth/templates/base.html from the package as a starting point. Do not use {% extends "base.html" %} in your override — that's circular.

Example — minimal base.html keeping dj_auth's Tailwind styles but adding your own nav:

{# myproject/templates/base.html #}
<!DOCTYPE html>
<html lang="en">
<head>
  <title>{% block head_title %}My App{% endblock %}</title>
  <script src="https://cdn.tailwindcss.com"></script>
  {% block extra_head %}{% endblock %}
</head>
<body>
  <nav><!-- your nav here --></nav>
  <main>{% block content %}{% endblock %}</main>
  {% block extra_body %}{% endblock %}
</body>
</html>

Overriding allauth's internal pages

allauth's built-in pages (TOTP setup, WebAuthn management, etc.) extend allauth/layouts/base.html. To make them match your project's branding:

{# myproject/templates/allauth/layouts/base.html #}
{% extends "base.html" %}

Tailwind CSS

Templates use the Tailwind CSS CDN for zero-configuration development. For production:

  1. Install Tailwind: npm install -D tailwindcss
  2. Configure content paths in tailwind.config.js:
    content: [
      "./templates/**/*.html",
      // Include dj_auth's package templates:
      "<path-to-venv>/lib/python3.x/site-packages/dj_auth/templates/**/*.html",
    ]
    
  3. Compile: npx tailwindcss -o static/css/main.css --minify
  4. Override extra_head in your base.html:
    {% block extra_head %}
    <link rel="stylesheet" href="{% static 'css/main.css' %}">
    {% endblock %}
    

Social Providers

Login/signup buttons are rendered only for providers that are actually usable: a provider whose APP has an empty client_id (e.g. credentials left blank in your .env) is hidden automatically, so you can keep provider apps in INSTALLED_APPS and placeholder config in settings without showing dead buttons. The buttons live in account/snippets/social_buttons.html, which you can override like any other template.

Google

SOCIALACCOUNT_PROVIDERS = {
    "google": {
        "APP": {
            "client_id": "your-client-id",
            "secret": "your-client-secret",
            "key": "",
        },
        "SCOPE": ["profile", "email"],
        "AUTH_PARAMS": {"access_type": "online"},
    },
}

Add "allauth.socialaccount.providers.google" to INSTALLED_APPS.

GitHub

SOCIALACCOUNT_PROVIDERS = {
    "github": {
        "APP": {
            "client_id": "your-client-id",
            "secret": "your-client-secret",
            "key": "",
        },
        "SCOPE": ["user:email"],
    },
}

Add "allauth.socialaccount.providers.github" to INSTALLED_APPS.

For other providers, see the django-allauth documentation.

MFA / Passkeys

MFA is enabled by default when allauth.mfa is in INSTALLED_APPS. Users manage their security settings at /accounts/2fa/.

Passkey login

Passkeys are enabled by default (MFA_PASSKEY_LOGIN_ENABLED = True). The login page shows a "Sign in with a passkey" button automatically.

Passkey signup

Disabled by default because it requires mandatory email verification:

ACCOUNT_EMAIL_VERIFICATION = "mandatory"
MFA_PASSKEY_SIGNUP_ENABLED = True

Production WebAuthn

For production (HTTPS), remove the insecure origin allowance:

MFA_WEBAUTHN_ALLOW_INSECURE_ORIGIN = False

Internal node-to-node API

Optional, and off unless configured. A single-node project can ignore this entire section.

Once a project splits across more than one node — one holding auth_user, others holding tenant data — the other nodes need to ask the first one about users. dj_auth.internal provides that: one endpoint, its client, and the machinery to keep both off the public internet.

The endpoint

# urls.py — explicitly, and NOT under accounts/
urlpatterns = [
    path("accounts/", include("dj_auth.urls")),
    path("", include("dj_auth.internal.urls")),   # serves /internal/users/
]
# settings.py, on the node that holds auth_user
DJ_AUTH_INTERNAL_API_TOKENS = [os.environ["INTERNAL_API_TOKEN"]]

Including the URLs with no token raises ImproperlyConfigured at startup rather than serving user data behind nothing. The way to not have an internal API is to not include the URLs.

GET /internal/users/?email=… or ?ids=1,2,3 returns {"users": [{"id", "email", "full_name"}]}. full_name is get_full_name(), which under this package's email-only signup defaults is usually empty — treat it as optional.

The client, on the other nodes

DJ_AUTH_INTERNAL_ORIGIN = "http://auth.internal:9000"
DJ_AUTH_INTERNAL_API_TOKENS = [os.environ["INTERNAL_API_TOKEN"]]
from dj_auth.internal.client import find_user_by_email, get_users_by_ids, AuthNodeUnavailable

try:
    user = find_user_by_email("someone@example.com")   # InternalUser | None
    users = get_users_by_ids([1, 2, 3])                # list[InternalUser]
except AuthNodeUnavailable:
    ...   # network error, timeout, non-2xx, or invalid JSON

call_auth_node(path, method=..., payload=...) is exported too, so a project's own node-to-node calls get the same origin, token and error handling without reimplementing them.

Tokens are a list so rotation is two deploys rather than one synchronised one: add the new token everywhere, then remove the old. A caller presents the first; the server accepts any. Comparison is constant-time.

Keeping it off the public internet

This is the part most likely to be got wrong, so it is worth reading even if the rest looked obvious. Add the middleware first:

MIDDLEWARE = [
    "dj_auth.internal.middleware.InternalRouteMiddleware",
    ...
]

It answers 404 — not 403 — to anything under /internal/ that did not arrive by the internal route, and it does so before the token is examined, so nothing about token state is observable from the wrong route. There are two independent checks, and neither is sufficient in every environment:

Setting Use it when Boundary or backstop
DJ_AUTH_INTERNAL_PORT The internal port is genuinely unpublished — e.g. a Docker Compose port absent from ports: The boundary there
DJ_AUTH_INTERNAL_CLIENT_NETWORKS The internal port is published on a public address — the normal case behind a platform proxy The boundary there

Configuring both is usually right. Bind the app to a second port and point the internal origin at it:

gunicorn ... --bind :8000 --bind :9000
DJ_AUTH_INTERNAL_PORT = "9000"                       # from SERVER_PORT, unforgeable
DJ_AUTH_INTERNAL_CLIENT_NETWORKS = ["10.0.0.0/8"]    # CIDRs callers must come from
DJ_AUTH_INTERNAL_CLIENT_IP_HEADER = ""               # empty = use REMOTE_ADDR

DJ_AUTH_INTERNAL_CLIENT_IP_HEADER names a header to trust for the client address, needed when a proxy sits in the path and REMOTE_ADDR is therefore the proxy. Set it only where a proxy always overwrites that header. On an app reachable without that proxy in front, a trusted header is client-supplied input — which is exactly why a Host allowlist is not used here. An absent or unparseable address fails closed.

Fly.io: the port check is not a boundary

Worth stating plainly, because it is counter-intuitive and it fails silently.

To reach a second port over Flycast — which is what lets private traffic wake a suspended machine — you add a [[services]] block for it. But Fly publishes a service's ports on every address the app holds, and its own documentation is explicit:

If you have public IP addresses assigned to your app, then services in fly.toml are exposed to the public internet.

There is no per-service private-only flag. So the block that makes port 9000 reachable privately makes it reachable publicly, and such a request passes the port check by construction — it really did arrive on the internal port. Meanwhile /internal/ on 443 returns a tidy 404, so it all looks like it is working.

On Fly, use the client-network check:

[env]
  DJ_AUTH_INTERNAL_PORT = '9000'                       # still worth setting; defence in depth
  DJ_AUTH_INTERNAL_CLIENT_NETWORKS = 'fdaa::/16'       # Fly's 6PN range: private, never public
  DJ_AUTH_INTERNAL_CLIENT_IP_HEADER = 'Fly-Client-IP'  # the proxy overwrites this; verified

fdaa::/16 covers every 6PN address and nothing public. Fly-Client-IP is safe to trust here specifically because Fly Proxy overwrites whatever a client sends — confirmed against a live deploy, with forged values including an unparseable one, all discarded.

System checks

manage.py check catches the configurations that otherwise fail quietly:

ID Meaning
dj_auth.E006 Internal API enabled with no route restriction while DEBUG=False
dj_auth.E007 A restriction is configured but the middleware is missing, so nothing enforces it
dj_auth.W005 CLIENT_IP_HEADER set with no CLIENT_NETWORKS, so the header is read by nothing
dj_auth.W006 Tokens that look like placeholders, or are under 32 characters, while DEBUG=False

Running the Example App

cd examples/basic
pip install -e ../../        # install dj-auth from source
pip install -r requirements.txt
cp .env.example .env         # edit as needed
python manage.py migrate
python manage.py createsuperuser
python manage.py runserver

Visit http://localhost:8000 to see the example app.

Running the Test Suite

pip install -e ".[dev]"
pytest

Or with tox (tests against multiple Django versions):

tox

To run just the lint checks:

tox -e lint
# or
ruff check dj_auth tests

Metadata

Release files for ybz-dj-auth 0.3.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for ybz-dj-auth 0.3.1
File Size Uploaded Provenance Actions
ybz_dj_auth-0.3.1.tar.gz 69.1 kB With provenance Details for ybz_dj_auth-0.3.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for ybz-dj-auth 0.3.1
File Interpreter ABI Platform Actions
ybz_dj_auth-0.3.1-py3-none-any.whl Python 3 none any Details for ybz_dj_auth-0.3.1-py3-none-any.whl

Total release size: 120.9 kB

Release files / ybz_dj_auth-0.3.1.tar.gz

Download URL ybz_dj_auth-0.3.1.tar.gz
Size 69.1 kB
Tags Source
SHA-256 checksum
How to use checksums
c5cd81056f5faceccf5880d630071edb99776a505b69086121d24cbe13fba115
BLAKE2b-256 checksum
How to use checksums
da297954009d15f2280745ee401967c2a726bb385873c2788da6326b66476b3e
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Sep 7, 2026.

Transparency log

Release files / ybz_dj_auth-0.3.1-py3-none-any.whl

Download URL ybz_dj_auth-0.3.1-py3-none-any.whl
Size 51.8 kB
Tags Python 3
SHA-256 checksum
How to use checksums
5dc393fd3a3717bc7f25b0b885ee0fba31c05cffefcf969fa6ca751b6f3940e2
BLAKE2b-256 checksum
How to use checksums
75ccb5f45e6c270965639ad1ae784381298084252852a8c10b4f8c95b49a4a92
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Sep 7, 2026.

Transparency log

Security for ybz-dj-auth 0.3.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for ybz_dj_auth-0.3.1.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Sep 7, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page