Logins, permissions and security in Django: what the framework does for you, and the third word it leaves to you
TL;DR
Difficulty: Intermediate
Django guards the classic doors by default: CSRF tokens, template escaping, parameterised queries, clickjacking headers, host validation, PBKDF2 password hashing and validators.
- It leaves four things to you: HTTPS settings, login throttling, a second factor and a Content Security Policy. check --deploy, django axes, django otp and django csp close them.
- Django permissions have two words, a verb and a model. Your rules have a third: which one. Put it in a for_user() queryset and start every lookup there.
- Answer 403 for the verb and 404 for the row, so a guessed id reveals nothing.
- A test that visits every URL as a stranger turns a forgotten decorator into a failed build.
- Customers often need no password at all: a signed link from django.core.signing does the job.
Django ships a more complete login system than almost any framework, and it guards the classic web attacks before you write a line. Its permissions still stop one word short of your business rules. Here is where the line runs, built on a bike workshop chain's application with logins, a second factor, throttling, scoped querysets and the tests that prove them.
The question behind this chapter
"How do I handle logins, permissions and security in Django properly, and what does Django already do for me?" The question usually arrives the week the first real users are about to log in.
Django's answer is more generous than most frameworks'. It ships a complete login system, from the user model to password reset by email, and its security documentation lists protections against the classic web attacks that are on before you write a line1. And yet there is one category of protection it cannot give you, and it happens to be the category behind most real breaches. This chapter draws that line, then builds both sides of it on one application, with code for Django 5.0 and tests that prove the rules.
If you are new to the series, how a Django project is structured explains the apps, the settings and the request cycle this chapter relies on. The custom user model comes from the chapter on starting a project, and the back office permissions from the chapter on the admin.
Example: the Django version of the spike
The example is the one the whole programme uses, and it is made up. Freewheel Cycles runs six bicycle repair workshops in Limerick (freewheelcycles.example), founded by Niamh. Its developers, Aisling and Cian, built a two week spike of the core in both frameworks before choosing. This series builds the Django version of the spike, with the same models and features as the Rails series, so you can compare like for like. The matching Rails chapter is authentication, authorisation and security in Rails.
Freewheel has 38 mechanics, about 1,150 repair bookings a week and 9,000 active customers. Job cards carry before and after photos, invoices carry VAT, and the customer list carries names, phone numbers and addresses. Every request to an application like this has to answer three questions, in order:
- Who are you? Authentication: proving identity with a password, a link or a second factor.
- Which records exist for you? Scoping: the rows this person may even know about.
- What may you do with this one? Authorisation: may this person read, change or delete it.
Django answers the first question almost completely. It answers the third one halfway. The second one is yours.
Django's permissions have two words, your rules have three
Here is the idea I would put at the top of every Django security checklist, and I have not seen it framed this way in the documentation or the usual tutorials.
A Django permission is a string like repairs.change_jobcard. Read it as two words: a verb (change) and a kind of thing (jobcard). For every model, migrate creates four of these, add, change, delete and view, and you can bundle them into groups2. user.has_perm("repairs.change_jobcard") then tells you whether this person may change job cards.
Now write down a real rule from Freewheel's business: "a mechanic may change the job cards of their own workshop". That rule has three words: a verb, a kind of thing, and which one. The third word is not in Django's permission system. The documentation is explicit about it: Django's permission framework has a foundation for object permissions, but the built in ModelBackend does not implement them, and checks against a specific object always return False or an empty list3.
So a mechanic who may change job cards may, as far as Django knows, change every job card in the database. The third word is your code. And the third word is where applications break. In the 2021 edition of the OWASP Top 10, the most widely used list of web application security risks, "Broken Access Control" moved to first place, with 94% of the applications tested showing some form of it4. OWASP's first prevention advice is to deny by default, and its second is to enforce record ownership4.
My view: in a Django project, spend your security effort on the third word. Django has done serious work on the first two words and on the classic attacks. Nobody can do the third word for you, because it is a fact about your business, not about HTTP.
Example: two attacks on the Freewheel workshop board
The attack Django stops. A stranger builds a page on another site with a hidden form that posts to freewheelcycles.example/workshops/2/cards/4812/move/. If a logged in mechanic visits that page, the browser sends the form along with the mechanic's session cookie. This is cross site request forgery (CSRF). In Django it fails without anyone at Freewheel writing a line: CsrfViewMiddleware is in the generated settings, and it rejects unsafe requests that do not carry the secret token from the page Django rendered5.
The attack only Freewheel can stop. A mechanic at the Castletroy workshop opens the board at /workshops/1/board/ and changes the 1 to a 2. In the chapter on templates and htmx, the board view looked the workshop up with get_object_or_404(Workshop, pk=workshop_id), and it was protected only by login_required. Everything about the request is valid: a real login, a correct token, a genuine cookie. Django shows him the Dooradoyle board, with customers' names on the cards. OWASP calls this an insecure direct object reference4. The photo upload view from the chapter on background tasks and files has the same gap: get_object_or_404(JobCard, pk=card_id) will find any card in the database.
Both chapters said this check would come later. This is later.
What Django already does for you
Here are the doors Django guards in a new Django 5.0 project, from the security topic guide, the settings reference and the deployment checklist. The third column is the one most articles leave out: whether you get it by default.
| Protection | Guards against | On in a new Django 5.0 project? | How it gets switched off |
|---|---|---|---|
| CSRF token check on unsafe requests | Cross site request forgery | Yes, CsrfViewMiddleware is in the generated settings5 | @csrf_exempt on a view |
| Parameterised QuerySets | SQL injection | Yes1 | String formatting in raw(), extra(), RawSQL or cursor.execute() |
| Automatic escaping in templates | Cross site scripting (XSS) | Yes6 | mark_safe, the safe filter, {% autoescape off %} |
| A ModelForm must name its fields | Mass assignment of fields like is_staff | Partly: you must set fields or exclude7 | fields = "__all__", or exclude on a model that grows |
X-Frame-Options: DENY | Clickjacking | Yes, the middleware is generated and the default is DENY8 | @xframe_options_exempt |
| Host header validation | Poisoned links in password reset emails, cache poisoning | Yes, and enforced: with DEBUG = False Django refuses to serve without ALLOWED_HOSTS9 | ALLOWED_HOSTS = ["*"], or reading request.META["HTTP_HOST"] directly |
Database sessions, HttpOnly and SameSite=Lax cookies | Session theft by script, cookies on cross site requests | Yes10 | Settings |
| A new session key at login | Session fixation | Yes, login() calls cycle_key()11 | Writing your own login without login() |
| Password hashing with PBKDF2, 720,000 iterations | A leaked user table | Yes1213 | Putting a weaker hasher first in PASSWORD_HASHERS |
| Password validators | Weak and common passwords | Yes, four in the generated settings13 | Setting passwords in code with create_user(), which skips them |
nosniff, Referrer-Policy: same-origin, Cross-Origin-Opener-Policy: same-origin | Content type confusion, leaking URLs to other sites | Yes, through SecurityMiddleware10 | Settings |
| HTTPS redirect, HTTP Strict Transport Security (HSTS), secure cookies | Eavesdropping, downgrade to plain HTTP | No. The settings default to off, and check --deploy warns914 | |
| Login throttling | Password guessing | No. The documentation says so plainly1 | |
| Content Security Policy (CSP) | Injected scripts running at all | No, it needs a package | |
| Second factor | Phished or reused passwords | No, it needs a package |
Two details in that table matter more than they look.
First, the bottom four rows. HTTPS is the one that surprises people coming from Rails. The deployment checklist says any site with logins should enforce HTTPS site wide9, yet SECURE_SSL_REDIRECT, SESSION_COOKIE_SECURE and CSRF_COOKIE_SECURE all default to False, and SECURE_HSTS_SECONDS to 010. The reason is fair, forcing HTTPS is impractical in local development9, but it means a person has to switch production protection on.
Second, Django gives you a tool for exactly that gap, and it is one of its best security features: python manage.py check --deploy. It inspects your settings and warns about each production protection that is off, from HSTS to DEBUG to a secret key that still starts with django-insecure-14. With --fail-level WARNING it exits with an error, which makes it a gate in continuous integration (CI)15. I come back to it near the end.
Example: one booking form, followed through the defaults
A customer books a service on Freewheel's site. Here is what Django does on the way, without a line of security code from Aisling or Cian:
- The booking form is rendered with
{% csrf_token %}inside it, so the POST carries the secret token, and the CSRF cookie goes out withSameSite=Lax. - The customer types
<script>alert(1)</script>into the problem description, because some people do. The booking is saved with that text. - On the workshop board,
{{ booking.problem }}is escaped, so the mechanics see the characters, not a running script. - The
BookingFormnames its fields:workshop,starts_at,problem. A crafted request that addsprice=0has nowhere to go, because the form ignores fields it does not declare. Bike.objects.filter(customer__email=email)sends the address to PostgreSQL as a parameter, so' OR 1=1 --is just an address that matches nothing.- The response carries
X-Frame-Options: DENY, so no other site can frame the booking page.
Six defences, zero lines. Now the part that needs lines.
Django and Rails, door by door
Because the series runs the same application in both frameworks, here is the same comparison for a new Rails 7.1 application, from the Rails security chapter and the Rails guides1617. Neither column wins outright, and a senior developer in either community should recognise both.
| Protection | Rails 7.1, new application | Django 5.0, new project |
|---|---|---|
| CSRF tokens | On | On |
| Parameterised queries | On | On |
| Escaping in templates | On | On |
| Mass assignment | Strong parameters | ModelForm fields |
| Session storage | Encrypted cookie holds the data | Database holds the data, cookie holds a key |
| HTTPS in production | On: force_ssl is true in the generated production file | Off until set, warned by check --deploy |
| Host header validation | Development only, production needs config.hosts | Enforced as soon as DEBUG is off |
| Clickjacking header | SAMEORIGIN | DENY |
| User model and password hashing | Building blocks: has_secure_password with bcrypt | Complete user model, PBKDF2, validators |
| Login, logout and password reset screens | You build them or add a gem | Built in views |
| Permission system | None built in: Pundit, Action Policy or plain methods | Model permissions and groups, no row level |
| Login throttling | None: Rack::Attack | None: django axes |
| Content Security Policy | Configuration generated, commented out | A package: django csp |
| Encrypted columns | Active Record encryption, opt in | None built in |
| Secret keys | Encrypted credentials file | Environment variables by convention |
| Settings audit before deploy | None built in, Brakeman as a gem | check --deploy built in |
The pattern is worth naming. Django gives you more of the login system and an audit of your settings. Rails gives you more safe defaults in the production file and more built in cryptography. Both leave the third word, which records belong to whom, entirely to you.
Every hole is a named escape hatch
Because the doors are shut by default, a door can only be opened from the inside, on purpose, with something that has a name. That turns part of a security review into a search. The Rails chapter makes the same argument with Rails' names. Here are Django's.
| Escape hatch | What it switches off | What to write instead |
|---|---|---|
mark_safe(...), {{ value|safe }}, {% autoescape off %} | Escaping | Plain {{ value }}, the linebreaksbr filter, or format_html()18 |
raw(), extra(), RawSQL or cursor.execute() with f strings or % formatting | Parameterised SQL | Pass values as params, never into the string19 |
@csrf_exempt | CSRF protection | Keep it for endpoints no browser with cookies talks to, such as a signed webhook |
fields = "__all__" or exclude on a ModelForm | Field allow lists | Name every field7 |
@xframe_options_exempt | Clickjacking protection | A narrow SAMEORIGIN where a frame is truly needed8 |
ALLOWED_HOSTS = ["*"], request.META["HTTP_HOST"] | Host validation | Real host names, request.get_host()1 |
redirect(request.GET["next"]) | Safe redirects | url_has_allowed_host_and_scheme(), which Django's LoginView already uses |
get_object_or_404(Model, pk=...) in a view for logged in users | Nothing, because nothing protected it | Look up through the user's scope, as shown below |
create_user(password=...) in scripts and imports | Password validators | Call validate_password() first13 |
The documentation for raw queries could hardly be clearer. In a box of its own it says: do not use string formatting on raw queries or quote placeholders in your SQL strings19. And the reference for mark_safe points you to format_html() for building fragments of HTML18, because format_html() escapes every argument before marking the result safe.
Example: Freewheel's ten minute review before each release
Cian adds one script to the repository:
#!/usr/bin/env bash
# bin/escape_hatches: list every line that switches a Django default off.
# Each hit needs a reason. A hit is a question, not a failure.
git grep -nE 'mark_safe|\|safe|autoescape off|csrf_exempt|xframe_options_exempt|__all__|HTTP_HOST' -- '*.py' '*.html'
git grep -nE '\.(raw|extra|execute)\(f?"' -- '*.py'
git grep -nE 'RawSQL\(' -- '*.py'
git grep -nE 'get_object_or_404\([A-Z][A-Za-z]+,' -- '*/views.py'
The first run finds a template tag Cian wrote in week one:
# repairs/templatetags/cards.py, before
from django import template
from django.utils.safestring import mark_safe
register = template.Library()
@register.filter
def notes_html(notes):
# Wanted: line breaks in the mechanics' notes
return mark_safe(notes.replace("\n", "<br>"))
The notes include text customers typed into the booking form, so this filter is a stored cross site scripting hole. Aisling deletes it. Django already has a filter for exactly this job, and it escapes the text before it adds the line breaks:
<!-- repairs/templates/repairs/_card.html, after -->
<p>{{ card.notes|linebreaksbr }}</p>
The second search finds the parts report, which filters by supplier with an f string inside cursor.execute(). The fix is to pass the value as a parameter:
# parts/reports.py
from django.db import connection
def stock_by_supplier(supplier_code):
with connection.cursor() as cursor:
# The %s placeholder is filled in by the database driver, never by Python
cursor.execute(
"SELECT sku, name, stock_quantity FROM parts_part WHERE supplier_code = %s",
[supplier_code],
)
return cursor.fetchall()
The last search finds the two lookups from the board and the photo upload. They are the third word problem, and the fix is the authorisation section below. The script takes seconds. Thinking about the hits takes ten minutes.
Logins: what django.contrib.auth gives you
Authentication answers "who are you?". In Django, django.contrib.auth answers it with parts that fit together: a user model, authenticate() to check credentials, login() to store the user in the session, logout() to clear it, and class based views for every screen around them2.
Four behaviours are easy to miss:
login()gives the visitor a new session key while keeping the session data, which the sessions documentation names as the defence against session fixation11, where an attacker plants a known session id and waits for the victim to log in.logout()clears the whole session, so the next person at a shared tablet finds nothing2.- Sessions carry a hash derived from the password, and Django checks it on every request. Changing a password therefore logs that user out everywhere else, which is what you want after a phished password2.
- The default backend refuses inactive users, also when it reloads the user on each request20. When a mechanic leaves and a manager unticks "active", the next click from that person's phone lands on the login page. One caution from the documentation: the
login_requireddecorator itself does not look atis_active. The backend does2.
Django 5.0 also finished a change that tidies up logout. Logging out through a GET request was deprecated in Django 4.1 and is removed in 5.012, so LogoutView only answers POST. A link to /logout/ that any image tag or prefetching browser could trigger is no longer possible.
Example: the staff login at Freewheel
The whole set of screens comes from one line in the URL configuration, which the documentation recommends as the easiest way in2:
# freewheel/urls.py
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
# login/, logout/, password_change/, password_reset/, reset/<uidb64>/<token>/ and the "done" pages
path("staff/", include("django.contrib.auth.urls")),
path("workshops/", include("repairs.urls")),
path("my/", include("bookings.customer_urls")),
# ... the public booking pages and the admin, as in earlier chapters ...
]
# freewheel/settings.py (excerpt)
LOGIN_URL = "login"
LOGIN_REDIRECT_URL = "repairs:my_board"
LOGOUT_REDIRECT_URL = "login"
# A staff session lasts one working day, not the default two weeks
SESSION_COOKIE_AGE = 60 * 60 * 12
# A reset link lives 15 minutes, not the default three days
PASSWORD_RESET_TIMEOUT = 60 * 15
The defaults are worth knowing. SESSION_COOKIE_AGE is two weeks and PASSWORD_RESET_TIMEOUT is three days10. Both are grand for a public site where people log in rarely. For staff who sign in every morning on shared tablets, Niamh prefers shorter.
The logout button is a small form, because 5.0 only accepts POST:
<!-- templates/includes/staff_nav.html -->
<form method="post" action="{% url 'logout' %}">
{% csrf_token %}
<button type="submit">Sign out</button>
</form>
Templates for the screens live in templates/registration/, such as login.html and password_reset_form.html. Three details make the flow safer than most hand built ones:
- The login form shows the same error for an unknown username and a wrong password, so it does not tell an attacker which staff usernames exist.
- The password reset page shows the same "check your email" page whether or not the address exists. The documentation says no email is sent in that case, and the user is still redirected to the done page2.
- A reset token is built from the user's id, the password hash, the last login time, a timestamp and the email address21. When the password changes, the hash changes, so a link that has been used once stops working, and an old link in a forgotten inbox dies with it.
Passwords: PBKDF2 by default, Argon2 with one package
Django stores passwords as <algorithm>$<iterations>$<salt>$<hash>, never as the password itself13. The default algorithm is PBKDF2 with SHA256, and the number of iterations rises with every release: Django 5.0 raised it from 600,000 to 720,00012. Iterations are deliberate slowness. An attacker who steals the user table has to repeat all of that work for every guess.
The documentation names Argon2, winner of the 2015 Password Hashing Competition, as the stronger option, and explains why it is not the default: it needs a third party library13. Switching is two steps: install argon2-cffi (or django[argon2]), and put Argon2PasswordHasher first in PASSWORD_HASHERS. Keep the PBKDF2 hashers below it. Django checks existing hashes with whichever hasher made them, and upgrades each password to the preferred algorithm the next time that user logs in13. Nobody has to reset anything.
Password validators decide what a person may choose. The generated settings switch on four: similarity to the username and other attributes, a minimum length (8 by default), a list of 20,000 common passwords compiled by Royce Williams, and a check that the password is not entirely numeric13. They run in the password change and reset forms and in createsuperuser, but not in create_user(), because the documentation assumes code is written by developers, not users13. That gap matters more than it sounds, and the escape hatch table above lists it.
For the length, the guidance from the US National Institute of Standards and Technology (NIST) is a sound reference: at least 8 characters, accept at least 64, and avoid composition rules and forced periodic changes22.
Example: Freewheel's password settings
# freewheel/settings.py (excerpt)
PASSWORD_HASHERS = [
"django.contrib.auth.hashers.Argon2PasswordHasher", # new and upgraded hashes
"django.contrib.auth.hashers.PBKDF2PasswordHasher", # still checks the spike's old hashes
"django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher",
]
AUTH_PASSWORD_VALIDATORS = [
{"NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator"},
{
"NAME": "django.contrib.auth.password_validation.MinimumLengthValidator",
"OPTIONS": {"min_length": 12}, # Freewheel's choice, above NIST's minimum of 8
},
{"NAME": "django.contrib.auth.password_validation.CommonPasswordValidator"},
{"NAME": "django.contrib.auth.password_validation.NumericPasswordValidator"},
]
Niamh's first job for the new system is importing 38 mechanics from a spreadsheet. Cian's import command sets a starting password, and here the gap shows. create_user() would accept "password1". So the command validates first:
# accounts/management/commands/import_staff.py (the relevant part)
from django.contrib.auth.password_validation import validate_password
def create_staff_member(User, row, workshop):
user = User(username=row["username"], email=row["email"], workshop=workshop)
validate_password(row["password"], user=user) # raises ValidationError if weak
user.set_password(row["password"])
user.save()
return user
validate_password() runs the same validators as the forms, with the user passed in so the similarity check can compare against the username and email13. In practice the mechanics also get a reset link on day one and choose their own.
Customers do not need a password
Freewheel's 9,000 customers bring a bike in a few times a year. They want to see their bookings, the before and after photos and their invoices. If each of them had a password, Freewheel would store 9,000 password hashes, answer a steady queue of "I forgot my password", and inherit every password a customer reused from a site that was breached. The data protection principle of data minimisation points the same way: process only the personal data you need23.
A signed link to the address they booked with proves what a password would prove: that this person controls that inbox. Django has the tool built in. django.core.signing signs any small JSON value with your SECRET_KEY, and loads() refuses a value that was changed or that is older than max_age seconds24. A salt keeps signatures for one purpose from being valid for another24. One caution: a signed value is encoded, not encrypted. Anyone holding the link can decode its contents, so never put an email address or a name inside.
If you would rather use a package, django allauth added login by a one time code sent by email, which it calls "Magic Code Login", in version 0.62.0 in April 202425. For Freewheel's one flow, the standard library is enough.
Example: Freewheel's "your bookings" link
A counter on the customer makes every link revocable. Raising it by one kills every link sent so far.
# bookings/models.py (the addition)
class Customer(models.Model):
name = models.CharField(max_length=200)
email = models.EmailField(unique=True)
phone = models.CharField(max_length=30, blank=True)
link_generation = models.PositiveIntegerField(default=0) # raise by one to revoke all links
# bookings/links.py
from django.core import signing
from django.urls import reverse
from .models import Customer
SALT = "bookings.customer_link" # a link for this purpose only
MAX_AGE = 7 * 24 * 60 * 60 # seven days, in seconds
def link_for(customer):
# Only an id and a counter inside: the content is readable, so nothing personal
token = signing.dumps({"c": customer.pk, "g": customer.link_generation}, salt=SALT)
return reverse("my:open_link", args=[token])
def customer_from_token(token):
try:
data = signing.loads(token, salt=SALT, max_age=MAX_AGE)
except signing.BadSignature: # also covers SignatureExpired
return None
return Customer.objects.filter(pk=data["c"], link_generation=data["g"]).first()
# bookings/customer_views.py
from django.contrib import messages
from django.shortcuts import get_object_or_404, redirect, render
from .links import customer_from_token
from .models import Booking, Customer
def open_link(request, token):
customer = customer_from_token(token)
if customer is None:
messages.info(request, "That link has expired. Ask for a new one below.")
return redirect("my:request_link")
request.session.cycle_key() # a new session key, as login() does for staff
request.session["customer_id"] = customer.pk
return redirect("my:bookings") # the token leaves the address bar at once
def _current_customer(request):
customer_id = request.session.get("customer_id")
return Customer.objects.filter(pk=customer_id).first() if customer_id else None
def my_bookings(request):
customer = _current_customer(request)
if customer is None:
return redirect("my:request_link")
bookings = customer.bookings.select_related("bike", "workshop").order_by("-starts_at")
return render(request, "bookings/my_bookings.html", {"bookings": bookings})
def my_booking(request, pk):
customer = _current_customer(request)
if customer is None:
return redirect("my:request_link")
# Found through the customer's own bookings: someone else's id is simply not there
booking = get_object_or_404(Booking.objects.filter(customer=customer), pk=pk)
return render(request, "bookings/my_booking.html", {"booking": booking})
# bookings/customer_urls.py
from django.urls import path
from . import customer_views
app_name = "my"
urlpatterns = [
path("link/<str:token>/", customer_views.open_link, name="open_link"),
path("bookings/", customer_views.my_bookings, name="bookings"),
path("bookings/<int:pk>/", customer_views.my_booking, name="booking"),
path("new-link/", customer_views.request_link, name="request_link"),
]
The request_link view is a one field form: it takes an email address, queues the link email through Celery as set up in the files chapter, and answers "if we know that address, a link is on its way" either way. The "your bike is ready" email carries the same link, so the customer sees the after photos with one tap.
One honest limit. The token sits in the URL path, and web server access logs record paths. The redirect keeps it out of the browser history and out of Referer headers, but the server's own logs will hold it for as long as you keep them. That is a reason for the seven day expiry, and a reason to treat access logs as personal data.
A second factor for anyone who can see money
A password alone fails when it is guessed, phished or reused. A second factor means a stolen password is not enough. The usual form for staff is the time based one time password (TOTP), the six digit code an authenticator app shows, defined in the open standard RFC 6238 and used by the django otp package for its TOTP devices26.
Django 5.0 has no second factor built in, and there are three established packages:
- django otp (1.5.0 at the time of writing) provides the building blocks: devices per user, a middleware that marks a request as verified, forms, an admin site that demands a code, and
user.is_verified()26. Its README says plainly that it is stable and maintained but not seeing much new investment26. Its TOTP device also throttles itself: after each failed code, the next attempt has to wait longer27. - django two factor auth (1.16.0, February 2024) builds complete login flows with setup wizards and backup codes on top of django otp28.
- django allauth has shipped its own two factor support in the
allauth.mfaapp since version 0.56.0 in September 202325. It is the natural choice if you already use allauth for sign up or social login.
The admin chapter already put the back office behind OTPAdminSite. Freewheel's own screens need the same rule for managers and head office.
Example: managers pass a code before anything else
The plan: everyone logs in with the normal login page. If the person is in the "Workshop managers" or "Head office" group and has not yet entered a code in this session, every page sends them to a verification page until they do. django otp's own LoginView is built for this case: when the user is logged in but not verified, it asks only for the code29.
# accounts/middleware.py
from django.shortcuts import redirect
from django.urls import reverse
SECOND_FACTOR_GROUPS = {"Workshop managers", "Head office"}
def needs_second_factor(user):
return user.groups.filter(name__in=SECOND_FACTOR_GROUPS).exists()
class RequireSecondFactorMiddleware:
"""Managers and head office see nothing until they have entered a code."""
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
user = request.user
if user.is_authenticated and not user.is_verified() and needs_second_factor(user):
if request.path not in {reverse("verify"), reverse("logout")}:
return redirect("verify")
return self.get_response(request)
# freewheel/settings.py (excerpt)
INSTALLED_APPS += ["django_otp", "django_otp.plugins.otp_totp"]
MIDDLEWARE = [
# ... the generated middleware, in order ...
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django_otp.middleware.OTPMiddleware", # adds user.is_verified()
"accounts.middleware.RequireSecondFactorMiddleware", # must come after OTPMiddleware
# ...
]
# freewheel/urls.py (the addition, above the include of django.contrib.auth.urls)
from django_otp.views import LoginView as VerifyView
urlpatterns = [
path("staff/verify/", VerifyView.as_view(template_name="registration/verify.html"), name="verify"),
path("staff/", include("django.contrib.auth.urls")),
# ...
]
Each manager registers an authenticator app once, through a TOTP device that Niamh creates for them in the admin, which shows a QR code. The group lookup costs one small query per request for logged in staff. For 45 staff logins that is nothing. If it ever matters, the answer is a field on the user, not a cache.
Django does not throttle logins
The security guide says it in one sentence: "Django does not throttle requests to authenticate users."1 It suggests a plugin or a web server module. The most widely used plugin is django axes (6.4.0, March 2024). It records failed logins in the database and locks out further attempts once a limit is reached30. Its defaults protect less than people assume: three failures, a lock by IP address only, and no cool off time, so a locked address stays locked until someone resets it30.
Freewheel changes three things. It locks by username as well as by address, so many addresses still buy only a handful of guesses at one account. It allows ten failures, because cold fingers on a tablet mistype. And locks expire after an hour, so nobody rings Niamh at 7.30am on a Saturday.
Example: Freewheel's axes settings
# freewheel/settings.py (excerpt)
INSTALLED_APPS += ["axes"]
AUTHENTICATION_BACKENDS = [
"axes.backends.AxesStandaloneBackend", # must be first, says the axes documentation
"django.contrib.auth.backends.ModelBackend",
]
MIDDLEWARE += ["axes.middleware.AxesMiddleware"] # last in the list
AXES_FAILURE_LIMIT = 10
AXES_COOLOFF_TIME = 1 # hours
AXES_LOCKOUT_PARAMETERS = ["ip_address", "username"] # lock either one, independently
AXES_RESET_ON_SUCCESS = True
Each entry in AXES_LOCKOUT_PARAMETERS is its own lock, so this blocks an address that fails too often and, separately, a username that fails too often from anywhere30. Behind a load balancer, check that axes sees the visitor's address and not the balancer's: otherwise one lock shuts out every mechanic at once. The installation guide recommends the optional ipware support for resolving the client address30.
The arithmetic: how long it takes to try the common passwords
Throttles feel like protection. Arithmetic shows how much. An attacker's best first move against a login is a list of common passwords. Take the same list of 20,000 that Django's CommonPasswordValidator uses. The time to try all of them against one account is
where is the time needed in hours, is the number of passwords on the attacker's list, and is the number of guesses per hour the attacker can make against that one account. Foundations: ratios and rates
With , four situations:
- No throttle, one machine sending 5 attempts a second. That rate is my assumption for the example, and the real figure is limited mainly by how fast the server hashes. Then an hour and hours.
- Lock by address only, ten tries per address per hour, from 100 rented addresses: , so hours.
- Lock by address only, from one address: , so hours, about 83 days.
- Lock by username as well, from any number of addresses: , so hours. In practice it is longer, because axes restarts the cool off when someone keeps failing during a lock30.
Two lessons. A lock by address only is exactly as strong as the attacker is poor: it equals a lock per account against one machine, and falls apart against a hundred. And the validator and the lock work together. Freewheel's validators reject every password on that list when a mechanic chooses one through the forms, so the attacker's best list is worthless before the first guess. The lock then makes the next best list slow. Neither is enough alone.
Authorisation: groups carry the verbs, the queryset carries the rows
Now the third word. Django gives you three tools for the verb:
user.has_perm("repairs.change_jobcard"), true when the user or one of their groups holds that permission, and always true for an active superuser2.@login_requiredand@permission_requiredfor function views, andLoginRequiredMixin,PermissionRequiredMixinandUserPassesTestMixinfor class based views2.- Groups, which bundle permissions so you assign roles instead of single permissions2.
One trap catches many teams. @permission_required without raise_exception=True sends a logged in user who lacks the permission to the login page, where they already are2. Stack @login_required outside and @permission_required(..., raise_exception=True) inside. The class based mixins get this right by default: 403 Forbidden for an authenticated user without the permission, a redirect only for strangers2.
For the row, I use one rule, which Rails readers will recognise from the Rails chapter as "scope first, check second". In Django it becomes concrete: every lookup in a view for logged in users starts from the user's queryset, never from Model.objects. A record outside the user's scope is then never loaded, so a forgotten check cannot leak it.
That leads to the second rule of this chapter, which I have not seen spelled out in the documentation: 403 for the verb, 404 for the row. If a mechanic opens the invoice list, refusing with 403 Forbidden is honest: he knows invoices exist, he simply may not see them. If he guesses the id of another workshop's job card, the answer is 404 Not Found, the same as a card that does not exist. The scope produces that answer by itself, and it tells him nothing, not even that card 4813 is real.
Example: Freewheel's roles and rights
Before writing code, Aisling writes the table, and Niamh signs it off. The table is the specification. Groups and querysets translate it into code, and the tests prove the translation. It is the same table as in the Rails version of the spike, which is the point.
| What | Customer (by link) | Mechanic | Workshop manager | Head office (Niamh) |
|---|---|---|---|---|
| Book a repair | Yes, no login needed | Walk ins, own workshop | Own workshop | All workshops |
| See job cards | Own bikes only | Own workshop | Own workshop | All workshops |
| Move a card on the board | No | Own workshop | Own workshop | All workshops |
| Before and after photos | See own | Add, own workshop | Add, own workshop | All workshops |
| Parts stock | No | See and record usage, own workshop | Edit and reorder, own workshop | All workshops |
| Invoices with VAT | Own invoices | No | Own workshop | All workshops |
| Reports | No | No | Own workshop | All workshops |
| Staff logins | No | No | Mechanics at own workshop, in the admin | Everyone |
| Second factor | Not needed (link only) | No | Required | Required |
Every "own workshop" is the third word, a row rule. Every "Yes" or "No" is a verb, a group permission. That split is the whole design.
Example: the groups carry the verbs
The admin chapter's setup_roles command created two groups. Freewheel adds the third, for mechanics, and the command stays safe to run again on every deploy:
# accounts/management/commands/setup_roles.py (the role list)
MECHANIC = [
"view_booking", "add_booking",
"view_jobcard", "change_jobcard",
"add_jobcardphoto", "view_jobcardphoto",
"view_part", "add_partusage",
]
ROLES = {
"Mechanics": MECHANIC,
"Workshop managers": MECHANIC + [
"change_booking", "delete_jobcard",
"change_part", "view_invoice", "view_report",
],
"Head office": MECHANIC + [
"change_booking", "delete_jobcard",
"change_part", "view_invoice", "view_report",
"view_all_workshops", # the custom permission on Workshop
],
}
view_report is a custom permission on a small Report model in the reporting app, declared in its Meta.permissions the same way as view_all_workshops. The rest of the command is unchanged from the admin chapter.
Example: the queryset carries the rows
The admin chapter added a workshop field to the user model for managers. Freewheel now fills it for every staff login, because it is the single fact every row rule needs. One small queryset class turns it into the third word for every model:
# workshops/scoping.py
from django.db import models
class WorkshopScopedQuerySet(models.QuerySet):
"""The rows a user may know about. Deny by default."""
workshop_path = "workshop" # subclasses say how to reach the workshop
def for_user(self, user):
if not user.is_authenticated or not user.is_active:
return self.none()
if user.has_perm("workshops.view_all_workshops"):
return self
if user.workshop_id is None:
return self.none() # a staff login without a workshop sees nothing
return self.filter(**{self.workshop_path: user.workshop_id})
# workshops/models.py, repairs/models.py (the additions)
class WorkshopQuerySet(WorkshopScopedQuerySet):
workshop_path = "pk"
class Workshop(models.Model):
# ... fields as before ...
objects = WorkshopQuerySet.as_manager()
class JobCardQuerySet(WorkshopScopedQuerySet):
workshop_path = "workshop"
class JobCard(models.Model):
# ... fields as before ...
objects = JobCardQuerySet.as_manager()
class InvoiceQuerySet(WorkshopScopedQuerySet):
workshop_path = "job_card__workshop"
class Invoice(models.Model):
# ... fields as before ...
objects = InvoiceQuerySet.as_manager()
Booking and Part get the same two lines. Note the order in for_user: every branch that is not explicitly allowed ends in none(). A new kind of staff login that someone forgets to give a workshop sees an empty board, not the whole company.
Example: the board, the move and the photo upload, fixed
Here are the views from the htmx and files chapters with the third word added. The changes are the decorators and the first line of each view.
# repairs/views.py
from django.contrib.auth.decorators import login_required, permission_required
from django.shortcuts import get_object_or_404, redirect, render
from django.views.decorators.http import require_GET, require_POST
from django.views.decorators.vary import vary_on_headers
from workshops.models import Workshop
from .models import JobCard
@login_required # strangers: to the login page
@permission_required("repairs.view_jobcard", raise_exception=True) # the verb: 403
@require_GET
@vary_on_headers("HX-Request")
def board(request, workshop_id):
# The row: another workshop's id is a 404, exactly like an id that does not exist
workshop = get_object_or_404(Workshop.objects.for_user(request.user), pk=workshop_id)
template = "repairs/_board.html" if request.htmx else "repairs/board.html"
return render(request, template, board_context(workshop))
@login_required
@permission_required("repairs.change_jobcard", raise_exception=True)
@require_POST
def move(request, workshop_id, card_id):
workshop = get_object_or_404(Workshop.objects.for_user(request.user), pk=workshop_id)
# move_card() already filters by workshop, so the card is scoped through it
# ... unchanged from the htmx chapter ...
@login_required
@permission_required("repairs.add_jobcardphoto", raise_exception=True)
@require_POST
def upload_photo(request, card_id):
card = get_object_or_404(JobCard.objects.for_user(request.user), pk=card_id)
# ... unchanged from the files chapter ...
board_context() is the function from the htmx chapter. The server sent events endpoint for the live board needs the same line: it checked only that the user was logged in, so it now looks up the workshop through Workshop.objects.for_user(user) before streaming anything. A live channel is a page that never finishes loading, and it obeys the same rules.
Example: invoices with class based views
The invoice pages use class based views, and a ten line mixin applies the scope to both:
# repairs/invoice_views.py
from django.contrib.auth.mixins import PermissionRequiredMixin
from django.views.generic import DetailView, ListView
from .models import Invoice
class ScopedToUserMixin:
"""Every object these views can reach comes through the user's scope."""
def get_queryset(self):
return super().get_queryset().for_user(self.request.user)
class InvoiceListView(PermissionRequiredMixin, ScopedToUserMixin, ListView):
model = Invoice
permission_required = "repairs.view_invoice"
paginate_by = 50
class InvoiceDetailView(PermissionRequiredMixin, ScopedToUserMixin, DetailView):
model = Invoice
permission_required = "repairs.view_invoice"
DetailView finds its object by filtering get_queryset() by the primary key, so an id outside the scope raises a 404 with no extra code. PermissionRequiredMixin redirects strangers to the login page and answers 403 to a mechanic, who has no view_invoice. The mixin order matters: the permission mixin first, so its check runs before anything else.
Object permissions: when django guardian or django rules earn their place
Django leaves object permissions to other backends3, and two packages fill the gap. They solve different problems, and choosing between them is easier once you ask where the permission comes from.
- django guardian (2.4.0) implements per object permissions on top of Django's authorisation backend31. It stores each grant as a row in the database: this user may change this one object. It fits when people grant access by hand, record by record: a document shared with three colleagues, a project opened to a contractor.
- django rules (published as
rules, 3.3) is, in its own words, a tiny app for object level permissions "without requiring a database"32. You write predicates, small functions such as "the user's workshop is the card's workshop", and combine them with&and|. It fits when permissions follow from data you already have.
And sometimes neither: when the rule is "same workshop", a queryset already says it, and it also filters lists, which neither package does for you by itself.
Example: the rule that would tip Freewheel to django rules
Every row rule in Freewheel's table is "own workshop", so the queryset is enough, and I would not add a package. Now imagine Niamh adds one rule in year two: a mechanic may edit a job card's notes only while it is "in repair" and only if it is assigned to them. That is logic on one object, beyond a simple filter. With django rules it reads like the sentence:
# repairs/rules.py
import rules
@rules.predicate
def is_assigned_mechanic(user, card):
return card is not None and card.mechanic_id is not None and card.mechanic.user_id == user.pk
@rules.predicate
def is_in_repair(user, card):
return card is not None and card.status == "in_repair"
rules.add_perm("repairs.edit_jobcard_notes", is_assigned_mechanic & is_in_repair)
With rules.permissions.ObjectPermissionBackend added to AUTHENTICATION_BACKENDS, user.has_perm("repairs.edit_jobcard_notes", card) evaluates the predicates32. The card still comes through for_user() first. The predicate is the check, the queryset is still the scope.
Deny by default, proved by a test that walks every URL
Django 5.0 protects views one at a time: a decorator here, a mixin there. There is no setting that makes every page require a login unless marked public. So the most likely security bug in a Django project is not a clever attack. It is a new view that someone forgot to decorate.
You cannot review your way out of that, but you can test your way out. A test can list every URL pattern in the project, visit each one as a stranger and insist on a refusal, except for an allow list of public pages. A view without a login check then fails the build on the day it is written.
Example: the test that walks Freewheel's URLs
# freewheel/tests/test_every_url_refuses_strangers.py
import re
from django.test import TestCase
from django.urls import URLPattern, URLResolver, get_resolver, reverse
from django.urls.resolvers import RoutePattern
# The only URL names a stranger may open. Adding to this list is a reviewed decision.
PUBLIC = {
"home", "booking_new", "booking_done",
"login", "logout", "verify",
"password_reset", "password_reset_done",
"password_reset_confirm", "password_reset_complete",
"open_link", "request_link",
}
SAMPLE = {"int": "1", "str": "x", "slug": "x", "path": "x",
"uuid": "00000000-0000-0000-0000-000000000000"}
def walk(patterns, prefix=""):
for p in patterns:
if isinstance(p, URLResolver):
if p.namespace == "admin": # the admin has its own login and its own chapter
continue
yield from walk(p.url_patterns, prefix + str(p.pattern))
elif isinstance(p, URLPattern) and isinstance(p.pattern, RoutePattern):
yield prefix + str(p.pattern), p.name
def concrete(route):
# "workshops/<int:workshop_id>/board/" becomes "/workshops/1/board/"
return "/" + re.sub(r"<(?:(\w+):)?\w+>", lambda m: SAMPLE[m.group(1) or "str"], route)
class EveryUrlRefusesStrangers(TestCase):
def test_no_private_page_opens_without_a_login(self):
refusal_targets = {reverse("login"), reverse("my:request_link")}
for route, name in walk(get_resolver().url_patterns):
if name in PUBLIC:
continue
url = concrete(route)
with self.subTest(url=url):
response = self.client.get(url)
if response.status_code == 302:
self.assertIn(response.url.split("?")[0], refusal_targets)
else:
self.assertIn(response.status_code, {401, 403, 405})
Note what the test does not accept: a 404. A 404 for a stranger means the view ran its database query before checking who was asking. It might be harmless, thanks to the scope, but it deserves a look, so it fails. And the test needs no data at all: every refusal must happen before the view touches the database. When Cian added a parts export view in week five and forgot the decorator, this test failed on his laptop before he had finished the template.
Tests that prove the roles table
A roles table that is not tested is a wish. The tests below use Django's own TestCase, which runs each test in a transaction and needs nothing extra. The testing series later in this programme covers writing tests first, pytest and factories. Here the point is what to test.
Example: two workshops and three people
# repairs/tests/test_access.py
from datetime import timedelta
from io import StringIO
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Group
from django.core.management import call_command
from django.test import TestCase
from django.urls import reverse
from django.utils import timezone
from bookings.models import Bike, Booking, Customer
from repairs.models import JobCard
from workshops.models import Mechanic, Workshop
User = get_user_model()
PASSWORD = "long enough secret 42"
def staff(username, group, workshop=None):
user = User.objects.create_user(username, password=PASSWORD, workshop=workshop)
user.groups.add(Group.objects.get(name=group))
return user
def job_card_at(workshop, mechanic_user):
# The minimum chain a job card needs. The testing series replaces this with factories.
customer = Customer.objects.create(name="Test", email=f"test{workshop.pk}@example.com")
bike = Bike.objects.create(customer=customer, make="Raleigh")
mechanic = Mechanic.objects.create(user=mechanic_user, workshop=workshop, display_name="Test")
starts = timezone.now() + timedelta(days=1)
booking = Booking.objects.create(
workshop=workshop, mechanic=mechanic, customer=customer, bike=bike,
starts_at=starts, ends_at=starts + timedelta(hours=1),
)
return JobCard.objects.create(booking=booking, workshop=workshop, mechanic=mechanic)
class AccessTest(TestCase):
@classmethod
def setUpTestData(cls):
call_command("setup_roles", stdout=StringIO())
cls.castletroy = Workshop.objects.create(name="Castletroy", city="Limerick")
cls.dooradoyle = Workshop.objects.create(name="Dooradoyle", city="Limerick")
cls.mechanic = staff("mechanic.castletroy", "Mechanics", cls.castletroy)
cls.manager = staff("manager.castletroy", "Workshop managers", cls.castletroy)
cls.niamh = staff("niamh", "Head office")
cls.castletroy_card = job_card_at(cls.castletroy, cls.mechanic)
cls.dooradoyle_card = job_card_at(cls.dooradoyle, staff("mechanic.dooradoyle", "Mechanics", cls.dooradoyle))
Example: the scope, the verb and the row
# (continued inside AccessTest)
def test_a_mechanic_sees_only_his_own_workshop(self):
visible = JobCard.objects.for_user(self.mechanic)
self.assertIn(self.castletroy_card, visible)
self.assertNotIn(self.dooradoyle_card, visible)
def test_head_office_sees_every_workshop(self):
self.assertEqual(JobCard.objects.for_user(self.niamh).count(), 2)
def test_another_workshops_board_is_not_found(self):
self.client.force_login(self.mechanic)
response = self.client.get(reverse("repairs:board", args=[self.dooradoyle.pk]))
self.assertEqual(response.status_code, 404) # the row: 404
def test_a_mechanic_may_not_open_invoices(self):
self.client.force_login(self.mechanic)
response = self.client.get(reverse("repairs:invoice_list"))
self.assertEqual(response.status_code, 403) # the verb: 403
def test_a_manager_must_enter_a_code_first(self):
self.client.force_login(self.manager)
response = self.client.get(reverse("repairs:board", args=[self.castletroy.pk]))
self.assertRedirects(response, reverse("verify"), fetch_redirect_response=False)
Example: the login gives nothing away
def test_unknown_user_and_wrong_password_get_the_same_error(self):
unknown = self.client.post(reverse("login"), {"username": "nobody", "password": "x" * 12})
wrong = self.client.post(reverse("login"), {"username": "niamh", "password": "x" * 12})
self.assertEqual(
unknown.context["form"].non_field_errors(),
wrong.context["form"].non_field_errors(),
)
def test_logout_needs_a_post(self):
self.client.force_login(self.mechanic)
self.assertEqual(self.client.get(reverse("logout")).status_code, 405)
force_login() skips the password check, which keeps the tests fast, and it does not verify a second factor, which is exactly why the manager test sees the redirect. The two failed logins in the last test do not reach the axes limit of ten. If you test the lockout itself, give that test its own user.
The settings that ship to production
The last part of the doors is configuration. The deployment checklist is short and blunt: keep SECRET_KEY secret and out of source control, never run with DEBUG on in production, set ALLOWED_HOSTS, and enforce HTTPS with secure cookies9. On DEBUG, the checklist explains why: error pages then leak excerpts of your source code, local variables, settings and libraries9. The start chapter already reads these values from the environment, with DEBUG failing safe to False.
Two settings deserve a sentence each. SECRET_KEY_FALLBACKS lets you rotate the secret key without logging everyone out: the new key signs, the old ones still verify for a while, and the checklist reminds you to remove old keys in a timely manner9. And SECURE_PROXY_SSL_HEADER tells Django to trust a proxy's X-Forwarded-Proto header. Behind a load balancer you usually need it, and the security guide warns that getting it wrong can open CSRF holes1, so set it only when the proxy always sets or strips that header.
The two remaining gaps from the defaults table are a Content Security Policy and dependency checks. For the first, django csp, maintained under the Mozilla organisation (3.8, March 2024), adds a middleware and settings such as CSP_DEFAULT_SRC, with a report only mode to see what a policy would block before it blocks anything33. For the second, pip-audit checks your installed packages against the Python Packaging Advisory Database34, and Bandit, a general security linter for Python, has checks for Django's escape hatches such as mark_safe (B703), extra() (B610) and RawSQL (B611)35. Bandit is not a Django specialist the way Brakeman is for Rails, so treat it as a second pair of eyes next to the escape hatch search.
Example: Freewheel's production settings and its gate
# freewheel/settings.py (the production part; DEBUG comes from the environment, as before)
SECRET_KEY = env("SECRET_KEY")
SECRET_KEY_FALLBACKS = env.list("SECRET_KEY_FALLBACKS", default=[])
ALLOWED_HOSTS = env.list("ALLOWED_HOSTS", default=[]) # freewheelcycles.example
if not DEBUG:
SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https") # the load balancer sets it
SECURE_SSL_REDIRECT = True
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
SECURE_HSTS_SECONDS = 60 * 60 # one hour first; one year after a calm week
SECURE_HSTS_INCLUDE_SUBDOMAINS = True # every Freewheel subdomain is HTTPS only
# Preload is a separate, hard to reverse decision, so its reminder is silenced on purpose
SILENCED_SYSTEM_CHECKS = ["security.W021"]
# Content Security Policy, in report only mode for the first week
MIDDLEWARE += ["csp.middleware.CSPMiddleware"]
CSP_DEFAULT_SRC = ("'self'",)
CSP_IMG_SRC = ("'self'", "data:", env("MEDIA_HOST")) # the storage domain of the signed photo URLs
CSP_OBJECT_SRC = ("'none'",)
CSP_REPORT_ONLY = True
The documentation warns that HSTS can cause serious problems if switched on carelessly14, which is why the first value is one hour, raised once a week has passed without surprises. htmx is served as a static file from Freewheel's own domain, so 'self' covers it.
The gate runs on every push and before every deploy:
#!/usr/bin/env bash
# bin/security_checks: fail the build if production settings or dependencies are unsafe
set -euo pipefail
DEBUG=off \
ALLOWED_HOSTS=freewheelcycles.example \
SECRET_KEY="$(python -c 'import secrets; print(secrets.token_urlsafe(64))')" \
python manage.py check --deploy --fail-level WARNING
pip-audit -r requirements.txt
bandit -r . -x ./.venv,./node_modules --skip B101 -q # B101 flags assert, which tests use
bin/escape_hatches
The throwaway secret key is there because check --deploy rightly warns about a short key or one that starts with django-insecure-14. The production key never leaves the server's environment.
The admin needs the same care as the rest, and the admin chapter covers it: a second factor, a path that is not /admin/, and a network rule. An exposed admin with a weak superuser password undoes everything above.
What the law asks: the GDPR and the Data Protection Commission
This section is general information, not legal advice. For decisions about your own processing, speak to a data protection professional.
Freewheel processes personal data: names, phone numbers, email addresses, addresses on invoices, and photos that may show a bike outside someone's home. In Ireland, the EU General Data Protection Regulation (GDPR) applies directly, and the Data Protection Act 2018 gives further effect to it36. The regulator is the Data Protection Commission (DPC). Three articles of the GDPR touch this chapter directly, and they are the same three the Rails chapter maps:
- Article 5(1)(f) requires personal data to be processed securely, with appropriate technical or organisational measures23.
- Article 32 asks for security appropriate to the risk, taking into account what current technology offers and what it costs, and names encryption and ongoing confidentiality among the measures37.
- Article 33 requires a personal data breach to be reported to the supervisory authority, here the DPC, without undue delay and, where feasible, within 72 hours of becoming aware of it, unless it is unlikely to result in a risk to people's rights and freedoms38. The DPC explains how to notify it on its own website39.
The law does not mention Django, groups or django axes. It asks for measures that fit the risk, and it expects you to be able to show them. The DPC also publishes guidance for controllers on data security, which is worth an hour of anyone's time before launch40.
Example: Freewheel's measures, mapped to the risk
| Risk | Measure in the application | Where in this chapter |
|---|---|---|
| A mechanic sees another workshop's customers | for_user() on every model, tested, and the URL walking test | Authorisation, deny by default |
| A manager's password is phished | Second factor through django otp | Second factor |
| Common passwords are guessed | Validators, plus axes locks by username and address | Passwords, throttling |
| A leaver keeps access | Unticking "active" ends the session on the next request | Logins |
| The user table leaks | Argon2 hashes, no customer passwords at all | Passwords, customers |
| Tokens in links are kept forever | Seven day expiry, a counter to revoke, access logs treated as personal data | Customers |
| A production setting is left off | check --deploy --fail-level WARNING on every push | Settings |
| A known flaw in a package | pip-audit on every push | Settings |
Aisling keeps this table in the repository next to the roles table. If the DPC ever asks what Freewheel did, the answer is a file and a test run, not a memory.
For the person paying for this
If you commission a Django application, you do not need to read the code to judge its security. Ask for these six things. A developer who has done the work can show each one in minutes.
- The roles table, signed off by you. If it does not exist, the rules exist only in someone's head.
- The test that a guessed id from another branch or customer returns "not found", and a run of the whole suite.
- The test that walks every URL as a stranger, or an equally strict answer to "how do you know no page was left open?".
- A run of
manage.py check --deployagainst the production settings, with every remaining warning explained. - How logins are throttled, and who has a second factor. "Django handles that" is the wrong answer for the first: Django's own guide says it does not1.
- What happens when someone leaves. Ask the developer to deactivate a test login while it is signed in, and watch the next click land on the login page.
If any of these takes longer than a day to produce, that tells you more than any assurance. I build web applications on Ruby on Rails, not Django, and I build them this way: test first, with the roles table as the specification, and the client owns the code, the accounts and the data. If you are weighing up the two frameworks for your own product, or want to talk through these questions before you commission anything, the free workshop is a good place to start, and my prices are published.
Conclusion
Django gives you more of the login system than almost any framework: a user model, PBKDF2 hashing that strengthens with each release, validators, login and reset views, session handling that closes fixation and logs out everywhere after a password change. It guards the classic doors by default and, with check --deploy, it audits the ones it leaves to your settings. What it does not do is throttle logins, ask for a second factor or switch on HTTPS for you. django axes, django otp and five lines of settings close those gaps.
Then comes the part no framework can do. Django's permissions have two words, a verb and a kind of thing. Your rules have three, and the third, which one, is yours. Put it in a for_user() queryset and start every lookup there, answer 403 for the verb and 404 for the row, prove the roles table with tests, and let a test walk every URL so that a forgotten decorator fails the build.
The next chapter takes the same application two years on, to 14 workshops and a JSON API for the mechanics' app, where these rules have to keep up with a much larger codebase.
