Files
plm-lottery/apps/accounts/views.py
T

167 lines
7.7 KiB
Python

"""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 apps.lottery.models import Report
from . import throttle
from .client_ip import client_ip
from .forms import LoginForm, PasswordChangeForm, RegisterForm, ReportForm
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)
def _profile_context(request, *, form=None, report_form=None) -> dict:
"""Only the signed-in user's own data and reports (WEB-03)."""
return {
"form": form or PasswordChangeForm(request.user),
"report_form": report_form or ReportForm(),
"reports": Report.objects.filter(user=request.user).order_by("-created_at", "-id"),
}
@never_cache
@login_required
@require_POST
def report_view(request):
"""WEB-55: send a problem report. A rejected form does not use the quota; a sent one does."""
key = str(request.user.pk)
wait = throttle.retry_after(throttle.REPORT, key)
form = ReportForm(request.POST)
if wait > 0:
return _too_many(request, "accounts/profile.html", _profile_context(request, report_form=form), wait)
if not form.is_valid():
return render(request, "accounts/profile.html", _profile_context(request, report_form=form), status=400)
with transaction.atomic():
report = Report.objects.create(user=request.user, text=form.cleaned_data["text"])
audit.record("report_submitted", actor=request.user, subject_type="report", subject_id=report.pk)
throttle.record(throttle.REPORT, key)
messages.success(request, "Segnalazione inviata. Ne vedrai lo stato qui sotto.")
return redirect("accounts:profile")
@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", _profile_context(request, 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", _profile_context(request, form=form))