Spaces:
Paused

yaz / src /core /multitenancy /api.py
anaselamr's picture
chore: stage remaining modified files from Sprint 44 batch
16a78e2
Raw History Blame Contribute Delete
3.72 kB
"""
Multi-Tenant API Endpoints
Sprint 29 Task 29.3
Admin endpoints for tenant management.
SECURITY: All endpoints require admin role — enforced via require_admin dependency.
"""
from fastapi import APIRouter, Depends, HTTPException, status
from typing import List, Optional
from core.multitenancy.service import TenantConfig, TenantUsage, TenantService
from core.multitenancy.tenant import get_tenant_id
# Admin RBAC guard
try:
from core.dependencies import require_role, get_current_user
_require_admin = require_role("admin")
except ImportError:
# Fallback: plain get_current_user (at minimum requires a valid token)
try:
from core.dependencies import get_current_user
_require_admin = get_current_user
except ImportError:
_require_admin = None
router = APIRouter(
prefix="/api/admin/tenants",
tags=["tenant-management"],
# Apply admin guard to every route in this router
dependencies=[Depends(_require_admin)] if _require_admin else [],
)
tenant_service = TenantService()
@router.post("/", response_model=TenantConfig, status_code=status.HTTP_201_CREATED)
async def create_tenant(config: TenantConfig):
"""Create new tenant. Requires admin role."""
return await tenant_service.create_tenant(config)
@router.get("/", response_model=List[TenantConfig])
async def list_tenants(
status: Optional[str] = None,
subscription_tier: Optional[str] = None,
limit: int = 100,
offset: int = 0,
):
"""List all tenants. Requires admin role."""
return await tenant_service.list_tenants(
status=status, subscription_tier=subscription_tier, limit=limit, offset=offset
)
@router.get("/{tenant_id}", response_model=TenantConfig)
async def get_tenant(tenant_id: str):
"""Get tenant configuration. Requires admin role."""
config = await tenant_service.get_tenant(tenant_id)
if not config:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND, detail=f"Tenant not found: {tenant_id}"
)
return config
@router.patch("/{tenant_id}", response_model=TenantConfig)
async def update_tenant(tenant_id: str, updates: dict):
"""Update tenant configuration. Requires admin role."""
return await tenant_service.update_tenant(tenant_id, updates)
@router.post("/{tenant_id}/suspend")
async def suspend_tenant(tenant_id: str, reason: str):
"""Suspend tenant (temporary). Requires admin role."""
await tenant_service.suspend_tenant(tenant_id, reason)
return {"message": f"Tenant {tenant_id} suspended", "reason": reason}
@router.post("/{tenant_id}/reactivate")
async def reactivate_tenant(tenant_id: str):
"""Reactivate suspended tenant. Requires admin role."""
await tenant_service.reactivate_tenant(tenant_id)
return {"message": f"Tenant {tenant_id} reactivated"}
@router.delete("/{tenant_id}")
async def delete_tenant(tenant_id: str):
"""
Delete tenant permanently. Requires admin role.
CAUTION: This operation cannot be undone.
"""
await tenant_service.delete_tenant(tenant_id)
return {"message": f"Tenant {tenant_id} deleted"}
@router.get("/{tenant_id}/usage", response_model=TenantUsage)
async def get_tenant_usage(tenant_id: str):
"""Get tenant resource usage and quota status. Requires admin role."""
return await tenant_service.get_tenant_usage(tenant_id)
@router.get("/{tenant_id}/violations")
async def check_quota_violations(tenant_id: str):
"""Check if tenant is violating any resource quotas. Requires admin role."""
violations = await tenant_service.check_quota_violation(tenant_id)
return {"tenant_id": tenant_id, "has_violations": len(violations) > 0, "violations": violations}