from django.conf import settings from django.shortcuts import redirect from django.urls import reverse from .models import User _SETUP_EXEMPT_PREFIXES = (settings.STATIC_URL,) class SetupWizardMiddleware: """Force every request to the first-run setup wizard until an account exists. Once any User row exists, /setup/ becomes unreachable again (see the setup view), mirroring FreshRSS's one-time install wizard. The "a user exists" check only ever flips false -> true for the lifetime of an instance, so it's cached per-process after the first positive result to avoid a query on every request. """ _a_user_exists = False def __init__(self, get_response): self.get_response = get_response def __call__(self, request): path = request.path if not path.startswith(_SETUP_EXEMPT_PREFIXES): if not SetupWizardMiddleware._a_user_exists: SetupWizardMiddleware._a_user_exists = User.objects.exists() setup_url = reverse("accounts:setup") if path != setup_url and not SetupWizardMiddleware._a_user_exists: return redirect(setup_url) return self.get_response(request)