ContentsClose contents
Pre-release
Chapter 29 · Account security: passwords, sign-in codes, and two factorsCHAPTER 29

Complete six-part pre-release for review. Adds allauth's mfa extra (qrcode, fido2) and its migrations. Requiring two-factor sign-in for staff and encrypting the stored secrets are Chapter 59; real email is Chapter 43; a shared cache is Chapter 57; passkeys follow HTTPS in Chapter 63.

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-NINE

Account security: passwords, sign-in codes, and two factors

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

Prerequisites: Chapters 15 to 28, including the Chapter 28 project, its 224 passing tests, the members who sign up and sign in through django-allauth since Chapter 27, and the signing walkthrough of Chapter 28

What you’ll build: Password rules of at least 15 characters; password change, reset, and set pages that reveal nothing about who has an account; reset links that work once and for one hour; Otahque’s own wording in every account email, with a notice for each change; sign-in by a code sent by email; two-factor sign-in with an authenticator app and recovery codes; the admin’s sign-in sent through the same pages; and a written design that names each known risk and the chapter that closes it

Why This Matters

Sai forgets her password the night before the Delhi workshop. She asks for a reset on Otahque’s sign-in page. The page must help her, but it must not help a stranger who types addresses one after another to learn who has an account: knowing that sai@example.org belongs to Otahque is the first step of an attack on Sai. And the link she receives must stop working as soon as she has used it, because emails are forwarded, left open, and read over shoulders.

Raj signed up with GitHub in Chapter 27, so he has no Otahque password at all. When GitHub is down, he has no way in. He asks for what many sites call a magic link: sign in from an email. Otahque gives him a sign-in code instead, and this chapter explains why a code is the safer form of the same idea.

Sam runs the admin. A password is one secret; if it leaks, everything Sam can do is open to whoever has it. He turns on two-factor sign-in: after his password, Otahque asks for a six-digit code from an app on his phone. And the admin’s own sign-in page, which Chapter 23 set up, must stop letting anyone around that second step.

These requests share one question: what does Otahque trust as proof that a person is who they claim, and what happens when one proof is lost? A password is something you know. A code from the phone is something you have. An email proves that you can read a mailbox. Each proof has a cost, and each fails in its own way.

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

  • set password rules from a published standard, and say why length matters more than mixing symbols;
  • change, reset, and set a password with django-allauth, and say what each one ends;
  • keep the reset page from revealing who has an account, and test it;
  • explain why a reset link stops working, using Chapter 28’s signing;
  • offer sign-in by an emailed code, and say what it proves and what it does not;
  • turn on two-factor sign-in with an authenticator app and recovery codes, and test it with a mocked clock;
  • route the admin’s sign-in through the same pages, and name the risks left for later chapters.

Requiring two-factor sign-in for every staff account, and encrypting the stored secrets, are Chapter 59. Real email delivery is Chapter 43, and a cache shared between server processes is Chapter 57. Passkeys, which need HTTPS, wait until after Chapter 63.

PAGE 001

What You Need to Know

What a password proves, and the rules for one

A password proves that the person typing it knows a secret that only the member should know. Django never stores the password itself: Chapter 17 showed that it stores a hash, a value worked out from the password that cannot be turned back into it. At sign-in, Django hashes what was typed and compares.

Which passwords to accept is set by AUTH_PASSWORD_VALIDATORS, the list Django’s project template put in settings.py and Chapter 17 promised to review here. Its four checks refuse a password too like the member’s name or email, one shorter than eight characters, one in a list of 20,000 common passwords, and one made only of digits.

The rules in this chapter come from NIST SP 800-63B-4, the United States National Institute of Standards and Technology’s guidance on signing in, finalized in 2025. Otahque is not a government system, but the guidance is public, tested, and widely followed. Table 29.1 compares it with Django’s defaults.

Table 29.1 — Password rules: NIST and Otahque
NIST SP 800-63B-4 (3.1.1.2) Django's default Otahque from this chapter
At least 15 characters for a password used alone At least 8 At least 15
Check against common and breached passwords 20,000 common ones The same; breach checks in Chapter 59
No rules such as "one digit and one symbol" None None
No forced change every few months None None
Allow at least 64 characters, paste, and password managers All allowed All allowed

Length wins because each extra character multiplies the guesses an attacker needs. “violet kettle harbour” is 21 characters, easy to remember, and far harder to guess than “P@ssw0rd!”, which follows the old symbol rules and appears in every attacker’s list. Fifteen characters applies to a password used alone; NIST allows eight when a second factor is always required. Two-factor sign-in is optional for Otahque’s members, so for most of them the password is the only factor, and 15 is the rule.

A new rule applies only when a password is chosen, changed, reset, or set. Existing passwords keep working: NIST says not to force a change without a reason to believe the password was stolen.

Changing, resetting, and setting a password

Three pages handle passwords, and allauth already provides all three at addresses Chapter 27 installed:

  • Change (/accounts/password/change/): a signed-in member types the current password and a new one.
  • Reset (/accounts/password/reset/): a member who forgot it receives an email with a link, and chooses a new one.
  • Set (/accounts/password/set/): a member with no password, such as Raj, chooses a first one.

Changing a password signs out every other browser where the member was signed in, and keeps the browser that made the change. Django does this by storing a value worked out from the password hash in each session; when the hash changes, every other session no longer matches, and Django treats it as signed out. If a thief had Sai’s password and was signed in on another computer, her change throws the thief out.

A reset that reveals nothing

Account enumeration means learning which addresses have accounts by watching how a site answers. A reset page that says “no account with that address” tells the stranger exactly that. So Otahque’s reset page shows the same “check your email” page for every address: a member’s, an unknown one, and that of an account an administrator has made inactive. Only a member’s address gets an email. Figure 29.1 follows Sai’s reset.

Four numbered cards down the left joined by arrows, and one box on the right. 1, a blue Ask card: Sai types her address on the reset page. 2, a purple Same page card: every address sees check your email, and only a member’s address gets an email. 3, an orange One-hour link card: works once, and the key moves from the address into the session. 4, a green New password card: other browsers signed out, a notice emailed, and Sai signs in with the new password. A grey Unknown or inactive box on the right, with an arrow to card 2, says the same page, and no email at all.
Figure 29.1 — A reset that reveals nothing.

allauth can also email an unknown address to say “someone tried to use this address here; you have no account”. The decision for Otahque is that someone who never signed up should not receive Otahque’s emails, so that email is turned off. The OWASP Forgot Password Cheat Sheet, the Open Worldwide Application Security Project’s guidance, also asks for the same answer in the same time for every address. Locally, sending an email to the console takes no measurable time; Chapter 43 measures the difference once real email is sent.

Two more rules follow from the same guidance. A reset does not sign the member in: after choosing a new password, Sai signs in with it, the ordinary way. And every change to a password, by change, reset, or set, sends the member a notice, an email that says what changed, from which address and browser, and when. A notice is how Sai would learn of a change she did not make.

Tokens that end

The link in a reset email ends with a token, a value that proves the email was sent by Otahque for this member. Chapter 28 showed signed values, which work until they expire however many times they are used. A reset token must work once. Django’s token generator achieves that without storing anything: the token is worked out from the member’s id, a time, the current password hash, and the time of the last sign-in. Change the password, or sign in, and the same calculation gives a different answer, so the old token no longer matches. allauth’s generator adds the member’s email addresses, so changing an address ends the link too.

New Concept: a token that stores nothing

What problem exists? A reset link must work once, expire, and be impossible to make up. Saving each token in a table works, but then the table must be cleaned, and a copy of it would let anyone reset any password.

What did people do before? Early sites emailed a new password in plain text, or stored a random token that never expired.

What is it? A token worked out from data that changes when it is used: the password hash and the last sign-in, signed with SECRET_KEY through an HMAC, the same kind of keyed hash as Chapter 28’s signatures. Using the link changes the password, and the token stops matching.

Why use it? There is nothing to store, clean, or leak, and nobody without SECRET_KEY can make a valid one. Expiry comes from the time inside it, checked against PASSWORD_RESET_TIMEOUT.

Now let’s use it. Step 2 makes a token in the shell and watches it stop working.

PASSWORD_RESET_TIMEOUT is three days in Django. Otahque sets one hour: a link sitting in a mailbox is a key to the account, and an hour is long enough for slow mail. NIST allows emailed recovery codes for at most 24 hours; OWASP asks only for “an appropriate period”.

A code instead of a link

A magic link signs a person in from an email, with no password. allauth’s version sends a code instead: eight letters and digits such as DPFW-HDVB, typed into the browser window that asked for it. Figure 29.2 shows why a code is the safer form.

Two boxes side by side and a banner. A red A sign-in link box: opened on the phone, it signs the phone in; mail scanners may open it; a forwarded email still works. A green A sign-in code box: typed in the browser that asked; any other browser is refused; ten minutes, three tries. A grey banner says both prove only that you read the mailbox, as a reset does: a convenience, not a second factor.
Figure 29.2 — A sign-in link and a sign-in code.

A link signs in whichever device opens it. Sai asks on her laptop, opens the email on her phone, and her phone is signed in, not her laptop. Some email services open links themselves to check them for danger. And anyone she forwards the email to can use it. The code is tied to the browser that asked for it: allauth remembers the request in that browser’s session, so the same code typed anywhere else is refused. Otahque’s code works for ten minutes, and three wrong tries throw it away.

Under the Hood: what an emailed code proves

NIST SP 800-63B-4 says that “email SHALL NOT be used for out-of-band authentication”: an emailed code is not a second factor, because anyone who can read the mailbox can read the code. That is true, and it is also true of the reset email. Whoever controls Sai’s mailbox can already reset her password, so a sign-in code opens no new way in; it only saves the step of choosing a new password. Otahque treats it as a convenience at the level of a reset. When two-factor sign-in is on, the second factor is still asked for after the code.

Something you know, something you have

Two-factor sign-in asks for two different kinds of proof. The password is something you know. The second is something you have: a phone with an authenticator app, such as Google Authenticator, Microsoft Authenticator, or any app that supports TOTP. Figure 29.3 shows a sign-in with both.

