ContentsClose contents
Pre-release
Chapter 27 · Authentication and account workflows: members sign up and sign inCHAPTER 27

Complete six-part pre-release for review. Password change, reset, and two-factor sign-in are Chapter 29; real email delivery and required confirmation are Chapter 43. Live Google and GitHub sign-in needs your own OAuth apps; the tests stand in for it. One migration and two pinned packages are added.

Working towards: First release (Chapter 34). One community runs free events. Members sign up, register, see, and cancel their registrations; organizers publish their own events; two people cannot both take the last place. Tests check each product rule. All milestones

CHAPTER TWENTY-SEVEN

Authentication and account workflows: members sign up and sign in

Stage 4: Accounts and first release (Chapters 24 to 34)

Prerequisites: Chapters 15 to 26, including the Chapter 26 project, its 165 passing tests, and the custom user model from Chapter 17 with Chapter 21’s lower-case email rule

What you’ll build: Sign-up, sign-in, and sign-out pages for members, built with django-allauth around Otahque’s email-only user; a sign-up that asks for a display name and an optional time zone and refuses invalid and disposable addresses; a profile page each member can change only for themselves; sign-in with Google and GitHub that never links accounts by email alone; “Organized by” on event pages; and a written design of the sign-in flow

Why This Matters

Until now, only the administrator could sign in, and only on the admin’s own page. Sam reached the New event page by signing in there, as a staff member. Sai, Raj, and Soni could not sign in at all, and the event pages sent every visitor to a page meant for staff.

A community needs its members to sign up and sign in on its own pages. That sounds like a form and a password check, and it is far more. Passwords must be stored as hashes, never as text. The address a person types must be a real one, and not a temporary inbox that disappears in ten minutes. Two people must not end up with the same email in two letter cases. Someone who signs in with GitHub must not be handed another person’s account because the email matched. Signing in must give the browser a fresh session, and signing out must be a deliberate action, not a link a crawler can follow. Many projects get one of these wrong.

So this chapter does not write account pages from nothing. It adds django-allauth, a widely used Django package for accounts, decided for Otahque on 13 November 2026, and fits it to what Otahque already has: the email-only user from Chapter 17, Chapter 21’s lower-case rule, and the pages and tests of Chapters 24 to 26. Where the community has its own rules, such as asking for a display name and refusing disposable addresses, Otahque adds a small piece of its own code at the place allauth provides for it.

By the end of the chapter, you will be able to:

  • explain what authentication is, and what signing in changes in the session;
  • add a third-party package with a pinned version, configure it for a custom user, and record the decision in an ADR;
  • ask for extra details at sign-up, and refuse addresses that are invalid, already used, or disposable;
  • build a page that only ever changes the signed-in member’s own data, and prove it with tests;
  • add sign-in with Google and GitHub without trusting an email address alone, and test it without a network;
  • show the organizers’ names on event pages, now that members choose them.

Sessions and messages in depth are Chapter 28, which also shows each member event times in their own time zone. Changing and resetting a password, and two-factor sign-in, are Chapter 29. Roles are Chapter 30. Real email delivery, after which confirming an address becomes required, is Chapter 43. A profile image arrives with file uploads in Chapter 42.

PAGE 001

What You Need to Know

Authentication, and what a session remembers

Authentication answers “who is this?”, and authorization, which Chapters 24 to 26 used, answers “may they do this?”. Signing in is authentication: the person proves who they are, usually with a password, and Django records the answer in the session, the small store on the server that Chapter 28 explores. The browser keeps only a cookie with the session’s key.

Two details matter for safety. When a person signs in, Django gives the session a new key, so a key someone saw before sign-in is useless afterwards; this chapter’s tests observe it. And signing out is a POST: Django’s documentation says its LogoutView “Logs a user out on POST requests”, and allauth’s sign-out page only asks when it is opened with a GET. That is Chapter 26’s rule about links and forms, applied to accounts.

Four numbered cards down the left joined by arrows, and two boxes on the right. 1, a blue Sign up card: email, display name, time zone (optional), password twice. 2, a purple Checks card: a valid address, not disposable, not already used, and Django’s password rules. 3, a green Saved card: the user in lower case, a profile with the zone, and an unconfirmed email address. 4, a green Signed in card: a new session key, and the member lands on their own profile. A blue box, Or a provider, says Google or GitHub confirms the email and the same sign-up form asks the name first, with an arrow to the Sign up card. A grey box, Sign out, says it is a POST from the button in the navigation, and a GET only asks.
Figure 27.1 — A member’s account journey in this chapter.

Why a package, and why this one

New Tool: django-allauth

What problem exists? Sign-up, sign-in, sign-out, email confirmation, limits on repeated failed sign-ins, and sign-in through other services are each easy to start and hard to finish safely.

What did people do before? They wrote each page with Django’s own views and forms, as The Custom Way below starts to, and added a separate package for each provider.

What is it? django-allauth is a Django package that provides all of these pages and rules, for both ordinary accounts and accounts at other services, with settings for what to ask and how to behave.

Why use it? One maintained package covers this chapter, the provider sign-in, and Chapter 29’s two-factor sign-in, and it works with a custom user model. It is a dependency, so it is pinned to an exact version and recorded in an ADR.

Now let’s use it. Step 3 adds it with uv add, configures it for Otahque’s email-only user, and runs its migrations.

Table 27.1 shows who checks what once it is in place. Otahque’s own code is small, and it sits only where the community’s rules differ from allauth’s defaults.

Three tall boxes and one banner. A purple allauth box: sign-up and sign-in pages, email confirmation, rate limits, providers, and sign-out by POST. A purple Django box: password hashing and rules, sessions and a new key at sign-in, CSRF, and login_required. An orange box, Otahque’s own code: display name and time zone at sign-up, disposable addresses refused, the profile page, and who organizes what. A green banner below says the database still refuses an upper-case email and a second account with the same address, from Chapter 21.
Figure 27.2 — Who checks what in Otahque’s accounts.
Table 27.1 — Where each account rule lives
Rule Where
Sign-up and sign-in pages, confirmation email, failed sign-in limits allauth, configured in settings.py
Passwords hashed and checked against the password rules Django
Email stored in lower case, one account per address Chapter 21's model rule and database constraint
Display name required, time zone asked Otahque's SignupForm
Disposable addresses refused Otahque's AccountAdapter
Only your own profile can be changed Otahque's profile view, which reads no id
Providers only from .env; no linking by email alone settings.py and allauth's rule

A custom user, and email-only sign-in

Chapter 17 built accounts.User without a username: members sign in with their email. allauth’s documentation describes exactly this case. Three settings say it: there is no username field, the login method is the email, and sign-up asks for the email and the password twice. Otahque keeps everything else Chapter 17 and 21 decided, and allauth works with it: the email is still lower-cased on save, and the database still refuses a second account for the same address.

Extra details at sign-up, and a profile

Members choose a display name, shown on the pages of events they organize, and may give a time zone, which Chapter 28 will use to show them event times. The display name already lives on User. The time zone goes on a new model, Profile, one row per member, linked one-to-one. allauth asks for extra fields through a small form you name in settings: its signup() method runs once the account exists, and saves the extra details.

A profile row is made the first time it is needed, by Profile.of(user). That one path covers every way a member can arrive: the sign-up page, a provider, createsuperuser, and the members created in earlier chapters.

New Concept: a page that cannot reach anyone else

What problem exists? A profile page at /members/7/edit/ invites someone to try /members/8/edit/. Every such page needs an ownership check, and one forgotten check exposes every account.

What did people do before? They put the member’s id in the address and checked it on every request.

What is it? The profile page reads no id at all. It edits request.user, the member Django signed in, so there is no other member it could reach.

Why use it? The safest check is the one that cannot be forgotten, because there is nothing to check.

Now let’s use it. Step 5 builds /accounts/profile/ this way, and its tests send crafted fields that change nothing.

Real addresses only

Django’s email field already refuses text that is not an address. A disposable address is different: a working inbox from a service such as Mailinator, used for minutes and then abandoned, often to sign up many times. Otahque refuses them at sign-up. The list of such domains is long and changes daily, so Otahque uses a maintained one, the disposable-email-domains package, which holds about ten thousand domains in a plain Python set. allauth provides a place for the check: its adapter, a class whose methods allauth calls at fixed moments, and whose clean_email() method sees every address at sign-up. A setting lists any domain the community chooses to accept anyway.

Sign-in with Google and GitHub, and linking accounts

