"""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]: """Parse HTTP cookie header into a dictionary.""" cookies: dict[str, str] = {} if not cookie_header: return cookies for cookie_part in cookie_header.split(";"): cookie_str = cookie_part.strip() if "=" in cookie_str: name, value = cookie_str.split("=", 1) cookies[name.strip()] = value.strip() return cookies 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)