Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

refactor(auth): single source of truth for session cookie attributes

Bingxi Zhao (Frank)7f5092ec60dd
diff --git a/deeptutor/api/routers/auth.py b/deeptutor/api/routers/auth.py
index 60481e09c..47e330618 100644
--- a/deeptutor/api/routers/auth.py
+++ b/deeptutor/api/routers/auth.py
@@ -57,6 +57,24 @@ _COOKIE_NAME = "dt_token"
_COOKIE_MAX_AGE = TOKEN_EXPIRE_HOURS * 3600
+def _cookie_attrs() -> dict:
+ """Attribute set shared by ``login``'s ``set_cookie`` and ``logout``'s
+ ``delete_cookie``.
+
+ The deletion ``Set-Cookie`` must carry the same attributes as the one
+ that created the cookie — ``delete_cookie`` defaults ``secure=False``,
+ which browsers reject when paired with ``SameSite=None``, silently
+ keeping the old cookie. See #623. Reads the module globals at call time
+ so tests can monkeypatch ``_SECURE``/``_SAMESITE``.
+ """
+ return {
+ "key": _COOKIE_NAME,
+ "httponly": True,
+ "samesite": _SAMESITE,
+ "secure": _SECURE,
+ }
+
+
# ---------------------------------------------------------------------------
# Schemas
# ---------------------------------------------------------------------------
@@ -399,14 +417,7 @@ async def login(body: LoginRequest, response: Response) -> dict:
detail="Incorrect email or password",
)
payload, pb_token = pb_result
- response.set_cookie(
- key=_COOKIE_NAME,
- value=pb_token,
- httponly=True,
- samesite=_SAMESITE,
- max_age=_COOKIE_MAX_AGE,
- secure=_SECURE,
- )
+ response.set_cookie(value=pb_token, max_age=_COOKIE_MAX_AGE, **_cookie_attrs())
logger.info(f"User '{payload.username}' logged in via PocketBase (role={payload.role!r})")
return {
"ok": True,
@@ -425,14 +436,7 @@ async def login(body: LoginRequest, response: Response) -> dict:
)
token = create_token(result.username, result.role, result.user_id)
- response.set_cookie(
- key=_COOKIE_NAME,
- value=token,
- httponly=True,
- samesite=_SAMESITE,
- max_age=_COOKIE_MAX_AGE,
- secure=_SECURE,
- )
+ response.set_cookie(value=token, max_age=_COOKIE_MAX_AGE, **_cookie_attrs())
logger.info(f"User '{result.username}' logged in (role={result.role!r})")
return {
@@ -448,16 +452,10 @@ async def login(body: LoginRequest, response: Response) -> dict:
async def logout(response: Response) -> dict:
"""Clear the JWT cookie.
- Attributes must mirror ``login``'s ``set_cookie`` call — ``delete_cookie``
- defaults ``secure=False``, which browsers reject when paired with
- ``SameSite=None`` and silently keep the old cookie. See #623.
+ Deletion attributes mirror ``login`` structurally via ``_cookie_attrs()``
+ (see the rationale there and #623).
"""
- response.delete_cookie(
- key=_COOKIE_NAME,
- httponly=True,
- samesite=_SAMESITE,
- secure=_SECURE,
- )
+ response.delete_cookie(**_cookie_attrs())
return {"ok": True}