Many members already have a Google or GitHub account. With a provider, the person signs in at Google or GitHub, which tells Otahque, through a standard called OAuth, that this person controls a confirmed email address. Figure 27.4, in Step 9, shows the steps.

One rule matters more than the rest. A provider vouches for an email address, not for an Otahque account. If an account already exists for that address, Otahque does not join the two on its own: someone could have signed up with that address and never confirmed it, and the provider’s word does not prove who controls the Otahque account. So the page says the address already has an account and asks the person to sign in to it first; signed in, they connect the provider from Connected accounts. Figure 27.3 shows the two outcomes.

Two boxes on the left and two on the right. A blue box, GitHub says: this person owns sam@example.org. A green box, Otahque has: an account for sam@example.org, made with a password. An arrow from GitHub says leads to a red box, Not linked: the page says the address already has an account and asks the person to sign in to it first. An arrow from Otahque has leads to a green box, Linked: signed in with the password, the member connects GitHub from Connected accounts. A grey note says why: an email alone does not prove who controls the Otahque account.
Figure 27.3 — Linking a provider to an existing account, safely.

Provider credentials are secrets, like Chapter 8’s secret key, so they live in .env, never in Git and never in the database. allauth’s documentation says that setting them up in the admin “effectively stores secrets in your database”. In tests, nothing talks to Google: the tests build the provider’s answer themselves, so they run offline and the same way every time.

Try it yourself

Que. 1 Raj signs up as Raj@Example.org, then tries to sign up again as raj@example.org. What happens the second time, and which rule from an earlier chapter is at work?

Flip to check your answerFold answer back

Answer. The second sign-up is refused, because the address is already used. Chapter 21 stores every email in lower case and the database allows one account per address, so both spellings are the same address. allauth checks this before saving and shows the message beside Email.

Que. 2 A profile page lives at /accounts/profile/ and takes no number in the address. Sai is signed in. How could she change Raj’s display name through it?

Flip to check your answerFold answer back

Answer. She cannot. The page changes request.user, which is Sai. There is no id to change and no field that names another member, and the tests in Step 5 send crafted fields such as email, is_staff, and user to prove that they change nothing.

PAGE 002

How We Build It

Start from Chapter 26, in the folder containing manage.py, with your own .env, the locked environment, 165 passing tests, every migration applied, the Node.js packages from Chapter 14, and Sam’s superuser password from Chapter 18. Step 3 downloads packages, so you need an internet connection once. The new files are accounts/forms.py, accounts/adapter.py, accounts/urls.py, accounts/templates/accounts/profile.html, accounts/migrations/0003_profile.py, four templates under templates/allauth/, docs/adr/ADR-003-accounts-allauth.md, and docs/design/sign-in.md. The commands are written the same for Windows PowerShell, Git Bash, macOS, Linux, and WSL; the chapter’s checks ran in the first two. Each step with new behaviour writes its tests first and runs them to see them fail.

The Custom Way

Django has its own sign-in and sign-out views, and a sign-in page takes three lines of URL configuration. This illustration is not part of the project:

from django.contrib.auth import views as auth_views
from django.urls import path

urlpatterns = [
    path('login/', auth_views.LoginView.as_view(),
         name='login'),
    path('logout/', auth_views.LogoutView.as_view(),
         name='logout'),
]

That much works, and R3’s Django for Beginners builds its sign-up the same way, with a form based on Django’s UserCreationForm. Then the list grows: a sign-up form for the custom user, a confirmation email and its link, limits on failed sign-ins, email addresses a member can change, providers, and later two-factor sign-in. Each is a new view, form, template, and set of tests, and each is a new chance to get a security detail wrong. The Django Way for this chapter is a maintained package that already does them, configured for Otahque’s rules.

The Django Way

Step 1: Check the starting point

uv run python manage.py test
Found 165 test(s).
Creating test database for alias 'default'...
...
Ran 165 tests in ...s

OK
Destroying test database for alias 'default'...
git status --short
git log --oneline -1
... Publish, cancel, delete, and copy events

Step 2: The journey on paper

Before any code, follow Figure 27.1 with the four people. Sai signs up with her email and a password, gives the name Sai and her time zone, and lands on her profile. Raj tries a Mailinator address and is refused. Soni signs in with Google, and the sign-up form still asks for her name. Sam already has an account with a password, and his GitHub account uses the same address: Otahque asks him to sign in first, and then he connects GitHub from his profile. Each sentence becomes a test in the steps below.

Step 3: Add django-allauth

Add the two packages, pinned to exact versions. The [socialaccount] part asks for allauth’s optional pieces for providers, which bring a few more packages, such as requests and cryptography:

uv add "django-allauth[socialaccount]==65.22.1"
uv add "disposable-email-domains==0.0.295"
Resolved 17 packages in ...
Installed 11 packages in ...
 + certifi==2026.10.23
 + cffi==2.1.1
 + charset-normalizer==3.5.2
 + cryptography==50.0.2
 + django-allauth==65.22.1
 + idna==3.20
 + oauthlib==4.0.1
 + pycparser==3.12
 + pyjwt==2.15.1
 + requests==2.34.2
 + urllib3==2.8.0
Resolved 18 packages in ...
Installed 1 package in ...
 + disposable-email-domains==0.0.295

uv add writes each pin into pyproject.toml and every resolved version into uv.lock. Now tell Django about allauth. In config/settings.py, add allauth’s apps at the end of INSTALLED_APPS:

    'registrations.apps.RegistrationsConfig',
    'allauth',
    'allauth.account',
    'allauth.socialaccount',
    'allauth.socialaccount.providers.google',
    'allauth.socialaccount.providers.github',
]

Add allauth’s middleware at the end of MIDDLEWARE. It keeps track of the request for allauth’s own code:

    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'allauth.account.middleware.AccountMiddleware',
]

And add this block at the end of settings.py. The backends let Django check a password through allauth as well as its own way. The next three settings describe Otahque’s user: no username, sign-in by email, and a sign-up form with the email and the password twice. The last says that confirming an address is optional for now:

# Accounts: django-allauth, with Otahque's email-only User.
# See docs/adr/ADR-003-accounts-allauth.md.

AUTHENTICATION_BACKENDS = [
    'django.contrib.auth.backends.ModelBackend',
    'allauth.account.auth_backends.AuthenticationBackend',
]
ACCOUNT_USER_MODEL_USERNAME_FIELD = None
ACCOUNT_LOGIN_METHODS = {'email'}
ACCOUNT_SIGNUP_FIELDS = [
    'email*', 'password1*', 'password2*',
]
ACCOUNT_EMAIL_VERIFICATION = 'optional'

Give allauth its addresses: in config/urls.py, put allauth’s URLs before the events URLs:

    path('accounts/', include('allauth.urls')),
    path('', include('events.urls')),

allauth brings its own tables, for email addresses and provider accounts. Create them (the output below is shortened with ...; nine account and six socialaccount migrations are applied):

uv run python manage.py migrate
Operations to perform:
  Apply all migrations: account, accounts, admin, auth,
    contenttypes, events, registrations, sessions,
    socialaccount
Running migrations:
  Applying account.0001_initial... OK
  Applying account.0002_email_max_length... OK
  ...
  Applying socialaccount.0001_initial... OK
  ...
  Applying
    socialaccount.0006_alter_socialaccount_extra_data... OK
uv run python manage.py check
System check identified no issues (0 silenced).

Every earlier test still passes, because nothing visible has changed yet. Open http://127.0.0.1:8000/accounts/login/ in the development server: allauth’s sign-in page is there, plain for now.

Common Error: an email setting from older tutorials

Many tutorials tell you to set EMAIL_BACKEND for allauth’s emails. Django 6.1 configures email with MAILERS, which Otahque has had since Chapter 6, and adding EMAIL_BACKEND beside it stops every command with ImproperlyConfigured: Deprecated email settings are not allowed when MAILERS is defined. Leave MAILERS as it is: allauth’s confirmation emails already appear in the terminal.

Common Error: provider apps without their extra

Installing django-allauth without [socialaccount] and then listing the Google provider stops with ModuleNotFoundError: No module named 'requests'. The providers need the optional packages. Run the uv add command above, with the extra.

Step 4: The members’ sign-in page

Chapter 24 sent people to the admin’s sign-in page, with LOGIN_URL = 'admin:login', and three tests check that address. They change in place first: in events/tests.py, replace each reverse('admin:login') with reverse('account_login'), the name allauth gives its sign-in page. There are three. Run the tests whose names mention a visitor:

