Files
leocrm/app/routes/roles.py
T

223 lines
7.0 KiB
Python
Raw Normal View History

"""Role management routes."""
from __future__ import annotations
import uuid
from fastapi import APIRouter, Depends, HTTPException, Response, status
from fastapi.responses import JSONResponse
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.audit import log_audit
from app.core.auth import get_redis
from app.core.db import get_db
from app.core.permission_registry import CORE_PERMISSIONS, get_permission_registry
from app.core.permissions import invalidate_all_user_permissions
from app.deps import require_permission
from app.models.plugin import Plugin as PluginModel
from app.models.user import UserTenant
from app.plugins.registry import get_registry
from app.schemas.role import RoleCreate, RoleUpdate
from app.services.role_service import role_service
router = APIRouter(prefix="/api/v1/roles", tags=["roles"])
# Derived from CORE_PERMISSIONS so changes in permission_registry are reflected
# automatically. ``category`` is remapped to "system" because the frontend groups
# permissions by that value (SettingsGroups.tsx).
SYSTEM_PERMISSIONS: list[dict[str, str]] = [
{
"key": perm["key"],
"label": perm["label"],
"category": "system",
}
for perm in CORE_PERMISSIONS
]
@router.get("/permissions")
async def list_permissions(
db: AsyncSession = Depends(get_db),
current_user: dict = Depends(require_permission("roles:read")),
):
"""List all available permissions (system + active plugin permissions).
Returns permissions grouped by category:
- ``system``: built-in CRM permissions
- ``plugins``: permissions from active plugin manifests
"""
registry = get_registry()
plugin_perms: list[dict[str, str]] = []
# Fetch active plugin records from DB
result = await db.execute(
select(PluginModel).where(PluginModel.active == True) # noqa: E712
)
active_records = {row.name: row for row in result.scalars().all()}
# Collect permissions from active plugins' manifests
seen_keys: set[str] = set()
for name in registry.list_discovered():
if name not in active_records:
continue
plugin = registry.get_plugin(name)
if plugin is None:
continue
for perm in plugin.manifest.permissions:
if perm in seen_keys:
continue
seen_keys.add(perm)
plugin_perms.append({
"key": perm,
"label": perm.replace("_", " ").replace(":", ": ").title(),
"category": "plugins",
"plugin_name": name,
})
return {
"system": SYSTEM_PERMISSIONS,
"plugins": plugin_perms,
"all": SYSTEM_PERMISSIONS + plugin_perms,
"field_definitions": get_permission_registry().get_all_field_definitions(),
}
@router.get("")
async def list_roles(
db: AsyncSession = Depends(get_db),
current_user: dict = Depends(require_permission("roles:read")),
):
"""List roles for the current tenant."""
tenant_id = uuid.UUID(current_user["tenant_id"])
roles = await role_service.list_roles(db, tenant_id)
return {"items": roles}
@router.post("")
async def create_role(
body: RoleCreate,
db: AsyncSession = Depends(get_db),
current_user: dict = Depends(require_permission("roles:write")),
):
"""Create a custom role (admin only)."""
tenant_id = uuid.UUID(current_user["tenant_id"])
role = await role_service.create_role(
db,
tenant_id,
body.name,
body.permissions,
body.denied_permissions,
body.field_permissions,
)
return JSONResponse(
status_code=status.HTTP_201_CREATED,
content={
"id": str(role.id),
"name": role.name,
"permissions": role.permissions,
"denied_permissions": role.denied_permissions,
"field_permissions": role.field_permissions,
"permission_version": role.permission_version,
},
)
@router.patch("/{role_id}")
async def update_role(
role_id: str,
body: RoleUpdate,
db: AsyncSession = Depends(get_db),
current_user: dict = Depends(require_permission("roles:write")),
):
"""Update a role (admin only)."""
tenant_id = uuid.UUID(current_user["tenant_id"])
try:
rid = uuid.UUID(role_id)
except ValueError:
raise HTTPException(
400, detail={"detail": "Invalid role_id", "code": "invalid_id"}
) from None
role = await role_service.update_role(
db,
tenant_id,
rid,
body.name,
body.permissions,
body.denied_permissions,
body.field_permissions,
)
if role is None:
raise HTTPException(404, detail={"detail": "Role not found", "code": "not_found"})
# Invalidate permission cache for all users across all their tenants
redis = get_redis()
tenant_ids = {tenant_id}
ut_q = select(UserTenant.tenant_id).where(
UserTenant.user_id.in_(
select(UserTenant.user_id).where(UserTenant.tenant_id == tenant_id)
)
)
ut_result = await db.execute(ut_q)
for (tid,) in ut_result.all():
tenant_ids.add(tid)
for tid in tenant_ids:
await invalidate_all_user_permissions(redis, tid)
# Audit log
acting_user_id = uuid.UUID(current_user["user_id"])
await log_audit(
db, tenant_id, acting_user_id, "update", "role", rid,
changes=body.model_dump(exclude_none=True),
)
return {
"id": str(role.id),
"name": role.name,
"permissions": role.permissions,
"denied_permissions": role.denied_permissions,
"field_permissions": role.field_permissions,
"permission_version": role.permission_version,
}
@router.delete("/{role_id}")
async def delete_role(
role_id: str,
db: AsyncSession = Depends(get_db),
current_user: dict = Depends(require_permission("roles:write")),
):
"""Delete a role (admin only)."""
tenant_id = uuid.UUID(current_user["tenant_id"])
try:
rid = uuid.UUID(role_id)
except ValueError:
raise HTTPException(
400, detail={"detail": "Invalid role_id", "code": "invalid_id"}
) from None
success = await role_service.delete_role(db, tenant_id, rid)
if not success:
raise HTTPException(404, detail={"detail": "Role not found", "code": "not_found"})
# Invalidate permission cache for all users across all their tenants
redis = get_redis()
tenant_ids = {tenant_id}
ut_q = select(UserTenant.tenant_id).where(
UserTenant.user_id.in_(
select(UserTenant.user_id).where(UserTenant.tenant_id == tenant_id)
)
)
ut_result = await db.execute(ut_q)
for (tid,) in ut_result.all():
tenant_ids.add(tid)
for tid in tenant_ids:
await invalidate_all_user_permissions(redis, tid)
acting_user_id = uuid.UUID(current_user["user_id"])
await log_audit(db, tenant_id, acting_user_id, "delete", "role", rid)
return Response(status_code=status.HTTP_204_NO_CONTENT)