import logging from django.contrib import messages from django.contrib.auth import login from django.contrib.auth.decorators import user_passes_test from django.contrib.auth.views import LoginView as DjangoLoginView from django.core.cache import cache from django.db import IntegrityError, transaction from django.shortcuts import redirect, render from .forms import CreateUserForm, SetupForm from .middleware import SetupWizardMiddleware from .models import SetupLock, User logger = logging.getLogger(__name__) is_admin = user_passes_test(lambda u: u.is_authenticated and u.is_staff) # Two independent throttles, either of which can block an attempt: by # client address (catches one attacker spraying many usernames) and by # the submitted username (catches a distributed/low-and-slow attack on # one specific account from many addresses). Both are generous enough # not to lock out a user who's just fat-fingered their own password a # few times. LOGIN_RATE_LIMIT_WINDOW_SECONDS = 5 * 60 LOGIN_RATE_LIMIT_MAX_ATTEMPTS_PER_ADDRESS = 15 LOGIN_RATE_LIMIT_MAX_ATTEMPTS_PER_USERNAME = 8 def _client_address(request) -> str: # gunicorn is always run behind a reverse proxy in every deployment # (see docs/install.md) and its bind address is never meant to be # reachable from outside that proxy — the same trust boundary # config.settings.prod already relies on for X-Forwarded-Proto. A # direct request (e.g. local dev) has no X-Forwarded-For and falls # back to REMOTE_ADDR. forwarded_for = request.META.get("HTTP_X_FORWARDED_FOR", "") if forwarded_for: return forwarded_for.split(",")[0].strip() return request.META.get("REMOTE_ADDR", "unknown") def _attempts_key(kind: str, value: str) -> str: return f"login-attempts:{kind}:{value}" def _too_many_attempts(key: str, limit: int) -> bool: # Fails open if the cache (Redis) is unreachable: logging in must keep # working through a cache outage, at the cost of no throttling until # it's back — an outage shouldn't lock every user out of the app. try: return cache.get(key, 0) >= limit except Exception: logger.warning("Login throttle cache unavailable; not rate limiting", exc_info=True) return False def _record_failed_attempt(key: str) -> None: try: try: cache.incr(key) except ValueError: cache.set(key, 1, LOGIN_RATE_LIMIT_WINDOW_SECONDS) except Exception: logger.warning("Login throttle cache unavailable; attempt not recorded", exc_info=True) class LoginView(DjangoLoginView): """Wraps Django's own LoginView with the throttle above — everything else (form, template, redirect behavior) is unchanged.""" template_name = "accounts/login.html" def post(self, request, *args, **kwargs): address_key = _attempts_key("addr", _client_address(request)) username_key = _attempts_key("user", request.POST.get("username", "")[:150]) if _too_many_attempts( address_key, LOGIN_RATE_LIMIT_MAX_ATTEMPTS_PER_ADDRESS ) or _too_many_attempts(username_key, LOGIN_RATE_LIMIT_MAX_ATTEMPTS_PER_USERNAME): messages.error( request, "Too many login attempts. Please wait a few minutes and try again." ) return redirect("accounts:login") return super().post(request, *args, **kwargs) def form_invalid(self, form): _record_failed_attempt(_attempts_key("addr", _client_address(self.request))) _record_failed_attempt(_attempts_key("user", self.request.POST.get("username", "")[:150])) return super().form_invalid(form) def setup(request): if User.objects.exists(): return redirect("accounts:login") form = SetupForm(request.POST or None) if request.method == "POST" and form.is_valid(): try: with transaction.atomic(): # Claims the one-time setup slot: the first of any # concurrent requests to reach this INSERT wins it, and # every other one raises IntegrityError instead of also # creating an admin account. See SetupLock's docstring. SetupLock.objects.create() user = form.save(commit=False) user.set_password(form.cleaned_data["password"]) user.is_staff = True user.is_superuser = True user.save() except IntegrityError: messages.info(request, "Setup was already completed. Log in with that account.") return redirect("accounts:login") SetupWizardMiddleware._a_user_exists = True login(request, user) messages.success(request, "Welcome to Evection! Your admin account is ready.") return redirect("reader:stream") return render(request, "accounts/setup.html", {"form": form}) @is_admin def manage_users(request): users = User.objects.order_by("username") return render(request, "accounts/manage_users.html", {"users": users}) @is_admin def create_user(request): form = CreateUserForm(request.POST or None) if request.method == "POST" and form.is_valid(): user = form.save(commit=False) user.set_password(form.cleaned_data["password"]) user.save() messages.success(request, f"Account '{user.username}' created.") return redirect("accounts:manage_users") return render(request, "accounts/create_user.html", {"form": form})