uv run python manage.py test events -k visitor
Found 5 test(s).
Creating test database for alias 'default'...
...
Ran 5 tests in ...s

FAILED (failures=3)
Destroying test database for alias 'default'...

In config/settings.py, replace the three LOGIN_URL lines from Chapter 24:

# Pages for signed-in people send everyone else to the
# members' sign-in page.
LOGIN_URL = 'account_login'
uv run python manage.py test events -k visitor
Found 5 test(s).
Creating test database for alias 'default'...
...
Ran 5 tests in ...s

OK
Destroying test database for alias 'default'...

Step 5: The profile, and signing in and out

Signing in will land members on /accounts/profile/, so the profile comes next. The tests use allauth’s and Django’s test tools, so replace the imports at the top of accounts/tests.py:

from allauth.account.models import EmailAddress
from allauth.core.context import request_context
from allauth.socialaccount.adapter import (
    get_adapter as get_social_adapter,
)
from allauth.socialaccount.helpers import (
    complete_social_login,
)
from allauth.socialaccount.models import (
    SocialAccount, SocialLogin,
)
from django.contrib.auth import get_user_model
from django.contrib.auth.models import AnonymousUser
from django.contrib.messages.storage.fallback import (
    FallbackStorage,
)
from django.contrib.sessions.backends.db import SessionStore
from django.core import mail
from django.core.exceptions import ValidationError
from django.db import IntegrityError
from django.test import (
    Client, RequestFactory, SimpleTestCase, TestCase,
    override_settings,
)
from django.urls import reverse

from events.tests import admin_url
from .models import Profile, User

Add the profile tests at the end of the file:

PASSWORD = 'a-long-safe-pass-123'


class ProfileTests(TestCase):
    """The profile page: your own name and time zone."""

    url = '/accounts/profile/'

    @classmethod
    def setUpTestData(cls):
        cls.sai = User.objects.create_user(
            'sai@example.org', PASSWORD, display_name='Sai'
        )

    def test_a_visitor_is_sent_to_sign_in(self):
        response = self.client.get(self.url)
        sign_in = reverse('account_login')
        self.assertRedirects(
            response, f'{sign_in}?next={self.url}',
            fetch_redirect_response=False,
        )

    def test_a_profile_is_made_the_first_time(self):
        self.assertFalse(Profile.objects.exists())
        self.client.force_login(self.sai)
        response = self.client.get(self.url)
        self.assertContains(response, 'value="Sai"')
        made = Profile.objects.get()
        self.assertEqual(made.user, self.sai)

    def test_name_and_zone_are_saved(self):
        self.client.force_login(self.sai)
        response = self.client.post(self.url, {
            'display_name': 'Sai K',
            'timezone': 'Europe/London',
        })
        self.assertRedirects(response, self.url,
                             fetch_redirect_response=False)
        self.sai.refresh_from_db()
        self.assertEqual(self.sai.display_name, 'Sai K')
        self.assertEqual(self.sai.profile.timezone,
                         'Europe/London')

    def test_an_unknown_zone_is_refused(self):
        self.client.force_login(self.sai)
        response = self.client.post(self.url, {
            'display_name': 'Sai', 'timezone': 'Mars/Base',
        })
        self.assertEqual(response.status_code, 200)
        self.assertFalse(Profile.objects.filter(
            timezone='Mars/Base').exists())

    def test_crafted_fields_change_nothing(self):
        self.client.force_login(self.sai)
        self.client.post(self.url, {
            'display_name': 'Sai', 'timezone': '',
            'email': 'boss@example.org', 'is_staff': 'on',
            'user': '999',
        })
        self.sai.refresh_from_db()
        self.assertEqual(self.sai.email, 'sai@example.org')
        self.assertFalse(self.sai.is_staff)

    def test_profile_csrf_is_checked(self):
        browser = Client(enforce_csrf_checks=True)
        browser.force_login(self.sai)
        data = {'display_name': 'Forged', 'timezone': ''}
        refused = browser.post(self.url, data)
        self.assertEqual(refused.status_code, 403)
        page = browser.get(self.url)
        token = str(page.context['csrf_token'])
        sent = browser.post(
            self.url, data | {'csrfmiddlewaretoken': token}
        )
        self.assertEqual(sent.status_code, 302)
uv run python manage.py test accounts.tests.ProfileTests
Found 1 test(s).
Creating test database for alias 'default'...
...
ImportError: Failed to import test module: tests
Ran 1 test in ...s

FAILED (errors=1)
Destroying test database for alias 'default'...

The whole module fails to load, because Profile does not exist yet. Add the model. In accounts/models.py, the imports become:

from django.conf import settings
from django.contrib.auth.models import (
    AbstractBaseUser,
    PermissionsMixin,
)
from django.db import models
from django.db.models.functions import Lower
from django.utils import timezone

from events.models import validate_timezone_name

from .managers import UserManager

Add the model at the end of the file:

class Profile(models.Model):
    """A member's own settings, one row per member."""

    user = models.OneToOneField(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        related_name='profile',
    )
    timezone = models.CharField(
        max_length=64, blank=True,
        validators=[validate_timezone_name],
        help_text='Blank means not set.',
    )

    def __str__(self):
        return f'Profile of {self.user}'

    @classmethod
    def of(cls, user):
        """Return the member's profile, making it if new."""
        return cls.objects.get_or_create(user=user)[0]

OneToOneField is a foreign key that allows one profile per user, and related_name='profile' lets you write user.profile. on_delete=models.CASCADE deletes the profile with its member, because a profile means nothing alone. The time zone reuses Chapter 21’s validator, and blank means “not set”. Profile.of() returns the member’s profile and makes it the first time.

uv run python manage.py makemigrations accounts -n profile
Migrations for 'accounts':
  accounts\migrations\0003_profile.py
    + Create model Profile

Apply it with uv run python manage.py migrate. Now the form, in a new file, accounts/forms.py. It reuses the list of time zones from Chapter 24’s event form:

"""The accounts app's forms."""
from django import forms

from events.forms import ZONE_CHOICES

from .models import Profile

NAME_HELP = ('Shown to other members, and on the pages of '
             'events you organize.')


class ProfileForm(forms.Form):
    """The signed-in member's own name and time zone."""

    display_name = forms.CharField(
        max_length=100, help_text=NAME_HELP,
    )
    timezone = forms.ChoiceField(
        choices=ZONE_CHOICES, required=False,
        label='Time zone (optional)',
    )

    def save(self, user):
        """Save the name to the user, the zone to Profile."""
        user.display_name = self.cleaned_data['display_name']
        user.save(update_fields=['display_name'])
        profile = Profile.of(user)
        profile.timezone = self.cleaned_data['timezone']
        profile.full_clean()
        profile.save()

The view is in accounts/views.py. It reads no id; request.user is the member:

"""The accounts app's own views; allauth has the rest."""
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.shortcuts import redirect, render

from .forms import ProfileForm
from .models import Profile


@login_required
def profile(request):
    """Show the signed-in member's profile; no id is read."""
    user = request.user
    if request.method == 'POST':
        form = ProfileForm(request.POST)
        if form.is_valid():
            form.save(user)
            messages.success(request, 'Profile saved.')
            return redirect('accounts:profile')
    else:
        form = ProfileForm(initial={
            'display_name': user.display_name,
            'timezone': Profile.of(user).timezone,
        })
    return render(request, 'accounts/profile.html', {
        'form': form,
    })

Give it an address in a new accounts/urls.py:

"""Addresses of the accounts app's own pages."""
from django.urls import path

from . import views

app_name = 'accounts'

urlpatterns = [
    path('accounts/profile/', views.profile, name='profile'),
]

Include it in config/urls.py, before allauth’s URLs, so that /accounts/profile/ is Otahque’s:

    path('', include('accounts.urls')),
    path('accounts/', include('allauth.urls')),
    path('', include('events.urls')),

The template, accounts/templates/accounts/profile.html, also links to allauth’s pages for email addresses and connected accounts:

{% extends "base.html" %}

{% block title %}Your profile | Otahque{% endblock %}

{% block content %}
  <h1>Your profile</h1>
  <p>Signed in as {{ user.email }}. Your display name is
     public on the pages of events you organize.</p>
  <form method="post" class="card space-y-4 border
        border-base-300 bg-base-100 p-6">
    {% csrf_token %}
    {{ form }}
    <button type="submit" class="btn btn-primary">
      Save profile</button>
  </form>
  <p class="flex flex-wrap gap-4">
    <a href="{% url 'account_email' %}">Email addresses</a>
    <a href="{% url 'socialaccount_connections' %}">
      Connected accounts</a>
  </p>
{% endblock %}

