baseball-engine / backend /app /core /dependencies.py
github-actions[bot]
Automated Deploy: 8f8167dc5709c2ea13b6f4ea7a93cc50c9b953cd
7a3215f
Raw History Blame Contribute Delete
1.75 kB
"""Request dependencies shared by all controllers."""
from typing import Annotated
from uuid import UUID
from fastapi import Depends, Header, Request
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.database import get_db
from app.core.errors import Forbidden, Unauthenticated
from app.core.pagination import PageParams, page_params
from app.core.security import decode_access_token
from app.integrations.storage import StorageClient, get_storage
from app.modules.accounts.models import Account
Db = Annotated[AsyncSession, Depends(get_db)]
Storage = Annotated[StorageClient, Depends(get_storage)]
Paging = Annotated[PageParams, Depends(page_params)]
def current_account_id(authorization: Annotated[str | None, Header()] = None) -> UUID:
if not authorization or not authorization.lower().startswith("bearer "):
raise Unauthenticated()
return decode_access_token(authorization[7:].strip())
async def current_account(
db: Db, account_id: Annotated[UUID, Depends(current_account_id)], request: Request,
) -> Account:
account = await db.get(Account, account_id)
if account is None:
raise Unauthenticated()
request.state.audit_account_id = account.id
return account
CurrentAccount = Annotated[Account, Depends(current_account)]
async def require_coach(account: CurrentAccount) -> Account:
if account.role != "coach":
raise Forbidden("Only coaches can do this.")
return account
async def require_player(account: CurrentAccount) -> Account:
if account.role != "player":
raise Forbidden("Only players can do this.")
return account
CurrentCoach = Annotated[Account, Depends(require_coach)]
CurrentPlayer = Annotated[Account, Depends(require_player)]