Four numbered cards down the left joined by arrows, and one red box on the right. 1, a blue First factor card: the password, or a code from the email. 2, a purple Asked for more card: two-factor sign-in is on, so the session is not signed in yet. 3, an orange Second factor card: an authenticator code, 30 seconds and used once, or a recovery code, once. 4, a green Signed in card: member pages open, and for staff the admin too. A red Password alone box on the right, with an arrow to card 2, says it stops at step 2, and no page that needs signing in opens.
Figure 29.3 — Signing in with two factors.

TOTP, a time-based one-time password, works like this. When Sam turns it on, Otahque makes a random secret and shows it as a QR code. His app reads it, and from then on, both the app and Otahque work out a six-digit code from the secret and the current time, cut into 30-second steps. The codes match only if both have the same secret and the same time. Nothing travels between the phone and Otahque, so the phone needs no network.

A phone can be lost. Recovery codes are ten single-use codes of eight digits, shown once two-factor sign-in is on. Sam prints them or keeps them in his password manager, and each one works once in place of the app’s code.

New Tool: allauth’s two-factor module

What problem exists? Two-factor sign-in needs secrets, QR codes, codes checked against time, recovery codes, pages to turn it on and off, and a second step in every sign-in path: password, code, provider, and the admin.

What did people do before? Separate packages bolted a second step onto Django’s sign-in, and every new sign-in path needed it added again.

What is it? allauth.mfa, the multi-factor part of the allauth package Otahque already uses, added with its mfa extra. It provides TOTP, recovery codes, and passkeys, and puts the second step after every way of signing in.

Why use it? One package for every sign-in path, kept up to date by the same maintainers, and decided for Otahque on 13 November 2026.

Now let’s use it. Step 8 adds it, Step 9 turns it on for a member, and Step 10 signs in with it.

Two rules protect the second factor. Turning it on asks for the password again, so that a browser left signed in cannot add an attacker’s phone. And a code is accepted only once, even inside its 30 seconds: someone who sees Sam type it cannot use it after him. allauth remembers each used code in Django’s cache, a fast store kept in the server’s memory. Otahque’s cache, like Django’s default, lives inside one server process; Chapter 57 lists every kind of cache Django offers and moves Otahque to one shared between processes.

Two-factor sign-in is optional for members and will be required for staff from Chapter 59. A passkey, which signs in with the phone’s fingerprint or face, is the strongest second factor, but browsers allow it only on HTTPS sites, so Otahque adds it, as an optional extra, after Chapter 63.

Where each check lives

Most of this chapter’s behaviour is allauth’s and Django’s; Otahque decides settings, words, and one form, and proves each rule with a test. Figure 29.4 shows the four places.

Four boxes side by side and a banner. A purple allauth box: pages, reset links, sign-in codes, two-factor steps, notices. A purple Django box: password rules, the reset token, sessions ended on a change. An orange The cache box: used codes and rate limits, one per process until Chapter 57. A green The database box: the authenticator secret, as plain text until Chapter 59. A grey banner says Otahque writes settings, email wording, one form, and the tests that prove each rule.
Figure 29.4 — Where each check lives.

The database box names a risk. allauth stores the authenticator secret, and the seed from which the recovery codes are made, as plain text. Anyone with a copy of the database can work out every member’s codes. Locally the members are fictional and no site is public, and Chapter 59 encrypts these values before Chapter 63 puts Otahque online. This chapter shows the risk with a test rather than hiding it.

Try it yourself

Que. 1 An attacker types sai@example.org and then nobody@example.org into Otahque’s reset page. What do the two answers look like, and what does Sai receive?

Flip to check your answerFold answer back

Answer. Both show the same “check your email” page. Sai receives a reset email; nobody@example.org receives nothing. The attacker learns nothing from the page, and Sai learns from the email that someone asked.

Que. 2 Sam’s phone shows 412 093. He types it, signs in, and a colleague behind him types 412 093 in another browser within the same 30 seconds. What happens?

Flip to check your answerFold answer back

Answer. The colleague is refused. allauth remembered the code as used when Sam signed in, so the same code fails for the rest of its 30 seconds, even though the time still matches.

PAGE 002

How We Build It

Start from Chapter 28, in the folder containing manage.py, with your own .env, the locked environment, 224 passing tests, every migration applied, and Sam’s superuser password from Chapter 18. One package extra is added, in Step 8, with its migrations. The new files are four email templates in templates/account/email/, templates/allauth/elements/field.html, and docs/design/passwords-and-two-factor.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. Steps 2 and 10 hold behaviour allauth and Django already have, so their checks pass at once.

The tests use helpers that each later step shares: member() makes a member with Chapter 27’s test password, sign_in() signs a test browser in through allauth’s page, and subjects() lists the subjects of the emails sent. Every test class that signs in or asks for codes calls cache.clear() in setUp(), for a reason Step 4 explains.

The Custom Way

Django has its own password views, and many tutorials build the reset with them. This illustration is not part of the project:

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

urlpatterns = [
    path('password/reset/',
         auth_views.PasswordResetView.as_view()),
    path('password/reset/done/',
         auth_views.PasswordResetDoneView.as_view()),
    path('reset/<uidb64>/<token>/',
         auth_views.PasswordResetConfirmView.as_view()),
    path('reset/done/',
         auth_views.PasswordResetCompleteView.as_view()),
]

Each view needs a template, the reset email needs two more, and the change pages need their own pair. Django’s views do the hard part well: the same page for every address, a token that stores nothing, and the token moved out of the address bar before the page is shown. But in Otahque they would be a second set of account pages beside allauth’s, with their own templates, emails, and rate limits, and they skip members with no usable password, so Raj could never reset. A hand-made magic link would need even more: a signed, expiring token from Chapter 28, a table to make it single-use, and a way to tie it to the browser that asked. The Django Way here is to use the pages allauth already serves, decide their settings, write their words, and prove each rule with a test.

The Django Way

Step 1: Check the starting point

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

OK
Destroying test database for alias 'default'...
git status --short
git log --oneline -1
... Remember visitors: sessions and time zones

Step 2: How a reset token works

Before using allauth’s reset, watch the token idea in Django’s own generator. Save this practice file as s2_token.py beside manage.py, run it with uv run python manage.py shell -c "exec(open('s2_token.py').read())", and delete it. It makes two demo members inside a transaction it rolls back, so your rows are unchanged:

from django.contrib.auth.tokens import (
    default_token_generator,
)
from django.db import transaction

from accounts.models import User

PASSWORD = 'a-long-safe-pass-123'
tokens = default_token_generator
with transaction.atomic():
    demo = User.objects.create_user(
        'demo@example.org', PASSWORD, display_name='Demo')
    other = User.objects.create_user(
        'other@example.org', PASSWORD, display_name='Other')
    token = tokens.make_token(demo)
    when, check = token.split('-')
    print('the token:', len(when), 'characters of time,',
          len(check), 'of hash')
    print('stored anywhere: no; it is worked out again')
    print('valid for demo:', tokens.check_token(demo, token))
    print('valid for other:',
          tokens.check_token(other, token))
    demo.set_password('violet kettle harbour')
    demo.save()
    print('after a new password:',
          tokens.check_token(demo, token))
    transaction.set_rollback(True)
the token: 6 characters of time, 32 of hash
stored anywhere: no; it is worked out again
valid for demo: True
valid for other: False
after a new password: False

The token is a time and a hash, and nothing is saved anywhere. It is valid for the member it was made for, not for another, and a new password makes it fail, because the hash covers the password.

Step 3: Password rules, then a change

Tests first. Add two imports to accounts/tests.py, the first after the AnonymousUser import:

from django.contrib.auth.password_validation import (
    validate_password,
)

and the second after from django.core import mail, signing:

from django.core.cache import cache

Then add these helpers and tests at the end of the file:

NEW_PASSWORD = 'violet kettle harbour'


def member(email='sai@example.org', **flags):
    """Create a member with the test password."""
    return User.objects.create_user(
        email, PASSWORD, display_name='Sai', **flags)


def sign_in(client, email='sai@example.org',
            password=PASSWORD):
    """Sign in on allauth's page with a password."""
    return client.post(reverse('account_login'), {
        'login': email, 'password': password})


def subjects():
    """Return the subjects of the emails sent so far."""
    return [message.subject for message in mail.outbox]


class PasswordRuleTests(SimpleTestCase):
    """Passwords need at least 15 characters."""

    def test_fourteen_characters_are_refused(self):
        with self.assertRaisesMessage(
                ValidationError, 'at least 15 characters'):
            validate_password('harbour kettle')

    def test_fifteen_characters_are_accepted(self):
        validate_password('harbour kettles')


class PasswordChangeTests(TestCase):
    """Changing a password; other browsers sign out."""

    def setUp(self):
        cache.clear()
        self.sai = member()
        sign_in(self.client)
        mail.outbox.clear()

    def change(self, current):
        """Post the change form, giving current."""
        return self.client.post(
            reverse('account_change_password'), {
                'oldpassword': current,
                'password1': NEW_PASSWORD,
                'password2': NEW_PASSWORD})

    def test_wrong_current_password_is_refused(self):
        response = self.change('not my password')
        self.assertContains(
            response, 'Please type your current password.')
        self.sai.refresh_from_db()
        self.assertTrue(self.sai.check_password(PASSWORD))

    def test_other_browsers_are_signed_out(self):
        laptop = Client()
        sign_in(laptop)
        self.change(PASSWORD)
        profile = reverse('accounts:profile')
        self.assertEqual(
            self.client.get(profile).status_code, 200)
        self.assertEqual(
            laptop.get(profile).status_code, 302)
uv run python manage.py test accounts -k Password
Found 4 test(s).
Creating test database for alias 'default'...
...
AssertionError: ValidationError not raised
Ran 4 tests in ...s

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

-k Password runs every test whose class or method name contains “Password”, which so far means the two new classes.

Only the 14-character password fails: Django still accepts eight characters. The change tests pass already, because allauth’s change page checks the current password and Django ends the other sessions. In config/settings.py, give the length check its option:

            'MinimumLengthValidator'
        ),
        # NIST SP 800-63B-4: 15 for a password used alone.
        'OPTIONS': {'min_length': 15},
    },

Only the comment and the 'OPTIONS' line are new; they sit inside the entry, before its closing },.

