File size: 3,564 Bytes
507973e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
"""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",
    )