fix(auth): return 401 for API paths in require_login to prevent wrong post-login redirect

The common.js fetch('/api/auth/whoami') probe on every page load was
overwriting the redirect_after_login session key with the API endpoint URL.
After login, users were sent to the JSON endpoint instead of the original page.

Fix: require_login now returns HTTP 401 for any /api/* path, consistent
with REST conventions, and never stores API URLs as the post-login redirect.

Co-authored-by: christianlouis <361235+christianlouis@users.noreply.github.com>
This commit is contained in:
copilot-swe-agent[bot]
2026-03-08 09:51:23 +00:00
parent 33a02633b7
commit 3aa5364e0c
3 changed files with 95 additions and 0 deletions
+27
View File
@@ -185,6 +185,33 @@ class TestRequireLogin:
assert isinstance(result, RedirectResponse)
assert result.status_code == status.HTTP_302_FOUND
@pytest.mark.asyncio
async def test_returns_401_for_api_path_when_not_authenticated(self):
"""Test returns 401 for /api/* paths instead of redirect-to-login.
Prevents the common.js /api/auth/whoami probe from overwriting
redirect_after_login, which would send the user to a JSON endpoint
after login instead of the page they originally requested.
"""
from fastapi.responses import JSONResponse
with patch("app.auth.AUTH_ENABLED", True):
@require_login
async def test_api_endpoint(request: Request):
return {"data": "ok"}
mock_request = MagicMock(spec=Request)
mock_request.session = {}
mock_request.url = MagicMock()
mock_request.url.__str__ = MagicMock(return_value="http://localhost/api/auth/whoami")
result = await test_api_endpoint(mock_request)
assert isinstance(result, JSONResponse)
assert result.status_code == status.HTTP_401_UNAUTHORIZED
assert "redirect_after_login" not in mock_request.session
@pytest.mark.unit
class TestOAuthConfiguration: