Files
leocrm-bot 7a7daf8100 T01: core infrastructure + auth + multi-tenant + RLS
- 10 models: tenants, users, user_tenants, roles, sessions, audit_log, deletion_log, notifications, password_reset_tokens, api_tokens
- Session-based auth (Redis + PostgreSQL audit trail)
- Multi-tenant with ORM-level filtering + PostgreSQL RLS (set_config)
- RBAC with roles/permissions + field-level permissions
- CSRF protection via Origin header validation
- Auth rate limiting (Redis counters with TTL)
- CORS with explicit origins (no wildcard)
- Health endpoint (no auth required)
- Notification service + audit log middleware
- 29 tests, 26 ACs, all passing
- Coverage: 62% (infrastructure modules pending coverage in later tasks)
2026-06-29 00:10:10 +02:00

76 lines
2.2 KiB
Python

"""Tenant management routes."""
from __future__ import annotations
import uuid
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.db import get_db
from app.deps import get_current_user, require_admin
from app.schemas.tenant import TenantCreate, TenantUserAssign
from app.services.tenant_service import tenant_service
router = APIRouter(prefix="/api/v1/tenants", tags=["tenants"])
@router.get("")
async def list_tenants(
db: AsyncSession = Depends(get_db),
current_user: dict = Depends(get_current_user),
):
"""List tenants for the current user."""
user_id = uuid.UUID(current_user["user_id"])
tenants = await tenant_service.list_tenants_for_user(db, user_id)
return {"items": tenants}
@router.post("")
async def create_tenant(
body: TenantCreate,
db: AsyncSession = Depends(get_db),
current_user: dict = Depends(require_admin),
):
"""Create a new tenant (admin only)."""
tenant = await tenant_service.create_tenant(db, body.name, body.slug)
return {
"id": str(tenant.id),
"name": tenant.name,
"slug": tenant.slug,
}
@router.get("/{tenant_id}/users")
async def list_tenant_users(
tenant_id: str,
db: AsyncSession = Depends(get_db),
current_user: dict = Depends(require_admin),
):
"""List users in a tenant (admin only)."""
try:
tid = uuid.UUID(tenant_id)
except ValueError:
raise HTTPException(400, detail={"detail": "Invalid tenant_id", "code": "invalid_id"})
users = await tenant_service.list_tenant_users(db, tid)
return {"items": users}
@router.post("/{tenant_id}/users")
async def assign_user_to_tenant(
tenant_id: str,
body: TenantUserAssign,
db: AsyncSession = Depends(get_db),
current_user: dict = Depends(require_admin),
):
"""Assign a user to a tenant (admin only)."""
try:
tid = uuid.UUID(tenant_id)
uid = uuid.UUID(body.user_id)
except ValueError:
raise HTTPException(400, detail={"detail": "Invalid ID", "code": "invalid_id"})
ut = await tenant_service.assign_user_to_tenant(db, tid, uid)
return {"message": "User assigned to tenant"}