Spaces:
Running
Running
File size: 3,698 Bytes
cd61bf7 c5aa5c4 cd61bf7 c5aa5c4 cd61bf7 c5aa5c4 cd61bf7 c5aa5c4 cd61bf7 20ee727 cd61bf7 c5aa5c4 cd61bf7 c5aa5c4 cd61bf7 20ee727 c5aa5c4 cd61bf7 c5aa5c4 cd61bf7 c5aa5c4 cd61bf7 | 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 110 111 112 113 | """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
|