"""FastAPI dependencies for authentication and database access.""" from typing import Annotated from fastapi import Depends, HTTPException, status from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer from sqlalchemy.orm import Session from app.db.database import get_db from app.models.user import User from app.services.auth_service import AuthService, decode_token security = HTTPBearer() async def get_current_user( credentials: Annotated[HTTPAuthorizationCredentials, Depends(security)], db: Annotated[Session, Depends(get_db)], ) -> User: """Get the current authenticated user from JWT token. Args: credentials: The HTTP Bearer credentials containing the JWT token. db: Database session. Returns: The authenticated User object. Raises: HTTPException: If token is invalid or user not found. """ credentials_exception = HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid authentication credentials", headers={"WWW-Authenticate": "Bearer"}, ) try: payload = decode_token(credentials.credentials) user_id_str: str = payload.get("sub") if user_id_str is None: raise credentials_exception user_id = int(user_id_str) except (JWTError, ValueError): raise credentials_exception user = AuthService.get_user_by_id(db, user_id) if user is None: raise credentials_exception return user # Type alias for dependency injection CurrentUser = Annotated[User, Depends(get_current_user)]