from typing import List from fastapi import Depends, HTTPException, status from sqlalchemy.orm import Session from app.db.session import get_db from app.dependencies.auth import get_current_active_user from app.models.user import User def check_user_role(required_roles: List[str]): """ Dependency to check if a user has the required role(s). """ async def _check_user_role( current_user: User = Depends(get_current_active_user), db: Session = Depends(get_db) ) -> User: # If no roles required, return user if not required_roles: return current_user # Get all user roles user_roles = [role.name for role in current_user.roles] # Check if user has any of the required roles for role in required_roles: if role in user_roles: return current_user # If user doesn't have any required role, raise exception raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail="You don't have the required permissions to access this resource" ) return _check_user_role