keyvault-api / src /dependencies.py
hashir-qt's picture
Upload folder using huggingface_hub
e656014 verified
Raw History Blame Contribute Delete
2.18 kB
from fastapi import Depends, HTTPException, status
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from sqlalchemy.ext.asyncio import AsyncSession
from src.database import get_db
from src.utils.security import decode_access_token
bearer_scheme = HTTPBearer()
async def get_current_user(
credentials: HTTPAuthorizationCredentials = Depends(bearer_scheme),
db: AsyncSession = Depends(get_db),
):
"""
Decode JWT and return the current authenticated user.
Raises 401 if token is missing, expired, or invalid.
"""
from src.services.auth_service import get_user_by_id # avoid circular import
token = credentials.credentials
payload = decode_access_token(token)
if payload is None:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid or expired token",
headers={"WWW-Authenticate": "Bearer"},
)
user_id: str = payload.get("sub")
if user_id is None:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Token missing subject",
)
user = await get_user_by_id(db, user_id)
if user is None:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="User not found",
)
return user
async def require_seller(current_user=Depends(get_current_user)):
"""Require the current user to have the SELLER role."""
from src.models.user import UserRole
if current_user.role not in (UserRole.SELLER, UserRole.ADMIN):
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Seller access required",
)
return current_user
async def require_admin(current_user=Depends(get_current_user)):
"""Require the current user to have the ADMIN role."""
from src.models.user import UserRole
if current_user.role != UserRole.ADMIN:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Admin access required",
)
return current_user