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) and path not in _setup_exempt_paths(): 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) def _setup_exempt_paths(): """Routes that must work even before the instance's first-run setup is complete: the manifest/service worker/offline page (a browser can fetch these on any visit, setup page included — it extends the same base template) and the health check (ops tooling, e.g. scripts/upgrade.sh, needs it reachable immediately after a fresh deploy, before anyone has created an account).""" return { reverse("pwa:manifest"), reverse("pwa:service_worker"), reverse("pwa:offline"), reverse("core:health"), reverse("core:health_ready"), }