import uuid from typing import Annotated from fastapi import Depends, Request from sqlalchemy.ext.asyncio import AsyncSession from app.auth.sessions import COOKIE_NAME, get_valid_session from app.db import get_db from app.errors import ApiError from app.models import AuthSession, User, UserRole async def get_current_auth_session( request: Request, db: Annotated[AsyncSession, Depends(get_db)] ) -> AuthSession: raw = request.cookies.get(COOKIE_NAME) if raw is None: raise ApiError(401, "Not authenticated.", "not_authenticated") try: session_id = uuid.UUID(raw) except ValueError: raise ApiError(401, "Not authenticated.", "not_authenticated") from None session = await get_valid_session(db, session_id) if session is None: raise ApiError(401, "Not authenticated.", "not_authenticated") return session async def get_current_user( session: Annotated[AuthSession, Depends(get_current_auth_session)], ) -> User: return session.user async def require_admin( user: Annotated[User, Depends(get_current_user)], ) -> User: if user.role != UserRole.admin: raise ApiError(403, "Admin privileges required.", "forbidden") return user