Last, tell allauth where members land after signing in. Add at the end of settings.py:

# After signing in, members land on their own profile.
LOGIN_REDIRECT_URL = 'accounts:profile'
uv run python manage.py test accounts.tests.ProfileTests
Found 6 test(s).
Creating test database for alias 'default'...
...
Ran 6 tests in ...s

OK
Destroying test database for alias 'default'...

Members need to sign in and out from every page. In templates/includes/site_nav.html, add this block just before </nav>. Signing out is a form with the CSRF token, never a link:

  <span class="ml-auto flex items-center gap-5">
    {% if user.is_authenticated %}
      <a href="{% url 'accounts:profile' %}">
        {{ user.display_name|default:"Profile" }}</a>
      <form method="post"
            action="{% url 'account_logout' %}">
        {% csrf_token %}
        <button type="submit" class="underline">
          Sign out</button>
      </form>
    {% else %}
      <a href="{% url 'account_login' %}">Sign in</a>
      <a href="{% url 'account_signup' %}">Sign up</a>
    {% endif %}
  </span>

Now prove what signing in and out do. These tests pass at once, because allauth and Django already behave this way; they hold the behaviour in place for every later chapter. Add them at the end of accounts/tests.py:

class SignInTests(TestCase):
    """Signing in with an email and password."""

    @classmethod
    def setUpTestData(cls):
        cls.sai = User.objects.create_user(
            'sai@example.org', PASSWORD, display_name='Sai'
        )

    def sign_in(self, email, password=PASSWORD):
        """Post the sign-in form for email."""
        return self.client.post('/accounts/login/', {
            'login': email, 'password': password,
        })

    def test_any_letter_case_signs_in(self):
        response = self.sign_in('Sai@EXAMPLE.org')
        self.assertRedirects(
            response, reverse('accounts:profile'),
            fetch_redirect_response=False,
        )

    def test_a_wrong_password_is_refused(self):
        response = self.sign_in('sai@example.org', 'wrong')
        self.assertEqual(response.status_code, 200)
        self.assertNotIn('_auth_user_id',
                         self.client.session)

    def test_the_session_key_changes(self):
        self.client.get('/accounts/login/')
        session = self.client.session
        session['seen'] = True
        session.save()
        before = session.session_key
        self.sign_in('sai@example.org')
        self.assertNotEqual(self.client.session.session_key,
                            before)

    def test_sign_out_needs_a_post(self):
        self.client.force_login(self.sai)
        self.client.get('/accounts/logout/')
        self.assertIn('_auth_user_id', self.client.session)
        self.client.post('/accounts/logout/')
        self.assertNotIn('_auth_user_id',
                         self.client.session)
uv run python manage.py test accounts.tests.SignInTests
Found 4 test(s).
Creating test database for alias 'default'...
...
Ran 4 tests in ...s

OK
Destroying test database for alias 'default'...

Common Error: a sign-out link

<a href="{% url 'account_logout' %}">Sign out</a> looks like it works: it opens allauth’s page, which asks for confirmation and signs out only when that page’s button sends a POST. A link that signed out on a GET would let any page sign a member out with an image tag. Keep the form.

Step 6: Sign-up asks for a name and a time zone

Without help, allauth’s sign-up saves the display name as an empty text, because it does not know the field exists. Tests first. These go at the end of accounts/tests.py, with a helper that the next steps reuse:

def signup_data(**changes):
    """Return what the sign-up page sends."""
    return {'email': 'sai@example.org',
            'display_name': 'Sai',
            'timezone': 'Asia/Kolkata',
            'password1': PASSWORD,
            'password2': PASSWORD} | changes


class SignUpTests(TestCase):
    """Signing up: what is asked, and what is saved."""

    url = '/accounts/signup/'

    def test_the_page_asks_for_name_and_zone(self):
        response = self.client.get(self.url)
        for name in ('email', 'display_name', 'timezone',
                     'password1', 'password2'):
            self.assertContains(response, f'name="{name}"')

    def test_sign_up_saves_name_zone_and_lower_case(self):
        response = self.client.post(
            self.url, signup_data(email='SAI@Example.ORG')
        )
        self.assertRedirects(
            response, reverse('accounts:profile'),
            fetch_redirect_response=False,
        )
        sai = User.objects.get()
        self.assertEqual(sai.email, 'sai@example.org')
        self.assertEqual(sai.display_name, 'Sai')
        self.assertEqual(sai.profile.timezone,
                         'Asia/Kolkata')
        self.assertTrue(sai.check_password(PASSWORD))

    def test_a_display_name_is_required(self):
        response = self.client.post(
            self.url, signup_data(display_name='')
        )
        self.assertEqual(response.status_code, 200)
        self.assertFalse(User.objects.exists())

    def test_a_confirmation_email_is_sent(self):
        self.client.post(self.url, signup_data())
        self.assertEqual(len(mail.outbox), 1)
        self.assertEqual(mail.outbox[0].to,
                         ['sai@example.org'])

    def test_an_address_in_use_is_refused(self):
        User.objects.create_user('sai@example.org',
                                 display_name='Sai')
        response = self.client.post(
            self.url, signup_data(email='Sai@example.org')
        )
        self.assertEqual(response.status_code, 200)
        self.assertEqual(User.objects.count(), 1)
uv run python manage.py test accounts.tests.SignUpTests
Found 5 test(s).
Creating test database for alias 'default'...
...
AssertionError: 302 != 200
AssertionError: '' != 'Sai'
Ran 5 tests in ...s

FAILED (failures=3)
Destroying test database for alias 'default'...

Add the sign-up form to accounts/forms.py, between NAME_HELP and ProfileForm. allauth adds its fields to these and calls signup() once the account exists:

class SignupForm(forms.Form):
    """What Otahque asks at sign-up, beside the email."""

    display_name = forms.CharField(
        max_length=100, help_text=NAME_HELP,
    )
    timezone = forms.ChoiceField(
        choices=ZONE_CHOICES, required=False,
        label='Time zone (optional)',
    )

    def signup(self, request, user):
        """Save the extra answers once the account exists."""
        user.display_name = self.cleaned_data['display_name']
        user.save(update_fields=['display_name'])
        profile = Profile.of(user)
        profile.timezone = self.cleaned_data['timezone']
        profile.save()

Name it in settings.py, just after ACCOUNT_SIGNUP_FIELDS:

ACCOUNT_SIGNUP_FORM_CLASS = 'accounts.forms.SignupForm'
uv run python manage.py test accounts.tests.SignUpTests
Found 5 test(s).
Creating test database for alias 'default'...
...
Ran 5 tests in ...s

OK
Destroying test database for alias 'default'...

The confirmation email appears in the terminal where the development server runs, because MAILERS uses the console. Confirming is optional until Chapter 43 sends real email.

Step 7: Valid, permanent addresses only

Tests first. Add the adapter’s message to the imports of accounts/tests.py, just above the models import:

from .adapter import DISPOSABLE

and the tests at the end:

class AddressCheckTests(TestCase):
    """Disposable email domains are refused."""

    url = '/accounts/signup/'

    def errors(self, email):
        """Return the sign-up page's errors for email."""
        response = self.client.post(
            self.url, signup_data(email=email)
        )
        return response.context['form'].errors.get('email')

    def test_an_invalid_address_is_refused(self):
        self.assertEqual(self.errors('not-an-email'),
                         ['Enter a valid email address.'])

    def test_a_disposable_address_is_refused(self):
        self.assertEqual(self.errors('raj@mailinator.com'),
                         [DISPOSABLE])
        self.assertFalse(User.objects.exists())

    @override_settings(
        EMAIL_DOMAINS_ALLOWED=['mailinator.com']
    )
    def test_an_allowed_domain_is_accepted(self):
        self.client.post(
            self.url, signup_data(email='raj@mailinator.com')
        )
        self.assertTrue(User.objects.exists())
uv run python manage.py test accounts.tests.AddressCheckTests
Found 1 test(s).
Creating test database for alias 'default'...
...
ImportError: Failed to import test module: tests
ModuleNotFoundError: No module named 'accounts.adapter'
Ran 1 test in ...s

FAILED (errors=1)
Destroying test database for alias 'default'...

