32 lines
944 B
Python
32 lines
944 B
Python
"""Helpers de validation d'appartenance multi-groupe."""
|
|
from fastapi import HTTPException
|
|
from sqlalchemy import select
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
|
|
|
|
async def get_owned_or_404(
|
|
db: AsyncSession,
|
|
model,
|
|
object_id,
|
|
groupe_id,
|
|
detail: str = "Objet introuvable",
|
|
*extra_conditions,
|
|
):
|
|
"""Charge un objet par id seulement s'il appartient au groupe demandé."""
|
|
conditions = [model.id == object_id, model.groupe_id == groupe_id, *extra_conditions]
|
|
result = await db.execute(select(model).where(*conditions))
|
|
obj = result.scalar_one_or_none()
|
|
if not obj:
|
|
raise HTTPException(status_code=404, detail=detail)
|
|
return obj
|
|
|
|
|
|
async def ensure_owned_or_404(
|
|
db: AsyncSession,
|
|
model,
|
|
object_id,
|
|
groupe_id,
|
|
detail: str = "Objet introuvable",
|
|
*extra_conditions,
|
|
):
|
|
return await get_owned_or_404(db, model, object_id, groupe_id, detail, *extra_conditions)
|