Files
leocrm/app/routes/user_preferences.py
Agent Zero abbe7a18fc fix(audit): P0-P3 audit fixes — 838 ruff errors → 0, 30 F821 bugs fixed, 118 files changed
- P0: hooks.py 3-tuple fix, trigger_dispatcher Contract, contacts/plugin unregister_actions_by_owner
- P0: 5 test files — check_permission mocks removed, hardcoded DB credential → env var
- P1: attachment_service DmsFile via Contract helper, restore_registry/history_hooks dedup
- P1: mail/plugin restore unregister, mcp_client datetime.now(UTC), saved_views/filters patterns
- P1: ProtectedRoute fail-closed, 13 test assertion fixes (bcrypt, DB-URLs, SECRET_KEYs)
- P2: deprecated notifications → post_system_message (3 files), forgejo Base, report_generator lazy import
- P2: webhooks permissions, deps.py/roles.py plugin perms removed, import_export default
- P2: address/tags/entity_links patterns removed, worker.py Contract-Umgehungen fixed
- P2: 28 frontend TODOs (hardcoded constants, deprecated notification API)
- P3: dead code, duplicates, deprecated imports, private attr, __import__ inline
- P3: 8 frontend TODOs (LucideIcons, inline styles, XSS, i18n)
- ruff: 838 → 0 (612 auto-fix + 246 manual + 27 F821 regression fix)
- F821: 30 → 0 (AutomationDefinition, DmsFile, user_id, Path, Any, String)
- Contract-Umgehungen: 2 neue gefunden (worker.py:169, worker.py:280) und gefixt
2026-08-16 01:17:18 +02:00

196 lines
5.3 KiB
Python

"""User Preferences routes — per-user UI settings via API, tenant-scoped with RBAC."""
from __future__ import annotations
import uuid
from typing import Any
from fastapi import APIRouter, Depends, HTTPException, status
from pydantic import BaseModel, Field
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.db import get_db
from app.deps import require_permission
from app.models.user_preference import UserPreference
router = APIRouter(prefix="/api/v1/user/preferences", tags=["user-preferences"])
# ─── Schemas ───
class PreferenceValue(BaseModel):
"""Arbitrary JSON value for a preference key."""
value: Any = Field(..., description="JSON value for the preference key")
class PreferenceResponse(BaseModel):
"""Single preference entry response."""
key: str
value: Any
updated_at: str | None = None
class PreferenceListResponse(BaseModel):
"""All preferences for the current user."""
preferences: list[PreferenceResponse]
# ─── Helpers ───
def _pref_to_response(p: UserPreference) -> PreferenceResponse:
"""Convert UserPreference model to response schema."""
updated_at = None
try:
updated_at = p.updated_at.isoformat() if p.updated_at else None
except Exception:
pass
return PreferenceResponse(
key=p.key,
value=p.value,
updated_at=updated_at,
)
# ─── Endpoints ───
@router.get("")
async def list_user_preferences(
db: AsyncSession = Depends(get_db),
current_user: dict[str, Any] = Depends(
require_permission("user_preferences:read")
),
) -> PreferenceListResponse:
"""Get all preferences for the current user."""
tenant_id = uuid.UUID(current_user["tenant_id"])
user_id = uuid.UUID(current_user["user_id"])
result = await db.execute(
select(UserPreference)
.where(
UserPreference.tenant_id == tenant_id,
UserPreference.user_id == user_id,
UserPreference.deleted_at.is_(None),
)
.order_by(UserPreference.key)
)
prefs = result.scalars().all()
return PreferenceListResponse(
preferences=[_pref_to_response(p) for p in prefs]
)
@router.get("/{key}")
async def get_user_preference(
key: str,
db: AsyncSession = Depends(get_db),
current_user: dict[str, Any] = Depends(
require_permission("user_preferences:read")
),
) -> PreferenceResponse:
"""Get a single preference by key."""
tenant_id = uuid.UUID(current_user["tenant_id"])
user_id = uuid.UUID(current_user["user_id"])
result = await db.execute(
select(UserPreference).where(
UserPreference.tenant_id == tenant_id,
UserPreference.user_id == user_id,
UserPreference.key == key,
UserPreference.deleted_at.is_(None),
)
)
pref = result.scalar_one_or_none()
if pref is None:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail={
"detail": f"Preference '{key}' not found",
"code": "not_found",
},
)
return _pref_to_response(pref)
@router.put("/{key}")
async def upsert_user_preference(
key: str,
body: PreferenceValue,
db: AsyncSession = Depends(get_db),
current_user: dict[str, Any] = Depends(
require_permission("user_preferences:write")
),
) -> PreferenceResponse:
"""Create or update a preference by key (upsert)."""
tenant_id = uuid.UUID(current_user["tenant_id"])
user_id = uuid.UUID(current_user["user_id"])
result = await db.execute(
select(UserPreference).where(
UserPreference.tenant_id == tenant_id,
UserPreference.user_id == user_id,
UserPreference.key == key,
UserPreference.deleted_at.is_(None),
)
)
pref = result.scalar_one_or_none()
if pref is None:
pref = UserPreference(
tenant_id=tenant_id,
user_id=user_id,
key=key,
value=body.value,
)
db.add(pref)
else:
pref.value = body.value
await db.commit()
await db.refresh(pref)
return _pref_to_response(pref)
@router.delete("/{key}", status_code=status.HTTP_204_NO_CONTENT)
async def delete_user_preference(
key: str,
db: AsyncSession = Depends(get_db),
current_user: dict[str, Any] = Depends(
require_permission("user_preferences:write")
),
):
"""Delete a preference by key (soft-delete)."""
tenant_id = uuid.UUID(current_user["tenant_id"])
user_id = uuid.UUID(current_user["user_id"])
result = await db.execute(
select(UserPreference).where(
UserPreference.tenant_id == tenant_id,
UserPreference.user_id == user_id,
UserPreference.key == key,
UserPreference.deleted_at.is_(None),
)
)
pref = result.scalar_one_or_none()
if pref is None:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail={
"detail": f"Preference '{key}' not found",
"code": "not_found",
},
)
# Soft-delete via TenantMixin's deleted_at
from datetime import UTC, datetime
pref.deleted_at = datetime.now(UTC)
await db.commit()
return None