The adapter goes in a new file, accounts/adapter.py. allauth calls clean_email() with each address at sign-up, after Django’s own check:

"""Otahque's changes to how allauth signs members up."""
from allauth.account.adapter import DefaultAccountAdapter
from disposable_email_domains import blocklist
from django import forms
from django.conf import settings

DISPOSABLE = 'Please use a permanent email address.'


class AccountAdapter(DefaultAccountAdapter):
    """Otahque's choices inside allauth's sign-up."""

    def clean_email(self, email):
        """Refuse disposable domains unless allowed."""
        email = super().clean_email(email)
        domain = email.rsplit('@', 1)[-1].lower()
        allowed = settings.EMAIL_DOMAINS_ALLOWED
        if domain in blocklist and domain not in allowed:
            raise forms.ValidationError(DISPOSABLE)
        return email

Name the adapter, and read the domains to accept anyway from .env. Add at the end of settings.py:

ACCOUNT_ADAPTER = 'accounts.adapter.AccountAdapter'

# Domains accepted even when a disposable-address list
# names them; separated by commas.
EMAIL_DOMAINS_ALLOWED = config(
    'DJANGO_EMAIL_DOMAINS_ALLOWED', default='', cast=Csv()
)

And document the name in .env.example, at the end:

# Domains to accept although a disposable-address list
# names them, separated by commas; usually empty.
DJANGO_EMAIL_DOMAINS_ALLOWED=
uv run python manage.py test accounts.tests.AddressCheckTests
Found 3 test(s).
Creating test database for alias 'default'...
...
Ran 3 tests in ...s

OK
Destroying test database for alias 'default'...

Step 8: allauth’s pages, in Otahque’s style

allauth draws its pages with its own plain layout. Django looks in the project’s templates/ folder before each app’s own templates, so a file at the same path replaces allauth’s. Four small files are enough. The layout uses Otahque’s base.html:

{% extends "base.html" %}

{% block title %}{% block head_title %}{% endblock %} |
  Otahque{% endblock %}

Forms are drawn with Chapter 24’s field templates instead of allauth’s paragraphs:

{{ attrs.form }}
{% load allauth %}
<form method="{{ attrs.method }}"
      class="card space-y-4 border border-base-300
             bg-base-100 p-6"
      {% if attrs.action %}
        action="{{ attrs.action }}"
      {% endif %}>
  {% slot body %}{% endslot %}
  {% slot actions %}{% endslot %}
</form>
{% load allauth %}
{% if attrs.href %}
<a href="{{ attrs.href }}" class="link">
  {% slot %}{% endslot %}</a>
{% else %}
<button class="btn btn-primary"
  {% if attrs.form %}form="{{ attrs.form }}"{% endif %}
  {% if attrs.name %}name="{{ attrs.name }}"{% endif %}
  {% if attrs.value %}value="{{ attrs.value }}"{% endif %}
  type="{{ attrs.type|default:'submit' }}">
  {% slot %}{% endslot %}</button>
{% endif %}

Rebuild the stylesheet with npm run build, and run every test:

uv run python manage.py test
Found 183 test(s).
Creating test database for alias 'default'...
...
Ran 183 tests in ...s

OK
Destroying test database for alias 'default'...

Open the sign-up page at a phone’s width and a desktop’s: it has Otahque’s navigation, the same fields as the New event page, and a primary button.

Step 9: Google and GitHub

Five numbered cards in a column joined by arrows. 1, a blue Button card: Sai chooses GitHub on the sign-in page, a POST. 2, a blue GitHub card: Sai signs in there and allows Otahque to read her email. 3, a purple Callback card: allauth checks the answer and reads the confirmed email. 4, an orange Sign-up form card: as a new member, the form asks a display name and a time zone. 5, a green Signed in card: the user, profile, and GitHub link are saved, and she sees her profile page.
Figure 27.4 — Signing in with a provider, step by step.

The tests cannot reach GitHub, and should not. Instead, a helper builds what allauth would have received from the provider, a confirmed email for a new or an existing member, and hands it to allauth’s own code. Add this at the end of accounts/tests.py:

PROVIDERS = {
    'google': {'APPS': [{'client_id': 'test-id',
                         'secret': 'test-secret'}]},
    'github': {'APPS': [{'client_id': 'test-id',
                         'secret': 'test-secret'}]},
}


def provider_sign_in(provider, email, uid='1'):
    """Sign in as if the provider confirmed this email.

    Returns the response and a client on that session.
    """
    request = RequestFactory().get('/')
    request.session = SessionStore()
    request.session.save()
    request._messages = FallbackStorage(request)
    request.user = AnonymousUser()
    found = get_social_adapter().get_provider(request,
                                              provider)
    login = SocialLogin(
        user=User(email=email),
        account=SocialAccount(provider=provider, uid=uid,
                              extra_data={'email': email}),
        email_addresses=[EmailAddress(
            email=email, verified=True, primary=True,
        )],
        provider=found,
    )
    with request_context(request):
        response = complete_social_login(request, login)
    request.session.save()
    browser = Client()
    key = request.session.session_key
    browser.cookies['sessionid'] = key
    return response, browser


@override_settings(SOCIALACCOUNT_PROVIDERS=PROVIDERS)
class SocialSignInTests(TestCase):
    """Signing in through a provider."""

    def test_buttons_for_configured_providers(self):
        response = self.client.get('/accounts/login/')
        for name in ('Google', 'GitHub'):
            self.assertContains(response, name)

    def test_a_new_member_still_gives_name_and_zone(self):
        response, browser = provider_sign_in(
            'google', 'soni@example.org'
        )
        self.assertEqual(response['Location'],
                         '/accounts/3rdparty/signup/')
        page = browser.get(response['Location'])
        self.assertContains(page, 'name="display_name"')
        browser.post(response['Location'], {
            'email': 'soni@example.org',
            'display_name': 'Soni', 'timezone': '',
        })
        soni = User.objects.get()
        self.assertEqual(soni.display_name, 'Soni')
        account = soni.socialaccount_set.get()
        self.assertEqual(account.provider, 'google')

    def test_a_registered_email_is_asked_to_sign_in(self):
        User.objects.create_user('sam@example.org', PASSWORD,
                                 display_name='Sam')
        response, browser = provider_sign_in(
            'github', 'sam@example.org'
        )
        page = browser.post(response['Location'], {
            'email': 'sam@example.org',
            'display_name': 'Sam', 'timezone': '',
        })
        self.assertContains(
            page, 'An account already exists with this email'
        )
        self.assertEqual(User.objects.count(), 1)
        self.assertFalse(SocialAccount.objects.exists())

    def test_a_signed_in_member_may_connect(self):
        sam = User.objects.create_user(
            'sam@example.org', PASSWORD, display_name='Sam'
        )
        self.client.force_login(sam)
        response = self.client.get('/accounts/3rdparty/')
        self.assertContains(response, 'GitHub')
        self.assertContains(response, 'Google')
uv run python manage.py test accounts.tests.SocialSignInTests
Found 4 test(s).
Creating test database for alias 'default'...
...
AssertionError: '/accounts/profile/' !=
    '/accounts/3rdparty/signup/'
Ran 4 tests in ...s

FAILED (failures=1)
Destroying test database for alias 'default'...

The new member was signed up straight away, with no display name, because allauth signs new provider members up automatically by default. Turn that off, and read the providers’ credentials from .env. Add at the end of settings.py:

# A first sign-in with a provider still shows the sign-up
# form, so every member gives a display name.
SOCIALACCOUNT_AUTO_SIGNUP = False

# Sign-in with Google and GitHub, only for the providers
# whose client ID is in .env. Secrets never go in Git.
SOCIALACCOUNT_PROVIDERS = {}
for provider in ('google', 'github'):
    client_id = config(
        f'DJANGO_{provider.upper()}_CLIENT_ID', default=''
    )
    if client_id:
        SOCIALACCOUNT_PROVIDERS[provider] = {'APPS': [{
            'client_id': client_id,
            'secret': config(
                f'DJANGO_{provider.upper()}_SECRET'
            ),
        }]}

A provider appears only when its client ID is set, so a reader without credentials sees no broken buttons. Document the names in .env.example:

# Sign-in with Google and GitHub (Chapter 27). Leave the
# client IDs empty to hide a provider's button.
DJANGO_GOOGLE_CLIENT_ID=
DJANGO_GOOGLE_SECRET=
DJANGO_GITHUB_CLIENT_ID=
DJANGO_GITHUB_SECRET=
uv run python manage.py test accounts.tests.SocialSignInTests
Found 4 test(s).
Creating test database for alias 'default'...
...
Ran 4 tests in ...s

