diff --git a/backend/src/ea_chatbot/api/routers/auth.py b/backend/src/ea_chatbot/api/routers/auth.py index 2dd3c34..5add78a 100644 --- a/backend/src/ea_chatbot/api/routers/auth.py +++ b/backend/src/ea_chatbot/api/routers/auth.py @@ -1,7 +1,8 @@ +from typing import Optional from fastapi import APIRouter, Depends, HTTPException, status, Response, Request from fastapi.responses import RedirectResponse from fastapi.security import OAuth2PasswordRequestForm -from ea_chatbot.api.utils import create_access_token, settings +from ea_chatbot.api.utils import create_access_token, create_refresh_token, settings from ea_chatbot.api.dependencies import history_manager, oidc_client, get_current_user from ea_chatbot.history.models import User as UserDB from ea_chatbot.api.schemas import Token, UserCreate, UserResponse, ThemeUpdate @@ -12,16 +13,34 @@ logger = logging.getLogger(__name__) router = APIRouter(prefix="/auth", tags=["auth"]) -def set_auth_cookie(response: Response, token: str): +def set_auth_cookie(response: Response, access_token: str, refresh_token: Optional[str] = None): + # Set Access Token Cookie response.set_cookie( key="access_token", - value=token, + value=access_token, httponly=True, - max_age=1800, - expires=1800, + max_age=settings.access_token_expire_minutes * 60, + expires=settings.access_token_expire_minutes * 60, samesite="lax", secure=not settings.dev_mode, ) + + # Set Refresh Token Cookie if provided + if refresh_token: + response.set_cookie( + key="refresh_token", + value=refresh_token, + httponly=True, + max_age=settings.refresh_token_expire_days * 24 * 60 * 60, + expires=settings.refresh_token_expire_days * 24 * 60 * 60, + path=f"{settings.api_v1_str}/auth/refresh", # Only send to refresh endpoint + samesite="lax", + secure=not settings.dev_mode, + ) + +def clear_auth_cookies(response: Response): + response.delete_cookie(key="access_token") + response.delete_cookie(key="refresh_token", path=f"{settings.api_v1_str}/auth/refresh") @router.post("/register", response_model=UserResponse, status_code=status.HTTP_201_CREATED) async def register(user_in: UserCreate, response: Response): diff --git a/backend/src/ea_chatbot/config.py b/backend/src/ea_chatbot/config.py index 572f122..05c85eb 100644 --- a/backend/src/ea_chatbot/config.py +++ b/backend/src/ea_chatbot/config.py @@ -21,6 +21,7 @@ class Settings(BaseSettings): log_level: str = Field(default="INFO", alias="LOG_LEVEL") dev_mode: bool = Field(default=False, alias="DEV_MODE") frontend_url: str = Field(default="http://localhost:5173", alias="FRONTEND_URL") + api_v1_str: str = "/api/v1" # Voter Database configuration db_host: str = Field(default="localhost", alias="DB_HOST")