Private
Public Access
The setup view's User.objects.exists() check and the admin account's save() weren't in the same transaction, so two concurrent requests during first deployment could both pass the check and both create an admin account. SetupLock is a singleton row (pk=1); claiming it and creating the admin now happen in one atomic block, so only the first of any racing requests can succeed — the rest hit IntegrityError and are sent to the login page instead. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
59 lines
2.2 KiB
Python
59 lines
2.2 KiB
Python
from django.contrib import messages
|
|
from django.contrib.auth import login
|
|
from django.contrib.auth.decorators import user_passes_test
|
|
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
|
|
|
|
is_admin = user_passes_test(lambda u: u.is_authenticated and u.is_staff)
|
|
|
|
|
|
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})
|