"""FastAPI dependencies for authentication and authorization.""" from fastapi import Depends, HTTPException, status from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials from sqlmodel import select from sqlmodel.ext.asyncio.session import AsyncSession from uuid import UUID from app.core.database import get_async_session from app.core.security import decode_access_token from app.models import User # Security scheme security = HTTPBearer() from app.core.logging import get_logger logger = get_logger(__name__) async def get_current_user( credentials: HTTPAuthorizationCredentials = Depends(security), session: AsyncSession = Depends(get_async_session) ) -> User: """Dependency to get the current authenticated user from JWT token.""" token = credentials.credentials try: payload = decode_access_token(token) except Exception as e: logger.error(f"Token decode failed: {e}") raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token", headers={"WWW-Authenticate": "Bearer"}, ) user_id: str = payload.get("sub") if user_id is None: logger.error("Token missing 'sub' claim") raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Could not validate credentials", headers={"WWW-Authenticate": "Bearer"}, ) # Check Cache from app.services.cache_service import cache_service cache_key = f"user:{user_id}" cached_data = await cache_service.get(cache_key) if cached_data: try: # Reconstruct User from cache # User is a SQLModel, which is Pydantic v2 compatible user = User.model_validate(cached_data) return user except Exception as e: logger.warning(f"Failed to validate cached user: {e}") # Fallback to DB result = await session.execute( select(User).where(User.id == UUID(user_id)) ) user = result.scalar_one_or_none() if user is None: logger.error(f"User {user_id} not found in DB") raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="User not found", headers={"WWW-Authenticate": "Bearer"}, ) if not user.is_active: logger.warning(f"User {user.email} is inactive") raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail="Inactive user" ) # Cache the user (5 minutes) try: # model_dump(mode='json') serializes datetimes to iso strings await cache_service.set(cache_key, user.model_dump(mode='json'), ttl=300) except Exception as e: logger.error(f"Failed to cache user: {e}") # logger.info(f"Auth success: {user.email} ({user.role})") # Too noisy for prod, but good for debug return user async def get_current_active_user( current_user: User = Depends(get_current_user) ) -> User: if not current_user.is_active: raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail="Inactive user" ) return current_user async def get_current_superuser( current_user: User = Depends(get_current_user) ) -> User: if not current_user.is_superuser: logger.warning(f"Access DENIED: User {current_user.email} is NOT a superuser") raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail="Not enough permissions" ) logger.info(f"Superuser access granted: {current_user.email}") return current_user