feat: Refactor cookie handling to use utility functions for setting access and refresh tokens
All checks were successful
Backend CI / lint (push) Successful in 9m30s
Backend CI / test (push) Successful in 3m31s

This commit is contained in:
JSC
2025-08-08 10:06:45 +02:00
parent b4f0f54516
commit 69544b6bb8
2 changed files with 79 additions and 85 deletions

View File

@@ -1,4 +1,8 @@
"""Cookie parsing utilities for WebSocket authentication."""
"""Cookie parsing and setting utilities for WebSocket and HTTP authentication."""
from fastapi import Response
from app.core.config import settings
def parse_cookies(cookie_header: str) -> dict[str, str]:
@@ -20,3 +24,52 @@ def extract_access_token_from_cookies(cookie_header: str) -> str | None:
"""Extract access token from HTTP cookies."""
cookies = parse_cookies(cookie_header)
return cookies.get("access_token")
def set_access_token_cookie(
response: Response,
access_token: str,
expires_in: int,
path: str = "/",
) -> None:
"""Set access token cookie with consistent configuration."""
response.set_cookie(
key="access_token",
value=access_token,
max_age=expires_in,
httponly=True,
secure=settings.COOKIE_SECURE,
samesite=settings.COOKIE_SAMESITE,
domain="localhost", # Allow cookie across localhost ports
path=path,
)
def set_refresh_token_cookie(
response: Response,
refresh_token: str,
path: str = "/",
) -> None:
"""Set refresh token cookie with consistent configuration."""
response.set_cookie(
key="refresh_token",
value=refresh_token,
max_age=settings.JWT_REFRESH_TOKEN_EXPIRE_DAYS * 24 * 60 * 60,
httponly=True,
secure=settings.COOKIE_SECURE,
samesite=settings.COOKIE_SAMESITE,
domain="localhost", # Allow cookie across localhost ports
path=path,
)
def set_auth_cookies(
response: Response,
access_token: str,
refresh_token: str,
expires_in: int,
path: str = "/",
) -> None:
"""Set both access and refresh token cookies with consistent configuration."""
set_access_token_cookie(response, access_token, expires_in, path)
set_refresh_token_cookie(response, refresh_token, path)