Files
mtusi2026lab3/app/deps.py
T
2026-10-13 19:11:11 +03:00

61 lines
1.7 KiB
Python

"""
FastAPI dependencies for Lab2:
- Bearer authentication;
- pagination query parameters.
"""
from typing import Optional
from fastapi import Depends, Query, Request, Security
from fastapi.security import HTTPAuthorizationCredentials, HTTPBasic, HTTPBearer
from sqlalchemy.ext.asyncio import AsyncSession
from app.db import get_db
from app.errors import Unauthorized
from app.services import current_user_from_bearer_token
# Security schemes make the "Authorize" button in /docs send real
# Authorization headers. Errors keep the contract format: auto_error=False
# and our own 401 responses.
bearer_scheme = HTTPBearer(
scheme_name="Bearer",
auto_error=False,
description="Opaque session token from POST /api/v1/auth/sessions.",
)
class BasicForDocs(HTTPBasic):
"""Documents Basic auth; the header is parsed by app.security."""
async def __call__(self, request: Request) -> None: # type: ignore[override]
return None
basic_scheme = BasicForDocs(
scheme_name="Basic",
auto_error=False,
description="Only for POST /api/v1/auth/sessions.",
)
async def require_user(
credentials: Optional[HTTPAuthorizationCredentials] = Security(
bearer_scheme
),
db: AsyncSession = Depends(get_db),
) -> dict:
if credentials is None or not credentials.credentials.strip():
raise Unauthorized("Bearer")
return await current_user_from_bearer_token(
db,
credentials.credentials.strip(),
)
def pagination_params(
limit: int = Query(default=50, ge=1, le=100),
cursor: Optional[str] = Query(default=None, min_length=1),
) -> tuple[int, Optional[str]]:
return limit, cursor