"""Better Auth session validation for backend API.""" from datetime import datetime from fastapi import HTTPException, status from sqlalchemy import select from sqlalchemy.ext.asyncio import AsyncSession from ..core.database import get_session from ..models.user import User from ..models.session import Session async def validate_session(session_token: str, db_session: AsyncSession) -> User | None: """ Validate Better Auth session token by querying the database directly. Args: session_token: Session token from cookie (format: sessionId.signature) db_session: Database session Returns: User object if valid, None if invalid """ try: # Better Auth tokens are signed: "sessionId.signature" # Database stores only the sessionId (first part before the dot) session_id = session_token.split('.')[0] # Single query with JOIN to get session and user together (optimization) from sqlalchemy.orm import selectinload stmt = ( select(Session) .where(Session.token == session_id) .where(Session.expires_at > datetime.utcnow()) # Filter expired sessions in query ) result = await db_session.execute(stmt) session = result.scalar_one_or_none() if not session: return None # Get user from session stmt = select(User).where(User.id == session.user_id) result = await db_session.execute(stmt) user = result.scalar_one_or_none() if not user: return None return user except Exception as e: print(f"❌ Validation error: {type(e).__name__}: {e}") import traceback traceback.print_exc() return None async def get_current_user_from_session( authorization: str | None, cookie: str | None, db_session: AsyncSession, ) -> User: """ Get current user from Better Auth session. Args: authorization: Authorization header value (optional) cookie: Cookie header value (for Better Auth session token) db_session: Database session Returns: User object Raises: HTTPException: If auth fails """ print(f"🔐 Auth attempt - Authorization header: {authorization is not None}, Cookie: {cookie is not None}") # Try Authorization header first (Bearer token) if authorization and authorization.startswith("Bearer "): print("🎫 Trying Bearer token from Authorization header") token = authorization[7:] user = await validate_session(token, db_session) if user: return user # Try cookie header (Better Auth session token) if cookie: print(f"🍪 Trying cookie header: {cookie[:100]}...") # Extract better-auth.session_token from cookie string import re from urllib.parse import unquote match = re.search(r'better-auth\.session_token=([^;]+)', cookie) if match: # URL decode the token (cookies are URL-encoded) token = unquote(match.group(1)) print(f"✅ Found session token in cookie (decoded)") user = await validate_session(token, db_session) if user: return user else: print(f"❌ No better-auth.session_token found in cookie") print("❌ Authentication failed - no valid token found") raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Missing or invalid authentication", )