A5: sign up, sign in, sign out, profile and the base layout (WEB-02, WEB-06, WEB-11, WEB-50..54)

Registration (case-insensitive unique names, 8-256 char passwords, no email),
sign-in with a generic error and a fresh session, internal-only ?next=,
POST-only sign-out, password change that closes the other sessions. The
failed-login backoff, the registration quota and the password-change guard
live in the database so every web process shares them; the client IP is the
last X-Forwarded-For hop. One responsive stylesheet with light/dark theme,
labelled fields, alerts and no inline scripts or styles; Italian error pages
and a readable CSRF failure. Mutation checks: open redirects, uncounted
failures and a missing CSRF middleware are all caught.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
davideandClaude Sonnet 5.5 committed 2026-11-16 14:07:45 +01:00
1 parent 1d4b53d778
commit efb3e2e702
28 files changed
+1232 -22

No files matched your search

+20
View File
@@ -0,0 +1,20 @@
from django.contrib.auth import get_user_model
from django.contrib.auth.backends import ModelBackend
class CaseInsensitiveBackend(ModelBackend):
"""Usernames are one case-insensitive namespace (ADR-38): `Mario` and `mario` log in as the same account."""
def authenticate(self, request, username=None, password=None, **kwargs):
User = get_user_model()
if username is None or password is None:
return None
try:
user = User.objects.get(username__iexact=username)
except User.DoesNotExist:
# Run the hasher anyway, so an unknown name costs as much as a wrong password (SEC-19).
User().set_password(password)
return None
if user.check_password(password) and self.user_can_authenticate(user):
return user
return None
+13
View File
@@ -0,0 +1,13 @@
"""The caller's address, for the throttles that are keyed by it (SEC-42, B-54)."""
def client_ip(request) -> str:
"""The *last* hop of X-Forwarded-For: the one written by our own proxy. The first elements are whatever
the client sent, so reading from the front would let a fake value per request dodge every IP-keyed
control. Caddy also overwrites the header with the real peer (Caddyfile), so either half closes it;
without the header (direct access) the socket peer is used."""
forwarded = request.META.get("HTTP_X_FORWARDED_FOR", "")
hops = [hop.strip() for hop in forwarded.split(",") if hop.strip()]
if hops:
return hops[-1]
return request.META.get("REMOTE_ADDR", "unknown")
+70
View File
@@ -0,0 +1,70 @@
from django import forms
from django.contrib.auth import get_user_model
from django.contrib.auth.password_validation import validate_password
from .validators import username_validator
User = get_user_model()
class LoginForm(forms.Form):
username = forms.CharField(label="Nome utente", max_length=150, strip=True,
widget=forms.TextInput(attrs={"autocomplete": "username", "autocapitalize": "none",
"spellcheck": "false", "autofocus": True}))
password = forms.CharField(label="Password", max_length=1024, strip=False,
widget=forms.PasswordInput(attrs={"autocomplete": "current-password"}))
class RegisterForm(forms.Form):
username = forms.CharField(
label="Nome utente", min_length=3, max_length=32, strip=True, validators=[username_validator],
help_text="Da 3 a 32 caratteri: lettere, numeri, punto, trattino e trattino basso.",
widget=forms.TextInput(attrs={"autocomplete": "username", "autocapitalize": "none", "spellcheck": "false",
"autofocus": True}),
)
password = forms.CharField(label="Password", strip=False, help_text="Almeno 8 caratteri.",
widget=forms.PasswordInput(attrs={"autocomplete": "new-password"}))
password_confirm = forms.CharField(label="Ripeti la password", strip=False,
widget=forms.PasswordInput(attrs={"autocomplete": "new-password"}))
def clean_username(self):
username = self.cleaned_data["username"]
if User.objects.filter(username__iexact=username).exists(): # one namespace, any case (ADR-38)
raise forms.ValidationError("Questo nome utente è già in uso.", code="username_taken")
return username
def clean_password(self):
password = self.cleaned_data["password"]
validate_password(password)
return password
def clean(self):
cleaned = super().clean()
if cleaned.get("password") and cleaned.get("password_confirm") and cleaned["password"] != cleaned["password_confirm"]:
self.add_error("password_confirm", "Le due password non coincidono.")
return cleaned
class PasswordChangeForm(forms.Form):
current_password = forms.CharField(label="Password attuale", max_length=1024, strip=False,
widget=forms.PasswordInput(attrs={"autocomplete": "current-password"}))
new_password = forms.CharField(label="Nuova password", strip=False, help_text="Almeno 8 caratteri.",
widget=forms.PasswordInput(attrs={"autocomplete": "new-password"}))
new_password_confirm = forms.CharField(label="Ripeti la nuova password", strip=False,
widget=forms.PasswordInput(attrs={"autocomplete": "new-password"}))
def __init__(self, user, *args, **kwargs):
super().__init__(*args, **kwargs)
self.user = user
def clean_new_password(self):
password = self.cleaned_data["new_password"]
validate_password(password, self.user)
return password
def clean(self):
cleaned = super().clean()
if cleaned.get("new_password") and cleaned.get("new_password_confirm") and \
cleaned["new_password"] != cleaned["new_password_confirm"]:
self.add_error("new_password_confirm", "Le due password non coincidono.")
return cleaned
@@ -0,0 +1,26 @@
# Generated by Django 5.2.19 on 2026-11-16 12:52
import django.utils.timezone
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('accounts', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='ThrottleEvent',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('scope', models.CharField(max_length=16)),
('key', models.CharField(max_length=150)),
('created_at', models.DateTimeField(default=django.utils.timezone.now)),
],
options={
'indexes': [models.Index(fields=['scope', 'key', 'created_at'], name='accounts_th_scope_248904_idx')],
},
),
]
+16
View File
@@ -1,6 +1,7 @@
from django.contrib.auth.models import AbstractUser
from django.db import models
from django.db.models.functions import Lower
from django.utils import timezone
class User(AbstractUser):
@@ -14,3 +15,18 @@ class User(AbstractUser):
# ADR-38: one case-insensitive namespace. The name is stored as typed.
models.UniqueConstraint(Lower("username"), name="accounts_user_username_ci_unique"),
]
class ThrottleEvent(models.Model):
"""One counted event of a throttle (failed login, registration, wrong current password).
In the database, not in memory: the web runs as several processes (ADR-55, ARC-72), and a throttle
kept in one process's memory is bypassed by whichever other process answers the next request.
"""
scope = models.CharField(max_length=16)
key = models.CharField(max_length=150)
created_at = models.DateTimeField(default=timezone.now)
class Meta:
indexes = [models.Index(fields=["scope", "key", "created_at"])]
@@ -0,0 +1,6 @@
<div class="field{% if field.errors %} has-error{% endif %}">
<label for="{{ field.id_for_label }}">{{ field.label }}</label>
{{ field }}
{% if field.help_text %}<p class="hint" id="{{ field.id_for_label }}-hint">{{ field.help_text }}</p>{% endif %}
{% for error in field.errors %}<p class="error" role="alert">{{ error }}</p>{% endfor %}
</div>
@@ -0,0 +1,4 @@
{% if throttled_seconds %}
<p class="error box" role="alert">Troppi tentativi. Riprova fra {{ throttled_seconds }} second{{ throttled_seconds|pluralize:"o,i" }}.</p>
{% endif %}
{% for error in form.non_field_errors %}<p class="error box" role="alert">{{ error }}</p>{% endfor %}
@@ -0,0 +1,15 @@
{% extends "web/base.html" %}
{% block title %}Accedi · PLM Lottery{% endblock %}
{% block content %}
<section class="card narrow">
<h1>Accedi</h1>
<form method="post" novalidate>
{% csrf_token %}
<input type="hidden" name="next" value="{{ next }}">
{% include "accounts/_form_errors.html" %}
{% for field in form %}{% include "accounts/_field.html" %}{% endfor %}
<button class="button" type="submit">Accedi</button>
</form>
<p class="aside">Non hai un account? <a href="{% url 'accounts:register' %}{% if next %}?next={{ next|urlencode }}{% endif %}">Registrati</a>.</p>
</section>
{% endblock %}
@@ -0,0 +1,28 @@
{% extends "web/base.html" %}
{% block title %}Profilo · PLM Lottery{% endblock %}
{% block content %}
<h1>Profilo</h1>
<section class="card">
<h2>Il tuo account</h2>
<dl class="facts">
<dt>Nome utente</dt><dd>{{ user.get_username }}</dd>
<dt>Iscritto dal</dt><dd>{{ user.date_joined|date:"j F Y" }}</dd>
</dl>
</section>
<section class="card narrow">
<h2>Cambia password</h2>
<form method="post" novalidate>
{% csrf_token %}
{% include "accounts/_form_errors.html" %}
{% for field in form %}{% include "accounts/_field.html" %}{% endfor %}
<button class="button" type="submit">Aggiorna la password</button>
</form>
</section>
<section class="card narrow">
<h2>Esci</h2>
<form method="post" action="{% url 'accounts:logout' %}">
{% csrf_token %}
<button class="button secondary" type="submit">Esci da questo dispositivo</button>
</form>
</section>
{% endblock %}
@@ -0,0 +1,16 @@
{% extends "web/base.html" %}
{% block title %}Registrati · PLM Lottery{% endblock %}
{% block content %}
<section class="card narrow">
<h1>Crea il tuo account</h1>
<form method="post" novalidate>
{% csrf_token %}
<input type="hidden" name="next" value="{{ next }}">
{% include "accounts/_form_errors.html" %}
{% for field in form %}{% include "accounts/_field.html" %}{% endfor %}
<p class="hint">Non raccogliamo email: se perdi la password non esiste un recupero automatico, solo un reset da parte dell'operatore.</p>
<button class="button" type="submit">Registrati</button>
</form>
<p class="aside">Hai già un account? <a href="{% url 'accounts:login' %}{% if next %}?next={{ next|urlencode }}{% endif %}">Accedi</a>.</p>
</section>
{% endblock %}
+98
View File
@@ -0,0 +1,98 @@
"""Throttles for credentials, shared by every web process (WEB-02, SEC-54, SEC-55).
Two kinds, as in the old server (B-33, B-58):
* `Backoff` — for failed guesses at a secret. After `threshold` failures in a row the next attempt must wait
`base_delay * 2**(failures - threshold)` seconds (capped), counted from the last failure; a streak ends when
the key stays quiet for `decay_seconds`, so a shared address is not punished forever for earlier mistakes.
* `Quota` — for "how many of these may one source create": a count in a rolling window, on completed actions.
"""
from dataclasses import dataclass
from datetime import datetime, timedelta
from django.utils import timezone
from .models import ThrottleEvent
@dataclass(frozen=True)
class Backoff:
scope: str
threshold: int
base_delay: float
max_delay: float
decay_seconds: float
@dataclass(frozen=True)
class Quota:
scope: str
limit: int
window_seconds: float
LOGIN = Backoff("login", threshold=5, base_delay=2.0, max_delay=300.0, decay_seconds=900.0)
LOGIN_IP = Backoff("login_ip", threshold=20, base_delay=2.0, max_delay=300.0, decay_seconds=900.0)
CHANGE_PASSWORD = Backoff("chpwd", threshold=5, base_delay=2.0, max_delay=300.0, decay_seconds=900.0)
REGISTER = Quota("register", limit=5, window_seconds=3600.0)
_KEY_MAX = 150
def _key(key: str) -> str:
return key[:_KEY_MAX]
def _streak(rule: Backoff, key: str) -> list[datetime]:
"""Timestamps of the current streak of failures, oldest first."""
events = list(
ThrottleEvent.objects.filter(scope=rule.scope, key=_key(key)).order_by("-created_at")
.values_list("created_at", flat=True)
)
streak: list[datetime] = []
for created_at in events: # newest first: walk back while the gap stays within the decay
if streak and (streak[-1] - created_at).total_seconds() > rule.decay_seconds:
break
streak.append(created_at)
return streak[::-1]
def retry_after(rule: Backoff | Quota, key: str, now: datetime | None = None) -> float:
"""Seconds until this key may try again; 0.0 while it may."""
now = now or timezone.now()
if isinstance(rule, Quota):
window_start = now - timedelta(seconds=rule.window_seconds)
recent = list(
ThrottleEvent.objects.filter(scope=rule.scope, key=_key(key), created_at__gt=window_start)
.order_by("-created_at").values_list("created_at", flat=True)[: rule.limit]
)
if len(recent) < rule.limit:
return 0.0
return max(0.0, (recent[-1] + timedelta(seconds=rule.window_seconds) - now).total_seconds())
streak = _streak(rule, key)
if len(streak) < rule.threshold:
return 0.0
if (now - streak[-1]).total_seconds() > rule.decay_seconds:
return 0.0
delay = min(rule.max_delay, rule.base_delay * 2 ** (len(streak) - rule.threshold))
return max(0.0, (streak[-1] + timedelta(seconds=delay) - now).total_seconds())
def record(rule: Backoff | Quota, key: str, now: datetime | None = None) -> None:
"""Count one failure (Backoff) or one completed action (Quota), and drop what no longer matters."""
now = now or timezone.now()
ThrottleEvent.objects.create(scope=rule.scope, key=_key(key), created_at=now)
horizon = rule.window_seconds if isinstance(rule, Quota) else rule.decay_seconds
if isinstance(rule, Backoff):
streak = _streak(rule, key)
if streak: # events before the current streak can never count again
ThrottleEvent.objects.filter(scope=rule.scope, key=_key(key), created_at__lt=streak[0]).delete()
else:
ThrottleEvent.objects.filter(scope=rule.scope, created_at__lt=now - timedelta(seconds=horizon)).delete()
def reset(rule: Backoff, key: str) -> None:
"""A success ends the streak of that key."""
ThrottleEvent.objects.filter(scope=rule.scope, key=_key(key)).delete()
+11
View File
@@ -0,0 +1,11 @@
from django.urls import path
from . import views
app_name = "accounts"
urlpatterns = [
path("accedi/", views.login_view, name="login"),
path("registrati/", views.register_view, name="register"),
path("esci/", views.logout_view, name="logout"),
path("app/profilo/", views.profile_view, name="profile"),
]
+31
View File
@@ -0,0 +1,31 @@
import re
from django.core.exceptions import ValidationError
from django.core.validators import RegexValidator
MIN_PASSWORD_LENGTH = 8 # SEC-17
MAX_PASSWORD_LENGTH = 256 # bounds the hashing work an anonymous caller can ask for (SEC-17)
username_validator = RegexValidator(
re.compile(r"^[A-Za-z0-9_.-]+$"), "Usa solo lettere, numeri, punto, trattino e trattino basso."
)
class MinimumLengthValidator:
def validate(self, password, user=None):
if len(password) < MIN_PASSWORD_LENGTH:
raise ValidationError(f"La password deve avere almeno {MIN_PASSWORD_LENGTH} caratteri.",
code="password_too_short")
def get_help_text(self):
return f"Almeno {MIN_PASSWORD_LENGTH} caratteri."
class MaximumLengthValidator:
def validate(self, password, user=None):
if len(password) > MAX_PASSWORD_LENGTH:
raise ValidationError(f"La password può avere al massimo {MAX_PASSWORD_LENGTH} caratteri.",
code="password_too_long")
def get_help_text(self):
return f"Al massimo {MAX_PASSWORD_LENGTH} caratteri."
+136
View File
@@ -0,0 +1,136 @@
"""Sign in, sign up, sign out and the profile (WEB-02, WEB-11, roadmap A5)."""
from django.conf import settings
from django.contrib import messages
from django.contrib.auth import authenticate, login, logout, update_session_auth_hash
from django.contrib.auth.decorators import login_required
from django.db import IntegrityError, transaction
from django.shortcuts import redirect, render
from django.utils.http import url_has_allowed_host_and_scheme
from django.views.decorators.cache import never_cache
from django.views.decorators.http import require_http_methods, require_POST
from apps.lottery import audit
from . import throttle
from .client_ip import client_ip
from .forms import LoginForm, PasswordChangeForm, RegisterForm
from .models import User
BACKEND = "apps.accounts.backends.CaseInsensitiveBackend"
def safe_next(request, value: str | None) -> str:
"""WEB-11: a destination after sign-in is honoured only if it is a path on this site. An external
address, a protocol-relative `//host`, a backslash trick or a scheme (`javascript:`) all fall back to
the default, so the login page cannot be used to send people elsewhere."""
if (
value
and value.startswith("/")
and not value.startswith("//")
and "\\" not in value
and url_has_allowed_host_and_scheme(value, allowed_hosts={request.get_host()}, require_https=request.is_secure())
):
return value
return settings.LOGIN_REDIRECT_URL
def _too_many(request, template: str, context: dict, wait: float):
seconds = int(wait) + 1
context = {**context, "throttled_seconds": seconds}
response = render(request, template, context, status=429)
response["Retry-After"] = str(seconds)
return response
@never_cache
@require_http_methods(["GET", "POST"])
def login_view(request):
next_url = request.POST.get("next") or request.GET.get("next") or ""
if request.user.is_authenticated:
return redirect(safe_next(request, next_url))
form = LoginForm(request.POST or None)
context = {"form": form, "next": next_url}
if request.method == "POST":
ip = client_ip(request)
user_key = request.POST.get("username", "").strip().lower()
wait = max(throttle.retry_after(throttle.LOGIN, user_key), throttle.retry_after(throttle.LOGIN_IP, ip))
if wait > 0: # refused before the password is even looked at
return _too_many(request, "accounts/login.html", context, wait)
user = None
if form.is_valid():
user = authenticate(request, username=form.cleaned_data["username"], password=form.cleaned_data["password"])
if user is None:
# The same answer whether the name does not exist or the password is wrong (SEC-19).
throttle.record(throttle.LOGIN, user_key)
throttle.record(throttle.LOGIN_IP, ip)
form.add_error(None, "Nome utente o password non corretti.")
return render(request, "accounts/login.html", context, status=200)
throttle.reset(throttle.LOGIN, user_key) # the address keeps its count: one success must not wipe a spray
login(request, user, backend=BACKEND) # also gives the session a fresh key
return redirect(safe_next(request, next_url))
return render(request, "accounts/login.html", context)
@never_cache
@require_http_methods(["GET", "POST"])
def register_view(request):
next_url = request.POST.get("next") or request.GET.get("next") or ""
if request.user.is_authenticated:
return redirect(safe_next(request, next_url))
form = RegisterForm(request.POST or None)
context = {"form": form, "next": next_url}
if request.method == "POST":
ip = client_ip(request)
wait = throttle.retry_after(throttle.REGISTER, ip)
if wait > 0:
return _too_many(request, "accounts/register.html", context, wait)
if form.is_valid():
try:
with transaction.atomic():
user = User.objects.create_user(form.cleaned_data["username"], password=form.cleaned_data["password"])
audit.record("user_registered", actor=user, subject_type="user", subject_id=user.pk)
except IntegrityError: # lost a race for the same name: the constraint is the backstop
form.add_error("username", "Questo nome utente è già in uso.")
else:
throttle.record(throttle.REGISTER, ip) # counts accounts that exist, not attempts
login(request, user, backend=BACKEND)
return redirect(safe_next(request, next_url))
return render(request, "accounts/register.html", context)
@require_POST
def logout_view(request):
logout(request)
return redirect(settings.LOGOUT_REDIRECT_URL)
@never_cache
@login_required
@require_http_methods(["GET", "POST"])
def profile_view(request):
form = PasswordChangeForm(request.user, request.POST or None)
if request.method == "POST":
key = str(request.user.pk)
wait = throttle.retry_after(throttle.CHANGE_PASSWORD, key)
if wait > 0:
return _too_many(request, "accounts/profile.html", {"form": form}, wait)
if form.is_valid():
if not request.user.check_password(form.cleaned_data["current_password"]):
# SEC-54: a stolen session must not be able to guess the password and lock the owner out.
throttle.record(throttle.CHANGE_PASSWORD, key)
form.add_error("current_password", "La password attuale non è corretta.")
else:
with transaction.atomic():
request.user.set_password(form.cleaned_data["new_password"])
request.user.save(update_fields=["password"])
audit.record("password_changed", actor=request.user, subject_type="user", subject_id=request.user.pk)
throttle.reset(throttle.CHANGE_PASSWORD, key)
# This session stays signed in; every other one is signed out, because a session is bound
# to the hash of the password it was created with (B-34).
update_session_auth_hash(request, request.user)
messages.success(request, "Password aggiornata. Le altre sessioni sono state chiuse.")
return redirect("accounts:profile")
return render(request, "accounts/profile.html", {"form": form})