import hashlib import hmac from django.conf import settings AUTH_MARKER_HEADER = "X-Evection-Auth" ANONYMOUS_MARKER = "anon" def auth_marker(user) -> str: """An opaque, stable identifier for who is logged in — "anon" if no one. Derived with an HMAC of the user's pk under SECRET_KEY, so it's constant for one user but reveals neither the pk nor anything guessable.""" if user is None or not user.is_authenticated: return ANONYMOUS_MARKER digest = hmac.new( settings.SECRET_KEY.encode(), f"evection-sw-auth:{user.pk}".encode(), hashlib.sha256 ).hexdigest() return digest[:16] class AuthMarkerMiddleware: """Stamps every HTML response with who it was rendered for. The service worker (templates/pwa/sw.js) caches authenticated pages for offline reading in a single cache; it compares this marker on every navigation and purges that cache whenever it changes — session expiry (the login page comes back as "anon"), logging in, switching accounts — so one session's pages can't be served to the next (R2-S3).""" def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) if response.get("Content-Type", "").startswith("text/html"): response[AUTH_MARKER_HEADER] = auth_marker(getattr(request, "user", None)) return response