uv run python manage.py test accounts -k Password
Found 4 test(s).
Creating test database for alias 'default'...
...
Ran 4 tests in ...s

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

Try the change page: sign in at http://127.0.0.1:8000/accounts/login/, open http://127.0.0.1:8000/accounts/password/change/, and type a 14-character new password. The page says “This password is too short. It must contain at least 15 characters.” Choose a longer one, then try the profile page in another browser where you were signed in: it asks you to sign in again.

Step 4: A reset that reveals nothing, for one hour

Tests first. The reset tests read the link from the email and move the clock, so add import re after import base64, add timedelta to the datetime import, and add this after the password_validation import from Step 3:

from django.contrib.auth.tokens import (
    PasswordResetTokenGenerator,
)

Then add at the end of the file:

LINK = re.compile(
    r'http://testserver(/accounts/password/reset/key/\S+/)')


class ResetCase(TestCase):
    """A member, Sai, and helpers for password resets."""

    def setUp(self):
        cache.clear()
        self.sai = member()
        member('old@example.org', is_active=False)

    def ask(self, email='sai@example.org'):
        """Ask for a reset email for email."""
        mail.outbox.clear()
        return self.client.post(
            reverse('account_reset_password'),
            {'email': email})

    def link(self):
        """Return the reset link in the first email."""
        return LINK.search(mail.outbox[0].body).group(1)

    def set_new_password(self, client, link):
        """Follow link and set the new password."""
        # The key moves from the address into the session.
        page = client.get(link)
        return client.post(page.url, {
            'password1': NEW_PASSWORD,
            'password2': NEW_PASSWORD})


class ResetTests(ResetCase):
    """Resets: the same page for all, one-hour links."""

    def test_every_address_gets_the_same_page(self):
        done = reverse('account_reset_password_done')
        for email in ('sai@example.org',
                      'nobody@example.org',
                      'old@example.org'):
            self.assertRedirects(self.ask(email), done)

    def test_only_a_member_gets_an_email(self):
        self.ask()
        self.assertEqual(len(mail.outbox), 1)
        for email in ('nobody@example.org',
                      'old@example.org'):
            self.ask(email)
            self.assertEqual(mail.outbox, [])

    def test_the_link_works_once(self):
        self.ask()
        link = self.link()
        self.assertRedirects(
            self.set_new_password(self.client, link),
            reverse('account_reset_password_from_key_done'))
        response = Client().get(link, follow=True)
        self.assertTrue(response.context['token_fail'])

    def test_the_link_lasts_one_hour(self):
        self.ask()
        link = self.link()
        for minutes, fails in ((59, False), (61, True)):
            later = (datetime.now()
                     + timedelta(minutes=minutes))
            with mock.patch.object(
                    PasswordResetTokenGenerator, '_now',
                    return_value=later):
                response = Client().get(link, follow=True)
            failed = response.context.get('token_fail')
            self.assertEqual(bool(failed), fails)

    def test_a_reset_does_not_sign_in(self):
        self.ask()
        self.set_new_password(self.client, self.link())
        self.assertNotIn(
            '_auth_user_id', self.client.session)
        self.sai.refresh_from_db()
        self.assertFalse(self.sai.check_password(PASSWORD))
        sign_in(self.client, password=NEW_PASSWORD)
        self.assertIn('_auth_user_id', self.client.session)

ResetCase holds the setup and helpers; ResetTests holds this step’s tests, and Steps 5 and 12 reuse the case. set_new_password() opens the link, which answers with a redirect to an address without the token, then posts the new password there.

uv run python manage.py test accounts.tests.ResetTests
Found 5 test(s).
Creating test database for alias 'default'...
...
AssertionError: False != True
Ran 5 tests in ...s

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

Two fail: an unknown address and an inactive one each receive allauth’s “Unknown Account” email, and a link is still accepted after 61 minutes. At the end of config/settings.py, add:

# Passwords, sign-in codes, and two-factor sign-in
# (Chapter 29). See docs/design/passwords-and-two-factor.md.

# A reset link works for one hour (Django: three days), and
# an address without an account gets no email.
PASSWORD_RESET_TIMEOUT = 60 * 60
ACCOUNT_EMAIL_UNKNOWN_ACCOUNTS = False
uv run python manage.py test accounts.tests.ResetTests
Found 5 test(s).
Creating test database for alias 'default'...
...
Ran 5 tests in ...s

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

Common Error: rate limits that leak between tests

allauth limits reset requests to five a minute for each address, and keeps the count in Django’s cache. The local cache lives in memory for the whole test run, and Django does not empty it between tests. A test class without cache.clear() in setUp() passes when run alone, then fails in the full run with “429 != 302”, because earlier tests already used the address’s five requests. Clear the cache in setUp() of every test class that signs in, resets, or asks for codes.

Step 5: Otahque’s emails, and a notice for each change

Run the server and ask for a reset for your own member at http://127.0.0.1:8000/accounts/password/reset/: the email appears in the terminal that runs the server, starting “Hello from 127.0.0.1:8000!”, with the subject “[127.0.0.1:8000] Password Reset Email”: allauth names the site after the address in the browser. Tests first, at the end of accounts/tests.py:

class AccountEmailTests(ResetCase):
    """Otahque's reset email and its change notices."""

    def test_the_reset_email_is_otahques(self):
        self.ask()
        self.assertEqual(
            subjects(), ['[Otahque] Password Reset Email'])
        body = mail.outbox[0].body
        self.assertIn('Hello from Otahque.', body)
        self.assertIn('one hour', body)
        self.assertNotIn('testserver!', body)

    def test_a_change_sends_a_notice(self):
        sign_in(self.client)
        mail.outbox.clear()
        self.client.post(
            reverse('account_change_password'), {
            'oldpassword': PASSWORD,
            'password1': NEW_PASSWORD,
            'password2': NEW_PASSWORD})
        self.assertEqual(
            subjects(), ['[Otahque] Password Changed'])
        self.assertIn('A notice about your Otahque account',
                      mail.outbox[0].body)

    def test_a_reset_sends_a_notice(self):
        self.ask()
        link = self.link()
        mail.outbox.clear()
        self.set_new_password(self.client, link)
        self.assertEqual(
            subjects(), ['[Otahque] Password Reset'])
