Fixed session cookies

This commit is contained in:
James Ketr 2025-09-05 11:38:05 -07:00
parent 2fdd58f7c3
commit 9a211c2ed4

View File

@ -5,7 +5,7 @@ This module contains session management endpoints.
""" """
from typing import TYPE_CHECKING from typing import TYPE_CHECKING
from fastapi import APIRouter from fastapi import APIRouter, Request, Response
# Import shared models # Import shared models
import sys import sys
@ -27,6 +27,17 @@ class SessionAPI:
self.router = APIRouter(prefix=f"{public_url}api") self.router = APIRouter(prefix=f"{public_url}api")
self._register_routes() self._register_routes()
def _is_valid_session_id(self, session_id: str) -> bool:
"""Check if session ID has the correct format (32-character hex string)"""
if not session_id or len(session_id) != 32:
return False
# Check if it's a valid hexadecimal string
try:
int(session_id, 16)
return True
except ValueError:
return False
def _register_routes(self): def _register_routes(self):
"""Register all session routes""" """Register all session routes"""
@ -35,10 +46,45 @@ class SessionAPI:
return HealthResponse(status="ok") return HealthResponse(status="ok")
@self.router.get("/session", response_model=SessionResponse) @self.router.get("/session", response_model=SessionResponse)
def get_session(): def get_session(request: Request, response: Response):
# Create new session only # Check for existing session cookie
session = self.session_manager.create_session() session_id = request.cookies.get("session_id")
logger.info(f"Created new session: {session.getName()}")
if session_id and self._is_valid_session_id(session_id):
# Try to get existing session
existing_session = self.session_manager.get_session(session_id)
if existing_session:
logger.info(f"Found existing session from cookie: {session_id[:8]}")
return SessionResponse(
id=existing_session.id,
name=existing_session.name or "",
lobbies=[], # Could be populated based on existing session
protected=False,
has_media=existing_session.has_media,
bot_run_id=existing_session.bot_run_id,
bot_provider_id=existing_session.bot_provider_id,
bot_instance_id=existing_session.bot_instance_id,
)
else:
# Cookie exists but session doesn't - create new session with this ID
logger.info(
f"Creating new session with cookie ID: {session_id[:8]}"
)
session = self.session_manager.create_session(session_id=session_id)
else:
# No valid cookie - create completely new session
session = self.session_manager.create_session()
logger.info(f"Created new session: {session.getName()}")
# Set the session cookie (expires in 30 days)
response.set_cookie(
key="session_id",
value=session.id,
max_age=30 * 24 * 60 * 60, # 30 days in seconds
httponly=True,
secure=False, # Set to True in production with HTTPS
samesite="lax",
)
return SessionResponse( return SessionResponse(
id=session.id, id=session.id,