File size: 2,671 Bytes
bda4716
 
 
 
 
 
 
 
 
 
 
 
 
1307382
 
 
 
 
 
 
 
 
 
bda4716
1307382
 
bda4716
1307382
 
 
 
 
 
 
bda4716
 
 
 
 
 
 
 
1307382
bda4716
 
 
 
 
 
 
 
 
 
1307382
bda4716
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from fastapi import Depends, HTTPException, status, Request
from sqlmodel import Session
from typing import Generator
from ..database import get_session_dep
from ..models.user import User
from .security import verify_user_id_from_token
from uuid import UUID


def get_current_user(
    request: Request,
    session: Session = Depends(get_session_dep)
) -> User:
    """Dependency to get the current authenticated user from JWT token in cookie or Authorization header.

    This accepts the token from either:
      - an HttpOnly cookie named `access_token` (cookie-based flows)
      - an Authorization Bearer header (e.g. `Authorization: Bearer <token>`) — helpful for cross-site frontends
    """
    # Debug: Print all cookies (do not print token values)
    print(f"All cookies received: { {k: '***' for k in request.cookies.keys()} }")

    # Try cookie first (usual flow when cookies are allowed)
    token = request.cookies.get("access_token")

    # If no cookie token, fall back to Authorization header
    if not token:
        auth_header = request.headers.get("Authorization") or request.headers.get("authorization")
        if auth_header and auth_header.lower().startswith("bearer "):
            token = auth_header.split(" ", 1)[1]
            print("Using Bearer token from Authorization header")

    if not token:
        print("No access token found in cookies or Authorization header")
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Not authenticated",
            headers={"WWW-Authenticate": "Bearer"},
        )

    user_id = verify_user_id_from_token(token)
    print(f"User ID from token: {user_id}")

    if not user_id:
        print("Invalid user ID from token")
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Invalid authentication credentials",
            headers={"WWW-Authenticate": "Bearer"},
        )

    user = session.get(User, user_id)
    print(f"User from database: {user}")

    if not user:
        print("User not found in database")
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Invalid authentication credentials",
            headers={"WWW-Authenticate": "Bearer"},
        )

    return user


def get_user_by_id(
    user_id: UUID,
    session: Session = Depends(get_session_dep)
) -> User:
    """Dependency to get a user by ID from the database."""
    user = session.get(User, user_id)
    if not user:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="User not found"
        )
    return user