"""Whose conversation this is. A conversation is private to the user who started it — there is no sharing and no admin view. One gate, used by every endpoint in the package, so the rule cannot quietly differ between reading and writing. """ import uuid from sqlalchemy import select from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy.orm import selectinload from app.errors import ApiError from app.models import Conversation, User async def own_conversation( db: AsyncSession, conversation_id: uuid.UUID, user: User, *, with_messages: bool = False, ) -> Conversation: stmt = select(Conversation).where( Conversation.id == conversation_id, Conversation.user_id == user.id ) if with_messages: stmt = stmt.options(selectinload(Conversation.messages)) conversation = (await db.execute(stmt)).scalar_one_or_none() if conversation is None: # 404 rather than 403: someone else's conversation must not be # confirmed to exist. raise ApiError(404, "Conversation not found.", "not_found") return conversation