OK
Destroying test database for alias 'default'...

To try it for real, which is optional, create an OAuth app at GitHub (Settings, Developer settings, OAuth Apps) with the callback address http://127.0.0.1:8000/accounts/github/login/callback/, and a Google one in the Google Cloud console with http://127.0.0.1:8000/accounts/google/login/callback/. Put each client ID and secret in your .env, never in Git, and restart the server.

Google and GitHub are two of more than a hundred providers in allauth 65.22.1. Others include Apple, Microsoft, Amazon, Facebook, GitLab, Bitbucket, Discord, Slack, LinkedIn, X, Okta, and Auth0, and any service that speaks OpenID Connect or SAML, two common sign-in standards. Each one added is one more line in INSTALLED_APPS, credentials in .env, and a test like the ones above, and one more company trusted with members’ email addresses.

Step 10: Organized by, the design, and the commit

Members now choose their names, so event pages can say who organizes them, as decided when profiles were planned. Tests first, at the end of events/tests.py:

class OrganizedByTests(TestCase):
    """An event's page names its current organizers."""

    @classmethod
    def setUpTestData(cls):
        cls.sam = editor()
        cls.event = save_event()
        cls.place = cls.event.add_organizer(cls.sam)

    def page(self):
        """Return the address of the event's own page."""
        return self.client.get(self.event.get_absolute_url())

    def test_the_organizer_is_named(self):
        self.assertContains(self.page(), 'Organized by Sam')

    def test_the_name_follows_the_profile(self):
        self.sam.display_name = 'Sam Chen'
        self.sam.save()
        page = self.page()
        self.assertContains(page, 'Organized by Sam Chen')

    def test_a_revoked_organizer_is_not_named(self):
        self.place.revoked_at = timezone.now()
        self.place.save()
        self.assertNotContains(self.page(), 'Organized by')

The names cost one more query on the event page, so Chapter 22’s query count in PlacesLeftTests.test_pages_show_places_left changes in place: the second assertNumQueries(1) becomes assertNumQueries(2).

uv run python manage.py test events -k Organized -k PlacesLeft
Found 5 test(s).
Creating test database for alias 'default'...
...
AssertionError: False is not true : Couldn't find 'Organized
    by Sam' in the following response
AssertionError: 1 != 2 : 1 queries executed, 2 expected
Ran 5 tests in ...s

FAILED (failures=3)
Destroying test database for alias 'default'...

Add the method to Event in events/models.py, before can_be_edited_by:

    def organizer_names(self):
        """List the current organizers' names, in order."""
        return list(self.organizer_assignments.filter(
            revoked_at__isnull=True
        ).values_list('member__display_name', flat=True))

And show the names on the event page, after the location, in events/templates/events/detail.html:

    {% with names=event.organizer_names %}
      {% if names %}
        <p>Organized by {{ names|join:", " }}</p>
      {% endif %}
    {% endwith %}
uv run python manage.py test events -k Organized -k PlacesLeft
Found 5 test(s).
Creating test database for alias 'default'...
...
Ran 5 tests in ...s

OK
Destroying test database for alias 'default'...

Record the decision in docs/adr/ADR-003-accounts-allauth.md:

# ADR-003: Member accounts with django-allauth

## Status

Proposed, November 2026 (Chapter 27). The choice of
django-allauth is the user's decision of 13 November 2026;
this record is not yet reviewed or accepted.

## Context

Members need to sign up, sign in, and sign out on Otahque's
own pages, with the email-only user of ADR-002, and to sign
in with Google or GitHub. Accounts must not be linked by an
email address alone, temporary addresses are refused, and
two-factor sign-in follows in Chapter 29.

## Options

- A: Django's own views (LoginView, LogoutView) and forms
  written for sign-up; social sign-in added later by hand.
- B: social-auth-app-django for providers, with Django's
  views for everything else.
- C: django-allauth for sign-up, sign-in, sign-out, email
  addresses, providers, rate limits, and later two-factor
  sign-in.

## Decision

Option C: `django-allauth[socialaccount]==65.22.1`, with
`disposable-email-domains==0.0.295` for refusing temporary
addresses. Email-only settings (no username field); an
extra sign-up form for the display name and time zone; an
account adapter that refuses disposable domains; provider
credentials read from .env; automatic sign-up through a
provider turned off, so every member gives a display name;
an email already registered is never connected without
signing in to that account first.

## Consequences

- Eleven more packages (the social extra brings requests,
  pyjwt, cryptography, and their dependencies); each pin is
  upgraded on purpose, with the test suite run first.
- allauth's templates are overridden in templates/allauth/
  to use Otahque's layout and field styles.
- The admin's own sign-in page bypasses allauth until
  Chapter 29 wraps it with secure_admin_login.
- Rate limits use the cache; one process is enough locally,
  and a shared cache is needed in production (Chapter 57).

## Revisit when

allauth stops supporting the pinned Django series, a
provider changes its sign-in rules, or the community needs
sign-in that allauth cannot provide.

and the design in docs/design/sign-in.md:

# Sign-up and sign-in: low-level design

Status: Drafted in Chapter 27, for review. Not approved.
Library: django-allauth (ADR-003), with accounts.User
(ADR-002).

## Pages

- /accounts/signup/: email, display name, time zone
  (optional), password twice. allauth's form plus
  accounts.forms.SignupForm. The email passes Django's
  validator, then AccountAdapter.clean_email(): refused if
  its domain is on the disposable-domains list and not in
  EMAIL_DOMAINS_ALLOWED. The address is stored in lower
  case (Chapter 21). A confirmation email is sent;
  verification is optional until Chapter 43.
- /accounts/login/: email (any letter case) and password.
  The session key changes on sign-in. Rate limits apply.
- /accounts/logout/: GET asks; POST signs out.
- /accounts/profile/: login required; edits the signed-in
  member's display name and Profile.timezone; reads no id
  from the address, so no other member can be reached.
  Profile.of(user) makes the profile the first time.
- /accounts/email/, /accounts/password/...: allauth's
  pages; taught in Chapter 29.

## Providers

- Google and GitHub, shown only when their client IDs are
  in .env; secrets never in Git or the database.
- A first sign-in shows the sign-up form (automatic
  sign-up is off), so a display name is always given.
- An email that already has an account: "An account already
  exists with this email address. Please sign in to that
  account first, then connect your ... account." Nothing is
  linked by email alone.
- A signed-in member connects a provider at
  /accounts/3rdparty/.

## Open

- Mandatory verification, with existing members marked
  verified: Chapter 43.
- Password change and reset, two-factor sign-in, and the
  admin's sign-in page: Chapter 29.
- Shared rate limits across processes: Chapter 57.
- Profile image: Chapter 42.

Check, test, and commit:

uv run python manage.py makemigrations --check --dry-run
uv run python manage.py test
No changes detected
Found 190 test(s).
Creating test database for alias 'default'...
...
Ran 190 tests in ...s

OK
Destroying test database for alias 'default'...
git add .
git status --short
git commit -m "Add member accounts with django-allauth"
M  .env.example
A  accounts/adapter.py
A  accounts/forms.py
A  accounts/migrations/0003_profile.py
M  accounts/models.py
A  accounts/templates/accounts/profile.html
M  accounts/tests.py
A  accounts/urls.py
M  accounts/views.py
M  config/settings.py
M  config/urls.py
A  docs/adr/ADR-003-accounts-allauth.md
A  docs/design/sign-in.md
M  events/models.py
M  events/templates/events/detail.html
M  events/tests.py
M  pyproject.toml
M  static/otahque/site.css
A  templates/allauth/elements/button.html
A  templates/allauth/elements/fields.html
A  templates/allauth/elements/form.html
A  templates/allauth/layouts/base.html
M  templates/includes/site_nav.html
M  uv.lock

.env is not in the list, because Chapter 8’s .gitignore keeps it out of Git, with any provider secrets you added.

Table 27.2 lists what to do when a step does not go as described.

