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:
1 parent
1d4b53d778
commit
efb3e2e702
28 files changed
+1232
-22
No files matched your search
@@ -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
|
||||
@@ -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")
|
||||
@@ -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')],
|
||||
},
|
||||
),
|
||||
]
|
||||
@@ -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 %}
|
||||
@@ -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()
|
||||
@@ -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"),
|
||||
]
|
||||
@@ -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."
|
||||
@@ -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})
|
||||
@@ -0,0 +1,70 @@
|
||||
/* One stylesheet for the whole site (ADR-54). Mobile first, no inline styles or scripts anywhere, so the
|
||||
Content-Security-Policy can be tightened for these pages (Caddyfile). */
|
||||
:root {
|
||||
--bg: #f6f7f9; --surface: #ffffff; --text: #16202a; --muted: #5a6672; --line: #d9dee4;
|
||||
--accent: #1b5fd6; --accent-text: #ffffff; --error: #b42318; --error-bg: #fdecea; --ok: #067647; --ok-bg: #e7f6ec;
|
||||
--radius: 10px; --gap: 1rem;
|
||||
color-scheme: light dark;
|
||||
}
|
||||
@media (prefers-color-scheme: dark) {
|
||||
:root {
|
||||
--bg: #10161c; --surface: #19222b; --text: #e8edf2; --muted: #9aa7b3; --line: #2b3742;
|
||||
--accent: #6ea0ff; --accent-text: #0b1220; --error: #ff8f85; --error-bg: #3a1d1b; --ok: #6ddba0; --ok-bg: #12301f;
|
||||
}
|
||||
}
|
||||
*, *::before, *::after { box-sizing: border-box; }
|
||||
html { -webkit-text-size-adjust: 100%; }
|
||||
body { margin: 0; background: var(--bg); color: var(--text); line-height: 1.55;
|
||||
font: 1rem/1.55 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; }
|
||||
h1 { font-size: 1.6rem; line-height: 1.25; margin: 1.2rem 0 .8rem; }
|
||||
h2 { font-size: 1.2rem; margin: 0 0 .8rem; }
|
||||
a { color: var(--accent); }
|
||||
.wrap { width: 100%; max-width: 60rem; margin-inline: auto; padding-inline: 1rem; }
|
||||
main { padding-block: 1rem 3rem; min-height: 60vh; }
|
||||
main:focus { outline: none; }
|
||||
|
||||
.skip-link { position: absolute; left: .5rem; top: -4rem; background: var(--accent); color: var(--accent-text);
|
||||
padding: .6rem 1rem; border-radius: var(--radius); z-index: 10; }
|
||||
.skip-link:focus { top: .5rem; }
|
||||
|
||||
.site-header { background: var(--surface); border-bottom: 1px solid var(--line); }
|
||||
.bar { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: .5rem 1rem; padding-block: .6rem; }
|
||||
.brand { font-weight: 700; font-size: 1.15rem; color: var(--text); text-decoration: none; }
|
||||
.nav { display: flex; flex-wrap: wrap; align-items: center; gap: .25rem .9rem; }
|
||||
.nav a { text-decoration: none; padding: .5rem .2rem; }
|
||||
.nav a.button { padding: .5rem .9rem; }
|
||||
.inline { display: inline; margin: 0; }
|
||||
|
||||
.card { background: var(--surface); border: 1px solid var(--line); border-radius: var(--radius); padding: 1.2rem; margin-block: 1rem; }
|
||||
.narrow { max-width: 28rem; }
|
||||
|
||||
.field { margin-bottom: 1rem; }
|
||||
label { display: block; font-weight: 600; margin-bottom: .3rem; }
|
||||
input[type=text], input[type=password] { width: 100%; min-height: 2.75rem; padding: .55rem .75rem; font: inherit; color: var(--text);
|
||||
background: var(--bg); border: 1px solid var(--line); border-radius: 8px; }
|
||||
.has-error input { border-color: var(--error); }
|
||||
.hint { color: var(--muted); font-size: .9rem; margin: .3rem 0 0; }
|
||||
.error { color: var(--error); font-size: .95rem; margin: .3rem 0 0; }
|
||||
.error.box { background: var(--error-bg); border-radius: 8px; padding: .6rem .8rem; margin: 0 0 1rem; }
|
||||
.messages { margin-block: 1rem 0; }
|
||||
.message { background: var(--ok-bg); color: var(--ok); border-radius: 8px; padding: .6rem .8rem; margin: 0 0 .5rem; }
|
||||
.message.error { background: var(--error-bg); color: var(--error); }
|
||||
|
||||
.button, .link-button { font: inherit; cursor: pointer; }
|
||||
.button { display: inline-flex; align-items: center; justify-content: center; min-height: 2.75rem; padding: .55rem 1.2rem; border: 0;
|
||||
border-radius: 8px; background: var(--accent); color: var(--accent-text); font-weight: 600; text-decoration: none; }
|
||||
.button.secondary { background: transparent; color: var(--accent); border: 1px solid var(--accent); }
|
||||
.button.small { min-height: 2.25rem; padding: .3rem .9rem; }
|
||||
.link-button { background: none; border: 0; color: var(--accent); padding: .5rem .2rem; text-decoration: underline; }
|
||||
.aside { color: var(--muted); margin: 1rem 0 0; }
|
||||
|
||||
.facts { display: grid; grid-template-columns: max-content 1fr; gap: .3rem 1rem; margin: 0; }
|
||||
.facts dt { color: var(--muted); } .facts dd { margin: 0; }
|
||||
|
||||
.site-footer { border-top: 1px solid var(--line); color: var(--muted); font-size: .9rem; padding-block: 1rem; }
|
||||
|
||||
/* Keyboard users always see where they are (WEB-06). */
|
||||
:focus-visible { outline: 3px solid var(--accent); outline-offset: 2px; }
|
||||
|
||||
@media (min-width: 40rem) { h1 { font-size: 2rem; } .card { padding: 1.6rem; } }
|
||||
@media (prefers-reduced-motion: reduce) { * { transition: none !important; animation: none !important; } }
|
||||
@@ -0,0 +1,6 @@
|
||||
{% extends "web/base.html" %}
|
||||
{% block title %}Gioca · PLM Lottery{% endblock %}
|
||||
{% block content %}
|
||||
<h1>Area giocatore</h1>
|
||||
<p>Ciao {{ user.get_username }}. La schermata di gioco è in costruzione.</p>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,47 @@
|
||||
{% load static %}<!doctype html>
|
||||
<html lang="it">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<meta name="color-scheme" content="light dark">
|
||||
<title>{% block title %}PLM Lottery{% endblock %}</title>
|
||||
<link rel="stylesheet" href="{% static 'web/site.css' %}">
|
||||
</head>
|
||||
<body>
|
||||
<a class="skip-link" href="#contenuto">Vai al contenuto</a>
|
||||
<header class="site-header">
|
||||
<div class="wrap bar">
|
||||
<a class="brand" href="{% url 'web:home' %}">PLM Lottery</a>
|
||||
<nav class="nav" aria-label="Principale">
|
||||
<a href="{% url 'web:home' %}">Home</a>
|
||||
{% if user.is_authenticated %}
|
||||
<a href="{% url 'web:app-home' %}">Gioca</a>
|
||||
<a href="{% url 'accounts:profile' %}">Profilo</a>
|
||||
<form class="inline" method="post" action="{% url 'accounts:logout' %}">
|
||||
{% csrf_token %}
|
||||
<button class="link-button" type="submit">Esci ({{ user.get_username }})</button>
|
||||
</form>
|
||||
{% else %}
|
||||
<a href="{% url 'accounts:login' %}">Accedi</a>
|
||||
<a class="button small" href="{% url 'accounts:register' %}">Registrati</a>
|
||||
{% endif %}
|
||||
</nav>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<main id="contenuto" class="wrap" tabindex="-1">
|
||||
{% if messages %}
|
||||
<div class="messages" role="status">
|
||||
{% for message in messages %}<p class="message {{ message.tags }}">{{ message }}</p>{% endfor %}
|
||||
</div>
|
||||
{% endif %}
|
||||
{% block content %}{% endblock %}
|
||||
</main>
|
||||
|
||||
<footer class="site-footer">
|
||||
<div class="wrap">
|
||||
<p>Ambiente di prova su rete regtest: nessun denaro reale.</p>
|
||||
</div>
|
||||
</footer>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,7 @@
|
||||
{% extends "web/base.html" %}
|
||||
{% block title %}{{ title }} · PLM Lottery{% endblock %}
|
||||
{% block content %}
|
||||
<h1>{{ title }}</h1>
|
||||
<p>{{ message }}</p>
|
||||
<p><a class="button" href="/">Torna alla home</a></p>
|
||||
{% endblock %}
|
||||
@@ -1,14 +1,5 @@
|
||||
<!doctype html>
|
||||
<html lang="it">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>PLM Lottery</title>
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
<h1>PLM Lottery</h1>
|
||||
<p>Il sito è in costruzione.</p>
|
||||
</main>
|
||||
</body>
|
||||
</html>
|
||||
{% extends "web/base.html" %}
|
||||
{% block content %}
|
||||
<h1>PLM Lottery</h1>
|
||||
<p>Il sito è in costruzione.</p>
|
||||
{% endblock %}
|
||||
@@ -5,5 +5,6 @@ from . import views
|
||||
app_name = "web"
|
||||
urlpatterns = [
|
||||
path("", views.home, name="home"),
|
||||
path("app/", views.app_home, name="app-home"),
|
||||
path("health/live", views.health_live, name="health-live"),
|
||||
]
|
||||
@@ -1,6 +1,8 @@
|
||||
from django.contrib.auth.decorators import login_required
|
||||
from django.db import connection
|
||||
from django.http import HttpResponse, JsonResponse
|
||||
from django.shortcuts import render
|
||||
from django.views.decorators.cache import never_cache
|
||||
|
||||
|
||||
def home(request):
|
||||
@@ -8,6 +10,13 @@ def home(request):
|
||||
return render(request, "web/home.html")
|
||||
|
||||
|
||||
@never_cache
|
||||
@login_required
|
||||
def app_home(request):
|
||||
"""Placeholder of the player area (WEB-20): the play screen arrives with A7."""
|
||||
return render(request, "web/app_home.html")
|
||||
|
||||
|
||||
def health_live(request):
|
||||
"""Liveness for the container healthcheck: the process answers and the database opens (ARC-73)."""
|
||||
try:
|
||||
@@ -16,3 +25,27 @@ def health_live(request):
|
||||
except Exception:
|
||||
return HttpResponse("database unavailable", status=503, content_type="text/plain")
|
||||
return JsonResponse({"status": "ok"})
|
||||
|
||||
|
||||
# Error pages in Italian, in the site's own layout, with a way out (WEB-06).
|
||||
|
||||
|
||||
def csrf_failure(request, reason=""):
|
||||
return render(request, "web/error.html", {
|
||||
"title": "Sessione scaduta",
|
||||
"message": "Il modulo non è più valido, probabilmente perché la pagina è rimasta aperta a lungo. "
|
||||
"Ricarica la pagina e riprova.",
|
||||
}, status=403)
|
||||
|
||||
|
||||
def not_found(request, exception=None):
|
||||
return render(request, "web/error.html", {
|
||||
"title": "Pagina non trovata", "message": "L'indirizzo richiesto non esiste.",
|
||||
}, status=404)
|
||||
|
||||
|
||||
def server_error(request):
|
||||
return render(request, "web/error.html", {
|
||||
"title": "Qualcosa è andato storto",
|
||||
"message": "Si è verificato un errore. Riprova fra qualche istante.",
|
||||
}, status=500)
|
||||
Reference in new issue
Block a user