Fixed session cookies
This commit is contained in:
parent
2fdd58f7c3
commit
9a211c2ed4
@ -5,7 +5,7 @@ This module contains session management endpoints.
|
||||
"""
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
from fastapi import APIRouter
|
||||
from fastapi import APIRouter, Request, Response
|
||||
|
||||
# Import shared models
|
||||
import sys
|
||||
@ -27,6 +27,17 @@ class SessionAPI:
|
||||
self.router = APIRouter(prefix=f"{public_url}api")
|
||||
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):
|
||||
"""Register all session routes"""
|
||||
|
||||
@ -35,11 +46,46 @@ class SessionAPI:
|
||||
return HealthResponse(status="ok")
|
||||
|
||||
@self.router.get("/session", response_model=SessionResponse)
|
||||
def get_session():
|
||||
# Create new session only
|
||||
def get_session(request: Request, response: Response):
|
||||
# Check for existing session cookie
|
||||
session_id = request.cookies.get("session_id")
|
||||
|
||||
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(
|
||||
id=session.id,
|
||||
name=session.name or "",
|
||||
|
Loading…
x
Reference in New Issue
Block a user