Prevent authenticated pages appearing after logout

This commit is contained in:
A R R R Associates
2026-08-01 13:35:30 +05:30
parent 2c415c38b9
commit 181d4f2c2e
3 changed files with 57 additions and 1 deletions
+19
View File
@@ -1,8 +1,15 @@
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.requests import Request
from app.core.security.session_auth import SESSION_USER_ID_KEY
class SecurityHeadersMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request: Request, call_next):
# Capture authentication state before the route runs. Logout clears the
# session during the request, but its response must still be non-cacheable.
was_authenticated = bool(request.session.get(SESSION_USER_ID_KEY))
resp = await call_next(request)
resp.headers["X-Content-Type-Options"] = "nosniff"
resp.headers["X-Frame-Options"] = "DENY"
@@ -18,4 +25,16 @@ class SecurityHeadersMiddleware(BaseHTTPMiddleware):
"connect-src 'self'; "
"frame-ancestors 'none';"
)
# Authenticated ERP pages contain client, PAN, document, billing and
# engagement data. Prevent browsers and intermediary caches from storing
# them, including responses generated immediately before logout.
is_authenticated = bool(request.session.get(SESSION_USER_ID_KEY))
if was_authenticated or is_authenticated:
resp.headers["Cache-Control"] = (
"no-store, no-cache, must-revalidate, private, max-age=0"
)
resp.headers["Pragma"] = "no-cache"
resp.headers["Expires"] = "0"
return resp