feat: Refactor cookie handling to use utility functions for setting access and refresh tokens
This commit is contained in:
@@ -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)
|
||||
|
||||
Reference in New Issue
Block a user