Table 27.2 — When a step goes wrong
Symptom Likely cause Recovery
ModuleNotFoundError: requests allauth installed without [socialaccount] Run Step 3's uv add command again, with the extra
ImproperlyConfigured: Deprecated email settings EMAIL_BACKEND added beside MAILERS Remove EMAIL_BACKEND; keep MAILERS
Signing in leads to Page not found LOGIN_REDIRECT_URL set before the profile exists Complete Step 5, or check its URL name
The sign-up page has no Display name ACCOUNT_SIGNUP_FORM_CLASS missing or misspelled Compare it with Step 6; the path is accounts.forms.SignupForm
A Google button that fails A client ID in .env without the matching secret, or the wrong callback address Check both values and the callback; or leave the ID empty to hide the button
Pages look unstyled The stylesheet was not rebuilt Run npm run build, then reload
PAGE 003

Verify Your Work

Work through Table 27.3 from the folder that holds manage.py.

Table 27.3 — Verification checklist for Chapter 27
Check Command or action Expected result
Starting point uv run python manage.py test Found 165 test(s); OK
Packages pinned pyproject.toml django-allauth[socialaccount]==65.22.1 and disposable-email-domains==0.0.295
Tests fail first Each step's new tests, before the code FAILED, or an import error
Tests pass uv run python manage.py test Found 190 test(s); OK
No migration waiting makemigrations --check --dry-run No changes detected
Sign-up /accounts/signup/ for a new address, first at Mailinator, then dev@example.org Please use a permanent email address.; then your profile
Lower case Sign up as Dev@Example.org (not an address already used) The profile shows dev@example.org
Profile Change the display name Profile saved.; the new name in the navigation
Sign-out The Sign out button Sign in and Sign up in the navigation
Organized by Open a published event Sam organizes Organized by and Sam's display name
Visitor sent to sign in /events/new/ in a private window allauth's sign-in page, with next=
Phone width Device toolbar, 390 px No sideways scroll
Committed git status --short No output
Not verified Live Google or GitHub sign-in; macOS, Linux, WSL; Firefox, Safari Readers with credentials or on those systems

The commands were checked in Windows PowerShell 5.1 and Git Bash, from a copy of the Chapter 26 checkpoint, with each listing applied in the order printed. The browser rows were walked through in Microsoft Edge at 390 px and 1280 px. Live sign-in with Google and GitHub was not run: it needs your own OAuth apps, and the tests stand in for it.

PAGE 004

Checkpoint: Quiz and Challenge

Quiz

Que. 3 Why does Otahque’s sign-out button sit inside a form, and what happens if a page links to /accounts/logout/ instead?

Flip to check your answerFold answer back

Answer. Signing out changes the session, so it is a POST with the CSRF token, by Chapter 26’s rule. A link sends a GET, and allauth answers a GET with a page that asks for confirmation; the member stays signed in until that page’s button sends the POST.

Que. 4 Sai signs up as SAI@Example.ORG. What is stored, and which two places make sure of it?

Flip to check your answerFold answer back

Answer. sai@example.org. Chapter 21’s model rule lower-cases the email when a member is saved, and its database constraint refuses a capital letter from anywhere; allauth’s sign-up goes through both.

Que. 5 Where does Otahque refuse raj@mailinator.com, and what would you change to accept a domain the list names by mistake?

Flip to check your answerFold answer back

Answer. In AccountAdapter.clean_email(), which allauth calls with every address at sign-up, after Django’s own check. Add the domain to DJANGO_EMAIL_DOMAINS_ALLOWED in .env, which EMAIL_DOMAINS_ALLOWED reads.

Que. 6 Sam has an account with a password. He chooses GitHub on the sign-in page, and GitHub confirms the same address. What happens, and why?

Flip to check your answerFold answer back

Answer. The page says that an account already exists with this email address and asks him to sign in to that account first, then connect GitHub. A provider vouches for an email, not for an Otahque account, so nothing is linked by email alone.

Que. 7 Why can the profile page not be used to change another member’s name?

Flip to check your answerFold answer back

Answer. It reads no id from the address. It edits request.user, the member who signed in, and its form ignores every field it does not list.

Mini-Challenge

Que. 8 Predict what the sign-up page does with two submissions of the same details, SAI@Example.ORG with a strong password: the first with the display name empty, the second with the display name Sai. Then check with l2_signup.py below, run with uv run python manage.py shell -c "exec(open('l2_signup.py').read())".

Flip to check your answerFold answer back

Answer. The first returns the page with status 200 and “This field is required.” for the display name, and saves nothing. The second creates the member, stored as sai@example.org with the name Sai. The file undoes its work, so your rows are unchanged:

from django.db import transaction
from django.test import Client
from django.test.utils import setup_test_environment

from accounts.models import User

setup_test_environment()
SENT = {'email': 'SAI@Example.ORG', 'display_name': '',
        'timezone': '', 'password1': 'a-long-safe-pass-123',
        'password2': 'a-long-safe-pass-123'}
with transaction.atomic():
    web = Client()
    page = web.post('/accounts/signup/', SENT)
    form = page.context['form']
    errors = list(form.errors['display_name'])
    print('without a name:', page.status_code, errors)
    named = SENT | {'display_name': 'Sai'}
    web.post('/accounts/signup/', named)
    sai = User.objects.get(display_name='Sai')
    print('with a name:', sai.email, sai.display_name)
    transaction.set_rollback(True)
without a name: 200 ['This field is required.']
with a name: sai@example.org Sai

What We Learned

  • Authentication answers who someone is; signing in records it in the session with a new key, and signing out is a POST.
  • django-allauth provides account pages and rules; it is pinned to an exact version and recorded in an ADR, and configured for Otahque’s email-only user with three settings.
  • Extra details at sign-up come from a form named in ACCOUNT_SIGNUP_FORM_CLASS; its signup() runs once the account exists.
  • A Profile holds a member’s own settings, made the first time it is needed; a page that edits request.user cannot reach another member.
  • Invalid addresses fail Django’s check; disposable ones fail the adapter’s clean_email(), against a maintained list.
  • Provider credentials live in .env; a provider’s email is never enough to link an existing account.
  • Overriding a package’s templates in templates/ keeps the package and changes its look.
  • A test can stand in for a provider by building its answer, so the suite runs offline.

Key terms

Use Table 27.4 to explain this chapter’s ideas in your own words.

Table 27.4 — Key terms from Chapter 27
Term Meaning
Authentication Proving who someone is, as signing in does.
Session key The value in the browser's cookie that names the session; renewed at sign-in.
django-allauth A Django package for sign-up, sign-in, email addresses, and providers.
Adapter allauth's class of hooks; Otahque's checks the email at sign-up.
Profile One row per member for their own settings, linked one-to-one.
OneToOneField A foreign key that allows one related row on each side.
Disposable address A temporary inbox, refused at sign-up.
Provider A service, such as Google or GitHub, that vouches for a person's email.
OAuth The standard a provider uses to tell Otahque who signed in.
Linking Connecting a provider account to an Otahque account, only after signing in to it.

Readiness checkpoint: you are ready for Chapter 28 when all 190 tests pass, makemigrations --check --dry-run prints No changes detected, a new member can sign up with a display name and is refused with a disposable address, the profile page saves a name and a time zone, signing out needs the button, the event pages show who organizes them, and the commit is made.

Git Commit

Your Chapter 27 work was committed in Step 10, with the message “Add member accounts with django-allauth”. It holds the two pinned packages, the settings and URLs, the profile model and its migration, the sign-up and profile forms, the adapter, the profile view, page, and navigation, four allauth templates, the rebuilt stylesheet, the organizers’ names on event pages, the ADR and the sign-in design, twenty-five new tests, and four changed in place.

PAGE 005

Test Your Knowledge: Interview Questions

These five questions rehearse the chapter at interview level, from junior to lead. L1 to L3 check what you have just done. L4 and L5 look ahead: attempt them now, and return after Chapters 29 and 30. They are extension questions, not a gate to the next chapter.

L1 (Junior): What does signing in change in the session, and why does sign-out need a POST?

What the interviewer is testing: Do you know what the session holds, why its key changes, and why a state change is never a GET?

Flip to check your answerFold answer back

Perfect answer: Signing in stores the member’s id, and a value derived from their password hash, in the session, and Django gives the session a new key, so a key someone saw before sign-in no longer works. Signing out deletes that data. It is a state change, so it is a POST with the CSRF token; a GET only shows a confirmation page, and the member stays signed in. Otherwise any page could sign a member out with an image or a link.

Behind the scenes:

POST /accounts/login/   -> new session key, member id stored
GET  /accounts/logout/  -> a page that asks; still signed in
POST /accounts/logout/  -> session cleared

Code proof: a demo member signs in and out, rolled back afterwards:

from django.db import transaction
from django.test import Client
from django.test.utils import setup_test_environment