uv run python manage.py test accounts.tests.AccountEmailTests
Found 3 test(s).
Creating test database for alias 'default'...
...
AssertionError: Lists differ: [] != ['[Otahque] Password
    Changed']
AssertionError: Lists differ: [] != ['[Otahque] Password
    Reset']
Ran 3 tests in ...s

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

Add the subject prefix and the notices, as a new block at the end of config/settings.py:

# Otahque's subject line, and a notice when a password, an
# email address, or two-factor sign-in changes.
ACCOUNT_EMAIL_SUBJECT_PREFIX = '[Otahque] '
ACCOUNT_EMAIL_NOTIFICATIONS = True

Every allauth email extends one template, account/email/base_message.txt, and every notice extends account/email/base_notification.txt. Overriding those two, and the reset email itself, puts Otahque’s words in all of them. Django finds templates in the project’s templates/ folder before allauth’s, as Chapter 27’s overrides showed. Create templates/account/email/base_message.txt:

{% autoescape off %}Hello from Otahque.

{% block content %}{% endblock content %}

-- 
Otahque, community events
{% endautoescape %}

templates/account/email/base_notification.txt, whose {{ ip }}, {{ user_agent }}, and {{ timestamp }} allauth fills in:

{% extends "account/email/base_message.txt" %}

{% block content %}A notice about your Otahque account:

{% block notification_message %}
{% endblock notification_message %}

If this was not you, reset your password now and turn on
two-factor sign-in from your profile. The change came
from:

- IP address: {{ ip }}
- Browser: {{ user_agent }}
- Time (UTC): {{ timestamp }}
{% endblock content %}

and templates/account/email/password_reset_key_message.txt:

{% extends "account/email/base_message.txt" %}

{% block content %}Someone asked to reset the password of
your Otahque account. If it was you, open this link within
one hour and choose a new password:

{{ password_reset_url }}

The link works once. If you did not ask, ignore this email;
your password stays as it is.
{% endblock content %}
uv run python manage.py test accounts.tests.AccountEmailTests
Found 3 test(s).
Creating test database for alias 'default'...
...
Ran 3 tests in ...s

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

Common Error: a reset link broken in the terminal

The console shows each email as it would travel, in a form called quoted-printable, where a line longer than 76 characters is split with = at the end. The reset link is longer than that, so it appears on two lines, the first ending in =. Copied as it stands, the link does not work. Join the two lines and remove the = before opening it. A mail program does this by itself, so real emails from Chapter 43 show the link whole.

autoescape off in the base message matters: these are plain-text emails, and without it Django would write &amp; for every & in a link. Check the behaviour in the shell with a practice file, l1_reset.py, which asks for a reset for a member and for an unknown address in a transaction it rolls back, and prints the answer, the page it leads to, and the number of emails sent. The interview’s L1 uses it too:

from django.core import mail
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():
    User.objects.create_user('demo@example.org',
                             'a-long-safe-pass-123',
                             display_name='Demo')
    for email in ('demo@example.org', 'nobody@example.org'):
        mail.outbox.clear()
        page = Client().post('/accounts/password/reset/',
                             {'email': email})
        print(f'{email:19}', page.status_code, page.url,
              len(mail.outbox))
    transaction.set_rollback(True)
demo@example.org    302 /accounts/password/reset/done/ 1
nobody@example.org  302 /accounts/password/reset/done/ 0

Step 6: Set a password

Raj has no password, so the profile should offer to set one where Sai’s offers to change it. Tests first, at the end of accounts/tests.py:

class SetPasswordTests(TestCase):
    """Members without a password may set one."""

    def setUp(self):
        self.raj = User.objects.create_user(
            'raj@example.org', None, display_name='Raj')

    def test_profile_offers_change_or_set(self):
        self.client.force_login(member())
        page = self.client.get(reverse('accounts:profile'))
        self.assertContains(page, 'Change password')
        self.assertNotContains(page, 'Set a password')
        self.client.force_login(self.raj)
        page = self.client.get(reverse('accounts:profile'))
        self.assertContains(page, 'Set a password')

    def test_a_member_without_one_can_set_a_password(self):
        self.assertFalse(self.raj.has_usable_password())
        self.client.force_login(self.raj)
        self.client.post(reverse('account_set_password'), {
            'password1': NEW_PASSWORD,
            'password2': NEW_PASSWORD})
        self.raj.refresh_from_db()
        self.assertTrue(
            self.raj.check_password(NEW_PASSWORD))
        self.assertEqual(
            subjects(), ['[Otahque] Password Set'])

create_user() with None as the password makes an unusable one, as a sign-up through GitHub does.

uv run python manage.py test accounts.tests.SetPasswordTests
Found 2 test(s).
Creating test database for alias 'default'...
...
AssertionError: False is not true : Couldn't find 'Change
    password' in the following response
Ran 2 tests in ...s

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

Setting already works, because allauth serves the page; only the profile’s link is missing. In accounts/templates/accounts/profile.html, replace the paragraph of links from Chapter 27 with an “Account security” list:

  <h2 class="mt-8">Account security</h2>
  <ul class="space-y-2">
    <li>
      {% if user.has_usable_password %}
        <a href="{% url 'account_change_password' %}">
          Change password</a>
      {% else %}
        You have no password yet.
        <a href="{% url 'account_set_password' %}">
          Set a password</a>
      {% endif %}
    </li>
    <li><a href="{% url 'account_email' %}">
      Email addresses</a></li>
    <li><a href="{% url 'socialaccount_connections' %}">
      Connected accounts</a></li>
  </ul>

user.has_usable_password is a method; Django’s templates call methods that take no arguments, so no brackets are written.

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

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

Step 7: Sign in with an emailed code

Tests first, at the end of accounts/tests.py. CODE finds the code in the email: four letters or digits, a dash, and four more, alone on a line:

CODE = re.compile(r'^([A-Z0-9]{4}-[A-Z0-9]{4})$', re.M)


class CodeSignInTests(TestCase):
    """Signing in with a code sent by email."""

    def setUp(self):
        cache.clear()
        self.sai = member()

    def ask(self, client, email='sai@example.org'):
        """Ask for a sign-in code for email."""
        mail.outbox.clear()
        return client.post(
            reverse('account_request_login_code'),
            {'email': email})

    def code(self):
        """Return the code in the first email."""
        return CODE.search(mail.outbox[0].body).group(1)

    def confirm(self, client, code):
        """Post code on the confirm-code page."""
        return client.post(
            reverse('account_confirm_login_code'),
            {'code': code})

    def test_the_sign_in_page_offers_a_code(self):
        page = self.client.get(reverse('account_login'))
        self.assertContains(
            page, reverse('account_request_login_code'))

    def test_a_code_signs_in_once(self):
        self.ask(self.client)
        self.assertEqual(
            subjects(), ['[Otahque] Sign-In Code'])
        self.assertIn('ten minutes', mail.outbox[0].body)
        code = self.code()
        self.confirm(self.client, code)
        self.assertIn('_auth_user_id', self.client.session)
        self.client.post(reverse('account_logout'))
        self.confirm(self.client, code)
        self.assertNotIn(
            '_auth_user_id', self.client.session)

    def test_only_the_asking_browser_can_use_it(self):
        self.ask(self.client)
        other = Client()
        self.confirm(other, self.code())
        self.assertNotIn('_auth_user_id', other.session)

    def test_three_wrong_codes_discard_it(self):
        self.ask(self.client)
        code = self.code()
        for _ in range(3):
            self.confirm(self.client, 'ZZZZ-ZZZZ')
        self.confirm(self.client, code)
        self.assertNotIn(
            '_auth_user_id', self.client.session)

    def test_the_code_lasts_ten_minutes(self):
        for minutes, works in ((9, True), (11, False)):
            client = Client()
            self.ask(client)
            later = time.time() + minutes * 60
            with mock.patch('time.time', return_value=later):
                self.confirm(client, self.code())
            self.assertEqual(
                '_auth_user_id' in client.session, works)

    def test_an_unknown_address_gets_no_email(self):
        response = self.ask(
            self.client, 'nobody@example.org')
        self.assertRedirects(
            response, reverse('account_confirm_login_code'),
            fetch_redirect_response=False)
        self.assertEqual(mail.outbox, [])

mock.patch('time.time', ...) makes the clock read nine, then eleven, minutes later while the code is typed, because allauth measures the code’s age with time.time().

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

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

All six end in errors: each is a NoReverseMatch, “Reverse for ’account_request_login_code’ not found”, because the code pages do not exist yet. allauth adds their addresses only when the setting is on. Add this block at the end of config/settings.py:

# Sign in with a code sent by email, typed in the same
# browser; it works for ten minutes.
ACCOUNT_LOGIN_BY_CODE_ENABLED = True
ACCOUNT_LOGIN_BY_CODE_TIMEOUT = 10 * 60

and Otahque’s words for the code email, templates/account/email/login_code_message.txt:

{% extends "account/email/base_message.txt" %}

{% block content %}Your Otahque sign-in code:

{{ code }}

Type it in the browser window where you asked for it,
within ten minutes. It does not work anywhere else.

If you did not ask, ignore this email; nobody can sign in
without the code.
{% endblock content %}
uv run python manage.py test accounts.tests.CodeSignInTests
Found 6 test(s).
Creating test database for alias 'default'...
...
Ran 6 tests in ...s

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

Common Error: turning the code pages on inside one test

A test decorated with @override_settings(ACCOUNT_LOGIN_BY_CODE_ENABLED=True) still fails with NoReverseMatch: Reverse for 'account_request_login_code' not found. allauth reads the setting once, when Django first loads the addresses, and a test cannot add addresses afterwards. Turn the feature on in settings.py, as above, and test the setting the project really runs with.

The sign-in page now has a “Send me a sign-in code” link. Restart the server, choose it, type your member’s address, and copy the code from the terminal into the same window. Then try the same code in a private window: it is refused. The practice file l3_code.py shows the same thing with a laptop and a phone, and the interview’s L3 uses it:

import re

from django.core import mail
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():
    User.objects.create_user('demo@example.org',
                             'a-long-safe-pass-123',
                             display_name='Demo')
    laptop, phone = Client(), Client()
    laptop.post('/accounts/login/code/',
                {'email': 'demo@example.org'})
    body = mail.outbox[0].body
    code = re.search(r'^\w{4}-\w{4}$', body, re.M).group()
    print('a link in the email:', 'http' in body)
    phone.post('/accounts/login/code/confirm/',
               {'code': code})
    print('phone signed in:',
          '_auth_user_id' in phone.session)
    laptop.post('/accounts/login/code/confirm/',
                {'code': code})
    print('laptop signed in:',
          '_auth_user_id' in laptop.session)
    transaction.set_rollback(True)
a link in the email: False
phone signed in: False
laptop signed in: True

Step 8: Add allauth’s two-factor module

The module needs allauth’s mfa extra, which adds the qrcode package, to draw the QR code, and fido2, used for passkeys. Add it with the same pin as Chapter 27:

uv add "django-allauth[socialaccount,mfa]==65.22.1"
 + colorama==0.4.6
 + fido2==2.2.1
 + qrcode==8.2

colorama comes with qrcode on Windows only; on macOS and Linux the list is two packages. uv writes the extra into pyproject.toml and uv.lock. In config/settings.py, add the app at the end of INSTALLED_APPS, after the GitHub provider:

    'allauth.mfa',

and the types and the name the authenticator app shows, as a new block at the end:

# Two-factor sign-in: an authenticator app, recovery codes.
MFA_SUPPORTED_TYPES = ['totp', 'recovery_codes']
MFA_TOTP_ISSUER = 'Otahque'

The module stores each member’s authenticators in a table of its own, so apply its migrations:

uv run python manage.py migrate
Operations to perform:
  Apply all migrations: account, accounts, admin, auth,
    contenttypes, events, mfa, registrations, sessions,
    socialaccount
Running migrations:
  Applying mfa.0001_initial... OK
  Applying mfa.0002_authenticator_timestamps... OK
  Applying mfa.0003_authenticator_type_uniq... OK
uv run python manage.py check
uv run python manage.py test
Found 244 test(s).
Creating test database for alias 'default'...
...
Ran 244 tests in ...s

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

Common Error: no such table: mfa_authenticator

After adding 'allauth.mfa' without running migrate, the profile page and every sign-in fail with OperationalError: no such table: mfa_authenticator, because allauth looks up each member’s authenticators. The tests still pass, since they build their own database from the migrations. Run uv run python manage.py migrate; it only adds tables, so no data is lost.

Step 9: Turn on an authenticator app

Tests first. They import allauth’s model and its TOTP functions, which exist only now that the app is installed. Add after the request_context import in accounts/tests.py:

from allauth.mfa.models import Authenticator
from allauth.mfa.totp.internal import auth as totp

and at the end of the file:

def code_at(secret, moment):
    """Return the authenticator app's code at moment."""
    counter = int(moment) // 30
    return totp.format_hotp_value(
        totp.hotp_value(secret, counter))


def turn_on_totp(client, at=None):
    """Turn on an authenticator app, as a member does.

    The code is typed at moment `at` (default: now).
    """
    page = client.get(reverse('mfa_activate_totp'))
    if page.status_code == 302:  # the password, again
        client.post(page.url, {'password': PASSWORD})
        page = client.get(reverse('mfa_activate_totp'))
    secret = page.context['form'].secret
    moment = time.time() if at is None else at
    with mock.patch('time.time', return_value=moment):
        client.post(reverse('mfa_activate_totp'),
                    {'code': code_at(secret, moment)})
    return secret


def confirmed(email='sai@example.org', **flags):
    """Create a member whose email address is verified."""
    user = member(email, **flags)
    EmailAddress.objects.create(
        user=user, email=email, verified=True, primary=True)
    return user


class TwoFactorCase(TestCase):
    """Helpers for members with an authenticator app."""

    def setUp(self):
        cache.clear()

    def two_factor_on(self):
        """Give Sai two-factor sign-in; sign out again."""
        sai = confirmed()
        sign_in(self.client)
        secret = turn_on_totp(self.client)
        self.client.post(reverse('account_logout'))
        return sai, secret

    def second_factor(self, client, code, at=None):
        """Type a code at moment `at` (default: 31 s on)."""
        moment = time.time() + 31 if at is None else at
        with mock.patch('time.time', return_value=moment):
            client.post(reverse('mfa_authenticate'),
                        {'code': code})
        return '_auth_user_id' in client.session


class TwoFactorTests(TwoFactorCase):
    """Turning on an authenticator app."""

    def test_turning_it_on_asks_for_the_password(self):
        confirmed()
        sign_in(self.client)
        page = self.client.get(reverse('mfa_activate_totp'))
        self.assertTrue(page.url.startswith(
            reverse('account_reauthenticate')))

    def test_an_unconfirmed_address_blocks_it(self):
        sai = member()
        EmailAddress.objects.create(
            user=sai, email=sai.email, verified=False,
            primary=True)
        sign_in(self.client)
        profile = self.client.get(
            reverse('accounts:profile'))
        self.assertContains(
            profile, 'Confirm your email address first')
        page = self.client.get(reverse('mfa_activate_totp'))
        self.client.post(page.url, {'password': PASSWORD})
        page = self.client.get(reverse('mfa_activate_totp'),
                               follow=True)
        self.assertContains(
            page, 'verified your email address')
        self.assertFalse(Authenticator.objects.exists())

    def test_the_profile_says_on_or_off(self):
        confirmed()
        sign_in(self.client)
        profile = reverse('accounts:profile')
        self.assertContains(self.client.get(profile),
                            '<strong>off</strong>')
        turn_on_totp(self.client)
        self.assertContains(self.client.get(profile),
                            '<strong>on</strong>')

    def test_the_secret_is_stored_as_text(self):
        sai, secret = self.two_factor_on()
        stored = Authenticator.objects.get(
            user=sai, type=Authenticator.Type.TOTP)
        # Known risk until Chapter 59 encrypts it.
        self.assertEqual(stored.data['secret'], secret)

    def test_the_activation_code_cannot_sign_in(self):
        confirmed()
        sign_in(self.client)
        now = time.time()
        secret = turn_on_totp(self.client, at=now)
        self.client.post(reverse('account_logout'))
        sign_in(self.client)
        used = code_at(secret, now)
        self.assertFalse(
            self.second_factor(self.client, used, at=now))

code_at() works out the code an authenticator app would show at a given moment, using allauth’s own functions. turn_on_totp() does what Sam does on the page: confirm the password, read the secret, and type the code. TwoFactorCase holds the shared setup for this step’s tests and the next two steps’. second_factor() types a code with the clock fixed at a given moment, 31 seconds on by default: in the next 30-second step, because the code used to turn the app on is used up.

Each test works out a moment once and passes it both to code_at() and to second_factor(). Asking the clock twice would be a mistake that shows only on a slow day: if a 30-second step ends between the two calls, the code belongs to one step and the check to the next, and the test fails for no reason in the code. The first run of this chapter’s checks failed exactly that way while the computer was busy.

uv run python manage.py test accounts.tests.TwoFactorTests
Found 5 test(s).
Creating test database for alias 'default'...
...
AssertionError: True is not false
Ran 5 tests in ...s

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

Three fail. The profile does not show the state or the warning yet, and the code used to turn the app on still signs in a second time: allauth marks codes as used at sign-in, but not on the page that turns the app on. NIST SP 800-63B-4 (3.1.4.2) says a code “SHALL” be accepted only once. allauth lets a project replace that page’s form through its MFA_FORMS setting, so Otahque’s form marks the code as allauth does. In accounts/forms.py, add these imports above from django import forms:

from allauth.mfa.models import Authenticator
from allauth.mfa.totp.forms import ActivateTOTPForm
from allauth.mfa.totp.internal.auth import TOTP

and this form at the end:

class OneUseActivateTOTPForm(ActivateTOTPForm):
    """allauth's form for turning on an authenticator app.

    The code is marked as used, so it cannot sign in again
    within its 30 seconds (NIST SP 800-63B-4).
    """

    def clean_code(self):
        """Mark the activation code as used."""
        code = super().clean_code()
        # A private allauth method: TwoFactorTests fails
        # if an upgrade changes it.
        unsaved = Authenticator(
            user=self.user, type=Authenticator.Type.TOTP,
        )
        TOTP(unsaved)._mark_code_used(code)
        return code

_mark_code_used() starts with an underscore: allauth’s own method, not promised to stay the same between versions. Calling it is a deliberate risk, so the test that proves the form also guards it, and the design note and ADR-003 say to check it on every upgrade. Tell allauth to use the form, at the end of config/settings.py:

# The code typed to turn it on is used up too (NIST).
MFA_FORMS = {
    'activate_totp':
        'accounts.forms.OneUseActivateTOTPForm',
}

The profile needs two facts the template cannot work out alone. In accounts/views.py, add the imports above from django.contrib import messages:

from allauth.account.models import EmailAddress
from allauth.mfa.models import Authenticator

and two entries in the dictionary that profile() passes to render(), after 'form': form,:

        'two_factor': Authenticator.objects.filter(
            user=user, type=Authenticator.Type.TOTP,
        ).exists(),
        'unconfirmed': EmailAddress.objects.filter(
            user=user, verified=False,
        ).exists(),

Then, in profile.html, add the two-factor line after the password line’s closing </li>:

    <li>
      <a href="{% url 'mfa_index' %}">Two-factor sign-in</a>:
      <strong>{{ two_factor|yesno:"on,off" }}</strong>
      {% if unconfirmed and not two_factor %}
        <span class="block text-sm">
          Confirm your email address first, from
          <a href="{% url 'account_email' %}">Email
            addresses</a>.</span>
      {% endif %}
    </li>

yesno:"on,off" is a Django filter that writes the first word for a true value and the second for a false one.

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

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

Common Error: importing allauth.mfa before installing it

Importing allauth.mfa.models in a view, a form, or a test before 'allauth.mfa' is in INSTALLED_APPS stops every command, check included, with ImproperlyConfigured: allauth.mfa not installed, yet its models are imported. allauth checks for this itself and says so plainly. That is why this chapter adds the app in Step 8 and imports the model in Step 9. Add the app first, then the import.

The two-factor pages use two of allauth’s display elements that Chapter 27 left alone: field, which draws a single box such as the authenticator secret or the list of recovery codes, and the links that the button element draws. With allauth’s plain versions, the secret runs into its help text and is cut off on a phone, so a member who types it into an app cannot see all of it, and the two links on the recovery codes page run together. Create templates/allauth/elements/field.html with the same fieldset classes as Otahque’s form fields:

{% load allauth %}
{{ attrs.errors }}
<div class="fieldset">
  {% if attrs.type == "checkbox" or attrs.type == "radio" %}
    <label>
      <input type="{{ attrs.type }}" id="{{ attrs.id }}"
        {% if attrs.name %}name="{{ attrs.name }}"{% endif %}
        {% if attrs.value is not None %}
          value="{{ attrs.value }}"{% endif %}
        {% if attrs.checked %}checked{% endif %}
        {% if attrs.disabled %}disabled{% endif %}>
      {% slot label %}{% endslot %}</label>
  {% else %}
    <label class="fieldset-legend" for="{{ attrs.id }}">
      {% slot label %}{% endslot %}</label>
    {% if attrs.type == "textarea" %}
      <textarea class="textarea w-full" id="{{ attrs.id }}"
        {% if attrs.rows %}rows="{{ attrs.rows }}"{% endif %}
        {% if attrs.name %}name="{{ attrs.name }}"{% endif %}
        {% if attrs.readonly %}readonly{% endif %}
        >{% slot value %}{% endslot %}</textarea>
    {% else %}
      <input class="input w-full" id="{{ attrs.id }}"
        type="{{ attrs.type }}"
        {% if attrs.name %}name="{{ attrs.name }}"{% endif %}
        {% if attrs.value is not None %}
          value="{{ attrs.value }}"{% endif %}
        {% if attrs.placeholder %}
          placeholder="{{ attrs.placeholder }}"{% endif %}
        {% if attrs.autocomplete %}
          autocomplete="{{ attrs.autocomplete }}"{% endif %}
        {% if attrs.disabled %}disabled{% endif %}
        {% if attrs.readonly %}readonly{% endif %}
        {% if attrs.required %}required{% endif %}>
    {% endif %}
  {% endif %}
  {% if slots.help_text %}
    <p class="label whitespace-normal">
      {% slot help_text %}{% endslot %}</p>
  {% endif %}
</div>

A checkbox or a radio button keeps its label beside it, as on the Email addresses page; every other box gets a label above it and the full width. In templates/allauth/elements/button.html from Chapter 27, put each link in a paragraph of its own:

{% if attrs.href %}
<p><a href="{{ attrs.href }}" class="link">
  {% slot %}{% endslot %}</a></p>
uv run python manage.py test accounts
Found 73 test(s).
Creating test database for alias 'default'...
...
Ran 73 tests in ...s

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

Now turn it on yourself. Restart the server, sign in, open your profile, and choose Two-factor sign-in. If the profile says to confirm your email address first, choose Email addresses, send the confirmation, and open the link printed in the server’s terminal. Then choose to activate the authenticator app. Otahque asks for your password again, then shows a QR code and the secret written out. Scan the code with an authenticator app on your phone, or type the secret into it, and enter the six digits it shows. Otahque then shows ten recovery codes: save them in your password manager. The profile now says on.

Step 10: Sign in with two factors

These tests prove what Figure 29.3 shows, and pass at once, because allauth adds the second step to every way of signing in. Add them at the end of accounts/tests.py:

class TwoFactorSignInTests(TwoFactorCase):
    """Signing in with a second factor."""

    def test_a_password_alone_is_not_enough(self):
        sai, secret = self.two_factor_on()
        response = sign_in(self.client)
        self.assertRedirects(
            response, reverse('mfa_authenticate'),
            fetch_redirect_response=False)
        self.assertNotIn(
            '_auth_user_id', self.client.session)
        later = time.time() + 31
        self.assertTrue(self.second_factor(
            self.client, code_at(secret, later), at=later))

    def test_a_recovery_code_works_once(self):
        sai, secret = self.two_factor_on()
        codes = Authenticator.objects.get(
            user=sai, type=Authenticator.Type.RECOVERY_CODES,
        ).wrap().get_unused_codes()
        self.assertEqual(len(codes), 10)
        sign_in(self.client)
        self.assertTrue(
            self.second_factor(self.client, codes[0]))
        other = Client()
        sign_in(other)
        self.assertFalse(self.second_factor(other, codes[0]))

    def test_a_used_code_waits_in_the_cache(self):
        sai, secret = self.two_factor_on()
        first, second, third = Client(), Client(), Client()
        for client in (first, second, third):
            sign_in(client)
        later = time.time() + 31
        code = code_at(secret, later)
        self.assertTrue(
            self.second_factor(first, code, at=later))
        self.assertFalse(
            self.second_factor(second, code, at=later))
        cache.clear()  # what a second process would see
        self.assertTrue(
            self.second_factor(third, code, at=later))

    def test_a_sign_in_code_still_asks_for_it(self):
        self.two_factor_on()
        mail.outbox.clear()
        self.client.post(
            reverse('account_request_login_code'),
            {'email': 'sai@example.org'})
        code = CODE.search(mail.outbox[0].body).group(1)
        response = self.client.post(
            reverse('account_confirm_login_code'),
            {'code': code})
        self.assertRedirects(
            response, reverse('mfa_authenticate'),
            fetch_redirect_response=False)
        self.assertNotIn(
            '_auth_user_id', self.client.session)
uv run python manage.py test accounts.tests.TwoFactorSignInTests
Found 4 test(s).
Creating test database for alias 'default'...
...
Ran 4 tests in ...s

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

test_a_used_code_waits_in_the_cache shows where allauth remembers used codes. After cache.clear(), the same code works again: a second server process, with a cache of its own, would see exactly that. One process is enough on your computer; Chapter 57 moves Otahque to a cache all processes share, before Chapter 62 starts several.

Under the Hood: what the database holds

Each member’s authenticators are rows of allauth’s mfa_authenticator table. The totp row’s data holds the secret your phone was given, written out, and the recovery_codes row holds the seed the ten codes are made from; the interview’s L5 prints such a row. allauth’s adapter has two methods, encrypt() and decrypt(), that a project can replace; by default they change nothing. test_the_secret_is_stored_as_text in Step 9 records this, and Chapter 59 encrypts both with a key kept in .env, before Otahque is put online in Chapter 63. Until then, treat a copy of the database, or of a backup, as holding every member’s second factor.

Sign out, then sign in again with your password: Otahque asks for an authenticator code. Type the one your phone shows now. Then sign out, sign in in a private window, and use one of your recovery codes; the profile’s two-factor page shows nine left.

Step 11: The admin signs in through allauth

Chapter 23’s admin has its own sign-in form, which signs staff in with Django’s ModelBackend directly: no allauth rate limits, and no second factor. Tests first, at the end of accounts/tests.py:

class AdminSignInTests(TwoFactorCase):
    """The admin sends staff to allauth's sign-in."""

    def test_the_admin_sends_staff_to_allauth(self):
        response = self.client.get(reverse('admin:login'))
        self.assertTrue(response.url.startswith(
            reverse('account_login')))

    def test_the_old_form_signs_nobody_in(self):
        member('sam@example.org', is_staff=True)
        self.client.post(reverse('admin:login'), {
            'username': 'sam@example.org',
            'password': PASSWORD})
        self.assertNotIn(
            '_auth_user_id', self.client.session)

    def test_staff_with_two_factor_give_the_code(self):
        confirmed('sam@example.org', is_staff=True)
        sign_in(self.client, 'sam@example.org')
        secret = turn_on_totp(self.client)
        self.client.post(reverse('account_logout'))
        sign_in(self.client, 'sam@example.org')
        index = reverse('admin:index')
        self.assertEqual(
            self.client.get(index).status_code, 302)
        later = time.time() + 31
        self.second_factor(
            self.client, code_at(secret, later), at=later)
        self.assertEqual(
            self.client.get(index).status_code, 200)
uv run python manage.py test accounts.tests.AdminSignInTests
Found 3 test(s).
Creating test database for alias 'default'...
...
AttributeError: 'TemplateResponse' object has no attribute
    'url'
Ran 3 tests in ...s

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

Two go wrong. The first test errors with 'TemplateResponse' object has no attribute 'url': the admin answers with its own sign-in form, a page rather than a redirect. The second fails because that form signs Sam in. The third passes already, because signing in through allauth already asks for the code. allauth provides secure_admin_login, which wraps the admin’s sign-in view: a visitor is sent to allauth’s page, and a signed-in member who is not active staff is refused. In config/urls.py, add the import at the top:

from allauth.account.decorators import secure_admin_login

and wrap the view after the two site_ lines from Chapter 23:

# Staff sign in through allauth's page, with its limits and
# two-factor sign-in; the admin's own form is never used.
admin.site.login = secure_admin_login(admin.site.login)
uv run python manage.py test accounts.tests.AdminSignInTests
Found 3 test(s).
Creating test database for alias 'default'...
...
Ran 3 tests in ...s

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

Chapter 23’s admin tests in config/tests.py still sign in on the old form. Run them:

uv run python manage.py test config
Found 8 test(s).
Creating test database for alias 'default'...
...
AssertionError: 302 != 200 : Couldn't retrieve content:
    Response code was 302 (expected 200)
Ran 8 tests in ...s

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

The three failures are the change working: the old form no longer signs anyone in. Change the tests in place, as Chapter 27 did for its sign-in tests. Remove the REFUSED text at the top of config/tests.py, which no page shows any more, and replace the sign_in() method of AdminAccessTests:

    def sign_in(self, email, **flags):
        """Create a member and sign in on allauth's page."""
        # Chapter 29: staff sign in on allauth's page.
        User.objects.create_user(
            email, PASSWORD, display_name='Test', **flags
        )
        return self.client.post(
            reverse('account_login'),
            {'login': email, 'password': PASSWORD},
        )

and the three tests that follow staff():

    def test_visitor_is_sent_to_sign_in(self):
        index = reverse('admin:index')
        self.assertRedirects(
            self.client.get(index),
            f"{reverse('admin:login')}?next={index}",
            fetch_redirect_response=False,
        )
        self.assertRedirects(
            self.client.get(index, follow=True),
            f"{reverse('account_login')}?next={index}",
        )

    def test_member_is_refused(self):
        self.sign_in('raj@example.org')
        response = self.client.get(reverse('admin:login'))
        self.assertEqual(response.status_code, 403)

    def test_inactive_staff_is_refused(self):
        self.sign_in(
            'old@example.org', is_staff=True,
            is_active=False,
        )
        self.assertNotIn(
            '_auth_user_id', self.client.session)
        response = self.client.get(reverse('admin:index'))
        self.assertEqual(response.status_code, 302)

A member who is not staff now gets a 403 page from allauth’s wrapper, and an inactive account cannot sign in at all, so the admin’s index sends it to sign in.

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

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

Open http://127.0.0.1:8000/admin/ in a private window: you arrive at Otahque’s sign-in page, not the admin’s. Sign in as Sam; if you turned on two-factor sign-in for Sam, Otahque asks for the code before the admin opens. Staff who have not turned it on still enter with a password alone until Chapter 59 requires it, and docs/design/admin.md says so.

Step 12: Logs, the design, and the commit

A last test checks that a full reset leaves neither the new password nor the token in the logs. Add import logging after import base64, and at the end of accounts/tests.py:

class SecretLogTests(ResetCase):
    """Logs never hold a password or a reset key."""

    def test_logs_hold_no_password_or_key(self):
        with self.assertLogs(level='DEBUG') as logs:
            logging.getLogger('otahque').debug('start')
            self.ask()
            link = self.link()
            self.set_new_password(self.client, link)
        text = '\n'.join(logs.output)
        self.assertNotIn(NEW_PASSWORD, text)
        self.assertNotIn(link.split('/')[-2], text)
uv run python manage.py test accounts.tests.SecretLogTests
Found 1 test(s).
Creating test database for alias 'default'...
...
Ran 1 test in ...s

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

It passes: allauth marks its password fields as sensitive, so Django’s error reports hide them, and it moves the token out of the address before the page is shown. assertLogs(level='DEBUG') captures everything any part of the project logs while the block runs; the first line logs one message itself, because the check fails if nothing at all is logged.

Write the design down. Create docs/design/passwords-and-two-factor.md:

# Passwords, sign-in codes, and two factors: design

Status: Drafted in Chapter 29, for review. Not approved.

## Passwords

- At least 15 characters (NIST SP 800-63B-4, 3.1.1.2,
  for a password used alone), not like the email or
  name, not a common password, not all digits. No
  other composition rules; no forced periodic change.
- Existing shorter passwords keep working; the rule
  applies whenever a password is chosen, changed,
  reset, or set.
- Change: the browser that changes it stays signed in;
  every other browser is signed out.
- A member with no password (a GitHub sign-up) may set
  one from the profile, or through a reset.

## Reset

- Every address gets the same page. Only a member's
  address gets an email (ACCOUNT_EMAIL_UNKNOWN_ACCOUNTS
  is False); inactive accounts get none.
- The link works once and for one hour
  (PASSWORD_RESET_TIMEOUT). A new password, a new
  address, or a sign-in ends it.
- A reset does not sign the member in (OWASP Forgot
  Password Cheat Sheet); the new password does.

## Notices

- Password changed, set, or reset; email changed;
  two-factor turned on or off: one email each, with
  the IP address, browser, and time.

## Sign-in by code

- An emailed code, eight characters, for ten minutes,
  three tries, only in the browser that asked.
- It proves control of the mailbox, as a reset email
  does: a convenience, not a second factor (NIST
  SP 800-63B-4, 3.1.3.1). Two-factor still applies
  after it.

## Two-factor sign-in

- Optional for members; required for staff from
  Chapter 59. An authenticator app (TOTP, 30-second
  codes) and ten single-use recovery codes. Passkeys
  later, after HTTPS (Chapter 63), as an optional
  extra.
- Turning it on asks for the password again and needs
  a confirmed email address.
- A code is accepted once. allauth remembers used
  codes in the cache; OneUseActivateTOTPForm also
  marks the activation code. It calls the private
  TOTP._mark_code_used(): a test fails if an upgrade
  changes it.

## Known risks

- The authenticator secret, and the seed the
  recovery codes are made from, are stored as plain
  text in mfa_authenticator. A copy of the database,
  a backup, or an export gives every member's codes.
  Exports leave the table out (Chapter 41); Chapter
  59 encrypts it before any deployment (Chapter 63).
- Used codes and rate limits live in the local-memory
  cache, one per process. Before more than one
  process, a shared cache (Chapter 57, Redis in 62).
- Until Chapter 43, a known address may answer more
  slowly than an unknown one, because only it sends
  an email.

## Admin

- The admin's sign-in page sends staff to allauth's,
  so limits and two-factor apply. Staff without
  two-factor still enter until Chapter 59.

In docs/design/admin.md, replace the “Planned (Chapters 29, 59): two-factor sign-in” item of the best-practices list with:

- Done (Chapter 29): sign-in through allauth's page
  (secure_admin_login), with its rate limits and
  two-factor sign-in for staff who turn it on.
- Planned (Chapter 59): two-factor required for every
  staff account.

In docs/adr/ADR-003-accounts-allauth.md, replace the consequence about the admin’s sign-in page with:

- The admin's own sign-in page bypassed allauth until
  Chapter 29 wrapped it with secure_admin_login.
- Chapter 29 adds the mfa extra:
  `django-allauth[socialaccount,mfa]==65.22.1`, with
  qrcode, fido2, and (on Windows) colorama.

and add this section before “## Revisit when”:

## Upgrade checklist

- Run the whole test suite before and after.
- accounts.forms.OneUseActivateTOTPForm calls allauth's
  private TOTP._mark_code_used(); TwoFactorTests must
  still pass, or remove the form if allauth now marks
  the activation code itself.

Check that the models and the migrations agree, run every test, and commit:

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

OK
Destroying test database for alias 'default'...
git add .
git status --short
git commit -m "Add password reset, codes, and two factors"
M  accounts/forms.py
M  accounts/templates/accounts/profile.html
M  accounts/tests.py
M  accounts/views.py
M  config/settings.py
M  config/tests.py
M  config/urls.py
M  docs/adr/ADR-003-accounts-allauth.md
M  docs/design/admin.md
A  docs/design/passwords-and-two-factor.md
M  pyproject.toml
A  templates/account/email/base_message.txt
A  templates/account/email/base_notification.txt
A  templates/account/email/login_code_message.txt
A  templates/account/email/password_reset_key_message.txt
M  templates/allauth/elements/button.html
A  templates/allauth/elements/field.html
M  uv.lock

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

Table 29.2 — When a step goes wrong
Symptom Likely cause Recovery
429 != 302 in the full test run only Rate limits counted across tests Add cache.clear() to the class's setUp(), as in Step 4
NoReverseMatch: account_request_login_code ACCOUNT_LOGIN_BY_CODE_ENABLED missing, or set only in a test Add the Step 7 block to settings.py
allauth.mfa not installed, yet its models are imported allauth.mfa imported before it is installed Add 'allauth.mfa' to INSTALLED_APPS, as in Step 8
no such table: mfa_authenticator The two-factor migrations not applied uv run python manage.py migrate
The authenticator app's code is always wrong The phone's clock is wrong, or the code was already used Set the phone's time automatically; wait for the next code
Lost phone and lost recovery codes No second factor left An administrator removes the member's authenticators in the shell, after checking who is asking
Reset email says "Hello from testserver!" templates/account/email/ not where Django looks Check the folder is beside manage.py, under templates/
A reset link from the terminal is refused The link copied with the = line break Join the two lines and remove the =
PAGE 003

Verify Your Work

Work through Table 29.3 from the folder that holds manage.py. For the browser rows, start the development server and keep its terminal in view: account emails are printed there. Use a private window when a row says so, so that no earlier session is sent.

Table 29.3 — Verification checklist for Chapter 29
Check Command or action Expected result
Starting point uv run python manage.py test Found 224 test(s); OK
Tests fail first Each step's new tests, before the code FAILED, or NoReverseMatch
Tests pass uv run python manage.py test Found 257 test(s); OK
No migration waiting makemigrations --check --dry-run No changes detected
Two-factor installed uv run python manage.py check No issues; mfa migrations applied
Short password Change your password to 14 characters "at least 15 characters"
Reset, unknown address /accounts/password/reset/ with nobody@example.org The same page; nothing in the terminal
Reset, your address The same page with your address One email, "[Otahque] Password Reset Email", with a link for one hour
Link used twice Open the link, set a password, open it again "Bad Token"
Notice After the reset A "Password Reset" notice in the terminal
Code sign-in Send me a sign-in code; type the code Signed in; the same code fails in a private window
Two-factor on Profile, Two-factor sign-in, activate Password asked again; QR code; ten recovery codes; profile says on
Second factor Sign out, sign in with the password "Two-Factor Authentication" page before any member page
Admin /admin/ in a private window Otahque's sign-in page, then the code, then the admin
Phone width Device toolbar, 390 px No sideways scroll on the profile and two-factor pages
Committed git status --short No output
Not verified macOS, Linux, WSL; Firefox, Safari; a real phone's app Readers on those systems

The commands were checked in Windows PowerShell 5.1 and Git Bash, from a copy of the Chapter 28 checkpoint, with each listing applied in the order printed. The browser rows were walked through in Microsoft Edge at 390 px and 1280 px, with the authenticator codes worked out by a script from the secret Otahque showed, in place of a phone.

PAGE 004

Checkpoint: Quiz and Challenge

Quiz

Que. 3 Why does Otahque ask for 15 characters, when Django’s default is eight?

Flip to check your answerFold answer back

Answer. NIST SP 800-63B-4 asks for at least 15 characters when a password is used alone, and allows eight only when a second factor is always required. Two-factor sign-in is optional for members, so for most of them the password is the only factor.

Que. 4 Sai changes her password on her laptop. What happens to her session on her phone, and why?

Flip to check your answerFold answer back

Answer. The phone is signed out. Each session holds a value worked out from the password hash; the new hash no longer matches the phone’s session, so Django treats it as signed out. The laptop’s session is updated and stays signed in.

Que. 5 Why does the reset page answer the same way for an address that has no account?

Flip to check your answerFold answer back

Answer. So that nobody can learn who has an account by trying addresses. Only a member’s address gets an email; the page itself says the same thing to everyone.

Que. 6 An emailed sign-in code and a password reset both reach Sai’s mailbox. Why is the code no weaker than the reset?

Flip to check your answerFold answer back

Answer. Whoever controls the mailbox can already reset the password, so the code opens no new way in. It also works only in the browser that asked, for ten minutes, with three tries. Neither is a second factor, which is why two-factor sign-in still asks for the app’s code after it.

Que. 7 Where does allauth remember that an authenticator code was used, and what changes when Otahque runs two server processes?

Flip to check your answerFold answer back

Answer. In Django’s cache, which is local memory inside one process. With two processes, each has its own memory, so a code used on one could be accepted once on the other. Chapter 57 moves Otahque to a shared cache before Chapter 62 starts several processes.

Mini-Challenge

Que. 8 Sai opens her reset link, chooses a new password, and then, from the same email, clicks the link again. Predict what she sees, and explain it with Step 2. Then check with l2_link.py below, run with uv run python manage.py shell -c "exec(open('l2_link.py').read())".

Flip to check your answerFold answer back

Answer. She sees “Bad Token”: the link has already been used. The token was worked out from her old password hash; the new password changes the hash, so the same calculation no longer matches. Nothing was stored, so nothing needed deleting. The file undoes its work, so your rows are unchanged:

import re

from django.core import mail
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()
NEW = 'violet kettle harbour'
with transaction.atomic():
    User.objects.create_user('demo@example.org',
                             'a-long-safe-pass-123',
                             display_name='Demo')
    web = Client()
    web.post('/accounts/password/reset/',
             {'email': 'demo@example.org'})
    link = re.search(r'testserver(\S+/key/\S+/)',
                     mail.outbox[0].body).group(1)
    page = web.get(link)
    print('first click ends:', page.url.split('/')[-2])
    done = web.post(page.url, {'password1': NEW,
                               'password2': NEW})
    print('new password saved:', done.url)
    again = Client().get(link, follow=True)
    print('second click, token_fail:',
          again.context['token_fail'])
    print('says "already been used":',
          'already been used' in again.content.decode())
    transaction.set_rollback(True)
first click ends: 5-set-password
new password saved: /accounts/password/reset/key/done/
second click, token_fail: True
says "already been used": True

The first click goes to an address ending set-password, after the member’s id: allauth moved the token into the session, so it is not in the address of the page where the password is typed.

What We Learned

  • A password proves knowledge of a secret; Django keeps only its hash, and its rules come from AUTH_PASSWORD_VALIDATORS.
  • NIST asks for length, not mixed symbols: at least 15 characters for a password used alone, checked against common passwords, never forced to change without a reason.
  • Changing a password signs out every other session, because each session holds a value from the password hash.
  • A reset page answers every address the same way; only a member’s address gets an email.
  • A reset token stores nothing: it is worked out from data that using it changes, and it expires after PASSWORD_RESET_TIMEOUT.
  • A notice for every change tells a member about a change they did not make.
  • A sign-in code is safer than a sign-in link because it works only in the browser that asked; neither is a second factor.
  • TOTP codes come from a shared secret and the time, in 30-second steps; each is accepted once, and recovery codes cover a lost phone.
  • allauth’s pages, Django’s sessions, the cache, and the database each hold a part of these checks; the plain-text secret and the per-process cache are named risks with chapters to close them.

Key terms

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

Table 29.4 — Key terms from Chapter 29
Term Meaning
Password validator A check Django runs on every new password, set in AUTH_PASSWORD_VALIDATORS.
Account enumeration Learning which addresses have accounts from the way a site answers.
Reset token A value in a reset link, worked out from the member's data, that works once and expires.
Notice An email telling a member that something about their account changed.
Sign-in code A one-time code, sent by email, typed in the browser that asked for it.
Factor One kind of proof: something you know, such as a password, or have, such as a phone.
Two-factor sign-in Signing in with two different kinds of proof.
TOTP A time-based one-time password: a code from a shared secret and the time.
Authenticator app A phone app that shows TOTP codes.
Recovery code A single-use code that replaces the authenticator app once.
Re-authentication Asking for the password again before a sensitive change.
Cache A fast store in memory, used here for rate limits and used codes.

Readiness checkpoint: you are ready for Chapter 30 when all 257 tests pass, makemigrations --check --dry-run prints No changes detected, a 14-character password is refused, the reset page answers every address the same way, a used reset link shows “Bad Token”, a sign-in code works only in the browser that asked, your profile shows two-factor sign-in on, the admin sends you to Otahque’s sign-in page, and the commit is made.

Git Commit

Your Chapter 29 work was committed in Step 12, with the message “Add password reset, codes, and two factors”. It holds the 15-character rule, the reset, email, code, and two-factor settings, the mfa extra in pyproject.toml and uv.lock, four email templates, allauth’s field element and the link branch of its button element in Otahque’s style, the profile’s account security list and its view, OneUseActivateTOTPForm, the admin’s wrapped sign-in, three of Chapter 23’s admin tests changed in place, the design note, the admin and ADR-003 updates, and thirty-three new tests.

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 57 and 59. They are extension questions, not a gate to the next chapter.

L1 (Junior): What does a password reset prove, and why does its page look the same for every address?

What the interviewer is testing: Do you know what the email proves, and can you name account enumeration?

Flip to check your answerFold answer back

Perfect answer: A reset proves only that the person can read the account’s mailbox: the link reaches nobody else. So it is exactly as strong as the email account, which is why the link must work once and expire. The page must not say whether an address has an account, or anyone could learn who uses the site by trying addresses, which is called account enumeration. Otahque shows the same page for every address and sends an email only to a member’s address, and a test proves both.

Behind the scenes:

member's address  -> 302 to done page; 1 email
unknown address   -> 302 to done page; 0 emails

Code proof: Step 5’s l1_reset.py:

demo@example.org    302 /accounts/password/reset/done/ 1
nobody@example.org  302 /accounts/password/reset/done/ 0

Common mistakes:

  • Showing “no account with that address”, or a different page for it.
  • Sending a new password by email instead of a link.
  • Making the link work for days, or more than once.

Follow-up the interviewer might ask:

  • “How would you keep the answer time the same once real email is sent?”
  • “What should happen to the member’s other sessions after a reset?”

L2 (Mid-Level): Sai uses her reset link, then clicks it again. Predict what she sees.

What the interviewer is testing: Can you explain why a token stops working when nothing about it is stored?

Flip to check your answerFold answer back
Five numbered steps. Sai opens the reset link and saves a new password. The token is worked out from her password and last sign-in. The new password changes what the token is checked against. A second click finds a different value: Bad Token. Ask for a new link; nothing is stored to delete.
Figure 29.5 — A second click on a used link.

Perfect answer: She sees “Bad Token: the password reset link was invalid, possibly because it has already been used”. The token is a time and a hash worked out, with the secret key, from her id, the time, her password hash, and her last sign-in. When she saves a new password, the hash changes, so checking the old token gives a different answer. Nothing was stored, so nothing needed deleting; and after an hour, the time inside the token fails it anyway.

Behind the scenes:

first click   -> redirect to .../set-password/
new password  -> saved; password hash changes
second click  -> token_fail: "Bad Token"

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

first click ends: 5-set-password
new password saved: /accounts/password/reset/key/done/
second click, token_fail: True
says "already been used": True

Common mistakes:

  • Storing tokens in a table and forgetting to delete them after use.
  • Believing a token is valid until its time runs out, however often it is used.
  • Leaving the token in the address of the page where the password is typed, where scripts and logs can see it.

Follow-up the interviewer might ask:

  • “Why does signing in also end an unused reset link?”
  • “What happens to every reset link if SECRET_KEY changes?”

L3 (Senior): A product manager asks for sign-in by magic link. Defend a code instead.

What the interviewer is testing: Can you compare two designs by what each proves and how each fails, and state a standard’s limit honestly?

Flip to check your answerFold answer back
Five numbered steps. The goal is to sign in without a password, safely. A link signs in whichever device opens it. A code works only in the browser that asked. Either proves only the mailbox, as a reset does. Offer the code; two-factor still applies after it.
Figure 29.6 — A code, not a link.

Perfect answer: A link signs in whichever device opens it: the member asks on a laptop and opens the email on a phone, mail scanners open links to check them, and a forwarded email still works. A code is typed into the browser that asked, which remembers the request in its session, so the same code anywhere else is refused; Otahque’s lasts ten minutes and allows three tries. Neither is a second factor: NIST says email “SHALL NOT be used for out-of-band authentication”. But whoever reads the mailbox can already reset the password, so the code adds no new way in, and when two-factor sign-in is on, it is still asked for after the code.

Behind the scenes:

laptop asks for a code  -> code tied to its session
phone types the code    -> refused: no request there
laptop types the code   -> signed in

Code proof: Step 7’s l3_code.py:

a link in the email: False
phone signed in: False
laptop signed in: True

Common mistakes:

  • Calling an emailed code a second factor.
  • A link or code that never expires, or allows unlimited guesses.
  • Telling an unknown address that it has no account, by email or on the page.

Follow-up the interviewer might ask:

  • “How would you rate-limit code requests for one address?”
  • “When would you turn code sign-in off for staff?”

L4 (Staff): A member says their authenticator code is always wrong. Diagnose it.

What the interviewer is testing: Can you reason from how TOTP works to the likely causes, and test a time-based rule without waiting?

Flip to check your answerFold answer back
Five numbered steps. My authenticator code is always wrong. Compare the phone’s clock with the server’s. Same 30 seconds? Was this code already used? Fix the clock; never widen the window for everyone. Test with a mocked clock: now, early, late.
Figure 29.7 — A code that is always wrong.

Perfect answer: A TOTP code comes from the shared secret and the current 30-second step, so a code is wrong when the two sides disagree on either. The commonest cause is the phone’s clock: set by hand and off by more than 30 seconds, it shows the code for another step, and allauth accepts only the current one. The fix is to set the phone’s time automatically, not to widen the window for everyone; OWASP suggests recording one token’s drift instead. Next, a code typed twice within its 30 seconds is refused the second time on purpose. Last, a member who scanned an old QR code has an old secret: turning the app off and on again gives a new one, and the recovery codes cover the time in between.

Behind the scenes:

phone in step with the server -> accepted
phone 40 seconds slow          -> a step behind: refused
phone 40 seconds fast          -> a step ahead: refused

Code proof: l4_totp.py, with the clock fixed by mock.patch:

from unittest import mock

from allauth.mfa.totp.internal import auth

secret = auth.generate_totp_secret()
now = 1_800_000_000  # a fixed moment, in seconds


def code_at(moment):
    return auth.format_hotp_value(
        auth.hotp_value(secret, moment // 30))


with mock.patch('time.time', return_value=now):
    for label, moment in (('right now', now),
                          ('phone 40 s slow', now - 40),
                          ('phone 40 s fast', now + 40)):
        ok = auth.validate_totp_code(secret, code_at(moment))
        print(f'{label:16} accepted: {ok}')
right now        accepted: True
phone 40 s slow  accepted: False
phone 40 s fast  accepted: False

Common mistakes:

  • Widening the accepted window for every member to hide one wrong clock.
  • Testing time-based rules with sleep() instead of a mocked clock.
  • Resetting a member’s two-factor sign-in on request without checking who is asking.

Follow-up the interviewer might ask:

  • “How would you prove the server’s own clock is right?”
  • “What should support check before removing a member’s authenticator?”

L5 (Lead): Where should Otahque require two-factor sign-in, and how should recovery work?

What the interviewer is testing: Can you weigh security against members’ effort, plan for lost devices, and name the risks that remain?

Flip to check your answerFold answer back
Five numbered steps. The goal is a second factor where the damage would be greatest. Staff: required, Chapter 59; members: their choice. Recovery codes, each used once, for a lost phone. A notice for every change to a factor. Secrets encrypted before deployment, Chapter 59.
Figure 29.8 — Where a second factor is required.

Perfect answer: Require it where a stolen account does the most harm: staff, who can change every event in the admin, from Chapter 59. Offer it to members, whose accounts reach only their own registrations, and make it easy: a QR code, re-authentication before the change, and ten single-use recovery codes. Every change to a factor sends a notice. Support must check who is asking before removing anyone’s authenticator, or recovery becomes the easiest attack. And the remaining risks are named with dates: the secrets are plain text until Chapter 59 encrypts them, used codes live in one process’s cache until Chapter 57, and passkeys, the strongest factor, follow HTTPS in Chapter 63.

Behind the scenes:

turned on   -> 10 codes of 8 digits
one used    -> accepted once, then refused
stored      -> a seed, as plain text until Chapter 59

Code proof: l5_recovery.py makes a member’s recovery codes in a transaction it rolls back:

from allauth.mfa.models import Authenticator
from allauth.mfa.recovery_codes.internal.auth import (
    RecoveryCodes,
)
from django.db import transaction

from accounts.models import User

with transaction.atomic():
    demo = User.objects.create_user('demo@example.org',
                                    'a-long-safe-pass-123',
                                    display_name='Demo')
    codes = RecoveryCodes.activate(demo)
    unused = codes.get_unused_codes()
    print('codes:', len(unused), 'of', len(unused[0]),
          'digits')
    print('first use:', codes.validate_code(unused[0]))
    print('second use:', codes.validate_code(unused[0]))
    print('left:', len(codes.get_unused_codes()))
    row = Authenticator.objects.get(user=demo)
    print('stored:', sorted(row.data), '(no codes)')
    transaction.set_rollback(True)
codes: 10 of 8 digits
first use: True
second use: False
left: 9
stored: ['seed', 'used_mask'] (no codes)

Common mistakes:

  • Requiring two factors for everyone at once, so that members are locked out of their own registrations.
  • No recovery path except support, with no check of who is asking.
  • Treating “two-factor is on” as finished while the secrets sit in plain text.

Follow-up the interviewer might ask:

  • “How would you move every existing staff member to two-factor sign-in without locking anyone out?”
  • “Would you allow ’trust this browser for 30 days’? What would it cost?”
PAGE 006