Download src/middleware/phi_middleware.py from anaselamr/yaz: direct link, hf CLI and curl.
- Browser
- Download file 2.36 kB
-
https://huggingface.co/spaces/anaselamr/yaz/resolve/main/src/middleware/phi_middleware.py
- Command line
-
hf download hf://spaces/anaselamr/yaz/src/middleware/phi_middleware.py
-
curl -L -o phi_middleware.py https://huggingface.co/spaces/anaselamr/yaz/resolve/main/src/middleware/phi_middleware.py
2.36 kB
| """ | |
| PHI (Protected Health Information) Middleware | |
| HIPAA-compliant access control for healthcare data | |
| """ | |
| from functools import wraps | |
| from typing import Callable | |
| import structlog | |
| from core.api.dependencies import TokenClaims, get_current_user | |
| from fastapi import Depends, HTTPException, status | |
| logger = structlog.get_logger(__name__) | |
| def require_phi_access(roles: list = None): # type: ignore[arg-type, assignment] | |
| """ | |
| Decorator to require PHI access permissions | |
| Args: | |
| roles: Optional list of roles that can access PHI data | |
| If None, requires any authenticated user | |
| Usage: | |
| @router.get("/patient-data") | |
| @require_phi_access() | |
| async def get_patient_data(...): | |
| ... | |
| """ | |
| def decorator(func: Callable): | |
| async def wrapper(*args, current_user: TokenClaims = Depends(get_current_user), **kwargs): | |
| # Check if user has required role | |
| if roles: | |
| if not any(role in current_user.roles for role in roles): | |
| logger.warning( | |
| f"PHI access denied for user {current_user.user_id}: " | |
| f"required roles {roles}, user has {current_user.roles}" | |
| ) | |
| raise HTTPException( | |
| status_code=status.HTTP_403_FORBIDDEN, | |
| detail="Insufficient permissions to access PHI data", | |
| ) | |
| # Log PHI access for audit trail | |
| logger.info( | |
| f"PHI access granted: user={current_user.user_id}, " | |
| f"function={func.__name__}, tenant={current_user.tenant_id}" | |
| ) | |
| # Execute the function | |
| return await func(*args, current_user=current_user, **kwargs) | |
| return wrapper | |
| return decorator | |
| def get_current_user_dependency(): | |
| """ | |
| Dependency function for getting current user | |
| Used in Insura API routes | |
| """ | |
| async def _get_current_user(credentials=Depends(get_current_user)) -> dict: | |
| return { | |
| "user_id": credentials.user_id, | |
| "username": credentials.username, | |
| "tenant_id": credentials.tenant_id, | |
| "roles": credentials.roles, | |
| "permissions": credentials.permissions, | |
| } | |
| return _get_current_user | |