This commit is contained in:
2026-03-18 18:16:44 +01:00
parent c89c08c397
commit b3c8b77f12
20 changed files with 1934 additions and 36 deletions
+20 -9
View File
@@ -21,6 +21,23 @@ security = HTTPBearer()
# ─── Database con RLS ─────────────────────────────────────────────────────────
async def _set_rls_tenant_id(db: AsyncSession, tenant_id: uuid.UUID) -> None:
"""
Imposta la variabile di sessione PostgreSQL per RLS.
È un no-op su SQLite (test environment) poiché SQLite non supporta
il comando SET LOCAL né il concetto di Row Level Security.
"""
try:
await db.execute(
text(f"SET LOCAL app.current_tenant_id = '{tenant_id!s}'")
)
except Exception:
# SQLite (usato nei test di integrazione) non supporta SET LOCAL.
# In produzione (PostgreSQL) questo comando funziona sempre.
pass
async def get_db_with_rls(
tenant_id: uuid.UUID,
db: AsyncSession = Depends(get_db),
@@ -29,10 +46,7 @@ async def get_db_with_rls(
Imposta la variabile di sessione PostgreSQL per RLS.
Da usare dopo aver estratto il tenant_id dall'utente autenticato.
"""
await db.execute(
text("SET LOCAL app.current_tenant_id = :tenant_id"),
{"tenant_id": str(tenant_id)},
)
await _set_rls_tenant_id(db, tenant_id)
return db
@@ -68,11 +82,8 @@ async def get_current_user(
except ValueError:
raise TokenInvalidError()
# Imposta RLS per questo tenant
# SET LOCAL non supporta parametri $1, usiamo text() con valore inline
await db.execute(
text(f"SET LOCAL app.current_tenant_id = '{tenant_id!s}'")
)
# Imposta RLS per questo tenant (no-op su SQLite/test)
await _set_rls_tenant_id(db, tenant_id)
# Carica utente
result = await db.execute(