from accounts.models import User

setup_test_environment()
PASSWORD = 'a-long-safe-pass-123'
with transaction.atomic():
    User.objects.create_user('demo@example.org', PASSWORD,
                             display_name='Demo')
    web = Client()
    web.get('/accounts/login/')
    session = web.session
    session['seen'] = True
    session.save()
    before = session.session_key
    web.post('/accounts/login/', {
        'login': 'demo@example.org', 'password': PASSWORD,
    })
    after = web.session.session_key
    print('new key after sign-in:', after != before)
    web.get('/accounts/logout/')
    signed_in = '_auth_user_id' in web.session
    print('signed in after GET:', signed_in)
    web.post('/accounts/logout/')
    signed_in = '_auth_user_id' in web.session
    print('signed in after POST:', signed_in)
    transaction.set_rollback(True)
new key after sign-in: True
signed in after GET: True
signed in after POST: False

Common mistakes:

  • A sign-out link instead of a form.
  • Thinking the password itself is kept in the session.
  • Turning on allauth’s ACCOUNT_LOGOUT_ON_GET, which its documentation calls a last resort.

Follow-up the interviewer might ask:

  • “What is session fixation, and how does a new key prevent it?”
  • “Where is the session stored, and what does the cookie hold?”

L2 (Mid-Level): Sai signs up as SAI@Example.ORG without a name. Predict what is saved.

What the interviewer is testing: Can you trace a sign-up through Django’s checks, allauth, and Otahque’s form, and say what reaches the database?

Flip to check your answerFold answer back
Five numbered steps. Sai sends SAI@Example.ORG and leaves Display name empty. Django’s email validator passes the address. The sign-up form refuses, because Display name is required. The page returns with the message beside the field. Nothing is saved, and with a name the email is stored in lower case.
Figure 27.5 — A sign-up without a display name.

Perfect answer: Nothing is saved. The address is valid, so Django’s check passes, and it is not disposable, so the adapter passes. But Otahque’s sign-up form makes the display name required, so the form is invalid and the page returns with status 200 and the message beside Display name. With a name, the member is saved with sai@example.org, because Chapter 21’s rule lower-cases the email, and the time zone goes to the profile.

Behind the scenes:

email field       -> valid address
clean_email()     -> not disposable
display_name      -> required: refused
form invalid      -> 200, same page, nothing saved

Code proof: the Mini-Challenge’s l2_signup.py:

without a name: 200 ['This field is required.']
with a name: sai@example.org Sai

Common mistakes:

  • Expecting allauth to know about display_name without a sign-up form.
  • Lower-casing in the view only, so other paths store capitals.
  • Making the time zone required, which turns away people who do not know theirs.

Follow-up the interviewer might ask:

  • “Where would you put a rule that a display name must be unique?”
  • “How does a member who signs up with Google give a display name?”

L3 (Senior): Defend not linking a GitHub sign-in to an existing account by email alone.

What the interviewer is testing: Do you see the account-takeover risk, and know where the safe flow puts the proof?

Flip to check your answerFold answer back
Five numbered steps. The goal is never to hand an account to the wrong person. A provider vouches for an email, not for an Otahque account. Someone may have signed up with that address and never confirmed it. Ask the person to sign in to the account first, then connect. Test that a matching email links nothing on its own.
Figure 27.6 — Why a matching email is not enough to link.

Perfect answer: GitHub tells Otahque that this person controls an address. It does not tell Otahque who controls the Otahque account with that address: someone else could have signed up with it and never confirmed it, or the address could have changed hands. Linking by email would give whoever signs in with GitHub that account. So Otahque asks the person to sign in to the existing account first, which proves they control it, and then connect GitHub. It costs one extra step, once.

Behind the scenes:

provider says  -> sam@example.org, confirmed
Otahque has    -> an account for sam@example.org
result         -> "already exists ... sign in first"
linked         -> only after signing in to the account

Code proof: the Step 9 test test_a_registered_email_is_asked_to_sign_in, run on its own:

Found 1 test(s).
Creating test database for alias 'default'...
...
Ran 1 test in ...s

OK
Destroying test database for alias 'default'...

Common mistakes:

  • Turning on email authentication with automatic connection for every provider.
  • Trusting a provider’s email without checking that the provider marks it confirmed.
  • Merging two accounts without telling either owner.

Follow-up the interviewer might ask:

  • “When could automatic connection be acceptable?”
  • “How would you let a member disconnect a provider safely?”

L4 (Staff): Members report being signed out of other devices after a password change. Diagnose.

What the interviewer is testing: Do you know how Django ties sessions to the password, and whether this is a fault or a feature?

Flip to check your answerFold answer back
Five numbered steps. After a password change, other devices are signed out. Changing a password changes the session hash Django checks. Sessions without the new hash no longer count as signed in. That is intended, because a stolen session stops working. Keep the current device signed in, as Django’s helper does.
Figure 27.7 — Why a password change signs out other devices.

Perfect answer: It is intended. Django stores a hash derived from the password in each session and compares it on every request. After a change, the other devices’ sessions carry the old hash, so they are treated as signed out, and a session someone stole stops working too. The device where the member changed the password stays signed in because Django’s update_session_auth_hash() updates that one session; Chapter 29’s password-change page does this. Tell members it is a safety feature, and check that the current device is not signed out as well.

Behind the scenes:

phone, laptop   -> both signed in
password saved  -> new hash on the account
laptop request  -> old hash: signed out, sent to sign in

Code proof: a member signed in on two clients changes the password, rolled back afterwards:

from django.db import transaction
from django.test import Client
from django.test.utils import setup_test_environment

from accounts.models import User

setup_test_environment()
with transaction.atomic():
    raj = User.objects.create_user(
        'demo@example.org', 'first-long-pass-1',
        display_name='Demo',
    )
    phone, laptop = Client(), Client()
    for device in (phone, laptop):
        device.force_login(raj)
    raj.set_password('second-long-pass-2')
    raj.save()
    page = laptop.get('/accounts/profile/')
    print('laptop after the change:', page.status_code,
          page.get('Location', '').split('?')[0])
    transaction.set_rollback(True)
laptop after the change: 302 /accounts/login/

Common mistakes:

  • Removing the hash check to stop the complaint.
  • Forgetting update_session_auth_hash() on a custom password page, which signs out the member who changed it.
  • Not telling members why it happened.

Follow-up the interviewer might ask:

  • “How would you let a member sign out of every other device on purpose?”
  • “What does Chapter 29’s two-factor sign-in add on top?”

L5 (Lead): The board wants sign-in with five more providers. What do you advise?

What the interviewer is testing: Can you turn a request into a decision with costs, privacy, and tests, and avoid adding everything because it is easy?

Flip to check your answerFold answer back
Five numbered steps. The goal is sign-in that suits the members, safely. Each provider is a party trusted with members’ email addresses. Each needs credentials, a privacy notice, and a mocked test. Ask which providers the members already use. Add one at a time, behind the same linking rule.
Figure 27.8 — Adding providers on purpose.

Perfect answer: Ask which providers the members already use, because each one is a company trusted with members’ email addresses and a set of credentials to keep secret and renew. allauth makes each addition small, a line in settings, credentials in .env, and a test, but each one also needs a line in the privacy notice and a check that it marks emails as confirmed. Add them one at a time, keep the same linking rule for all of them, and remove any that nobody uses. A community with a company identity service can use OpenID Connect or SAML instead of many separate providers.

Behind the scenes:

INSTALLED_APPS  -> its provider app
.env            -> client ID and secret
tests           -> a built answer, like Step 9's
notice          -> what the provider shares

Code proof: the providers in the installed allauth, counted:

from pathlib import Path

import allauth.socialaccount.providers as providers

folder = Path(providers.__file__).parent
names = sorted(p.name for p in folder.iterdir()
               if (p / 'provider.py').exists())
print(len(names), 'providers, for example:')
print(', '.join(n for n in names if n in {
    'apple', 'microsoft', 'gitlab', 'discord', 'slack',
    'openid_connect', 'saml', 'okta'}))
128 providers, for example:
apple, discord, gitlab, microsoft, okta, openid_connect,
    saml, slack

Common mistakes:

  • Adding every provider because the package offers them.
  • Storing provider secrets in the database or in Git.
  • Linking accounts across providers by email.

Follow-up the interviewer might ask:

  • “How would you retire a provider members still use?”
  • “What changes when the community needs single sign-on for a company?”
PAGE 006