forked from mtusi2026/mtusi2026lab5
prepared skeleton for lab5
This commit is contained in:
@@ -0,0 +1,52 @@
|
||||
"""HTTP-параметры и упаковка ответов; сценарии находятся в domain."""
|
||||
|
||||
from typing import Annotated
|
||||
from urllib.parse import quote
|
||||
from uuid import UUID
|
||||
|
||||
from fastapi import APIRouter, Query, Request
|
||||
from fastapi.responses import StreamingResponse
|
||||
from starlette.background import BackgroundTask
|
||||
|
||||
from app.domain import attachments
|
||||
from app.endpoints.dependencies import CurrentUser, DbSession, S3Storage, UploadCapacity
|
||||
from app.schemas.attachment import Attachment
|
||||
|
||||
router = APIRouter(prefix='/api/v1', tags=['attachments'])
|
||||
|
||||
|
||||
@router.post('/chats/{chat_id}/attachments', status_code=201)
|
||||
async def upload(
|
||||
request: Request, chat_id: UUID, user: CurrentUser, session: DbSession,
|
||||
storage: S3Storage, capacity: UploadCapacity,
|
||||
filename: Annotated[str, Query(min_length=1, max_length=255)],
|
||||
) -> Attachment:
|
||||
return await attachments.receive_attachment(
|
||||
session, storage, user, chat_id, capacity=capacity, filename=filename,
|
||||
content_type=request.headers.get('content-type', '').lower(),
|
||||
declared_length=request.headers.get('content-length'), chunks=request.stream(),
|
||||
)
|
||||
|
||||
|
||||
@router.get('/attachments/{attachment_id}')
|
||||
async def metadata(attachment_id: UUID, user: CurrentUser, session: DbSession) -> Attachment:
|
||||
return await attachments.get_attachment(session, user, attachment_id)
|
||||
|
||||
|
||||
@router.get('/attachments/{attachment_id}/content')
|
||||
async def content(
|
||||
attachment_id: UUID, user: CurrentUser, session: DbSession, storage: S3Storage,
|
||||
variant: Annotated[str, Query()] = 'original',
|
||||
) -> StreamingResponse:
|
||||
record, stream = await attachments.download_attachment(
|
||||
session, storage, user, attachment_id, variant=variant,
|
||||
)
|
||||
return StreamingResponse(
|
||||
stream, media_type=record.content_type,
|
||||
headers={
|
||||
'Content-Length': str(record.size_bytes),
|
||||
'Content-Disposition': "attachment; filename*=UTF-8''" + quote(record.filename, safe=''),
|
||||
'X-Content-Type-Options': 'nosniff', 'Cache-Control': 'private, no-store',
|
||||
},
|
||||
background=BackgroundTask(stream.aclose),
|
||||
)
|
||||
@@ -0,0 +1,32 @@
|
||||
from fastapi import APIRouter, Response
|
||||
|
||||
from app.domain.auth import create_session, revoke_session
|
||||
from app.endpoints.dependencies import (
|
||||
AppSettings,
|
||||
BasicCredentials,
|
||||
BearerToken,
|
||||
DbSession,
|
||||
RedisClient,
|
||||
)
|
||||
from app.schemas.session import AuthSession
|
||||
|
||||
router = APIRouter(prefix="/api/v1/auth", tags=["auth"])
|
||||
|
||||
|
||||
@router.post("/sessions", status_code=201)
|
||||
async def login(
|
||||
credentials: BasicCredentials,
|
||||
session: DbSession,
|
||||
redis: RedisClient,
|
||||
settings: AppSettings,
|
||||
) -> AuthSession:
|
||||
username, password = credentials
|
||||
return await create_session(
|
||||
session, redis, username, password, settings.session_ttl_seconds
|
||||
)
|
||||
|
||||
|
||||
@router.delete("/sessions/current", status_code=204)
|
||||
async def logout(token: BearerToken, redis: RedisClient) -> Response:
|
||||
await revoke_session(redis, token)
|
||||
return Response(status_code=204)
|
||||
@@ -0,0 +1,32 @@
|
||||
from typing import Annotated
|
||||
from uuid import UUID
|
||||
|
||||
from fastapi import APIRouter, Query
|
||||
|
||||
from app.domain.chats import create_chat, get_chat, list_chats
|
||||
from app.endpoints.dependencies import CurrentUser, DbSession
|
||||
from app.schemas.chat import Chat, ChatPage, CreateChat
|
||||
|
||||
router = APIRouter(prefix="/api/v1/chats", tags=["chats"])
|
||||
|
||||
|
||||
@router.post("", status_code=201)
|
||||
async def create_new_chat(
|
||||
new_chat: CreateChat, creator: CurrentUser, session: DbSession
|
||||
) -> Chat:
|
||||
return await create_chat(session, creator, new_chat)
|
||||
|
||||
|
||||
@router.get("")
|
||||
async def list_user_chats(
|
||||
user: CurrentUser,
|
||||
session: DbSession,
|
||||
limit: Annotated[int, Query(ge=1, le=100)] = 50,
|
||||
cursor: Annotated[str | None, Query(min_length=1)] = None,
|
||||
) -> ChatPage:
|
||||
return await list_chats(session, user, cursor, limit)
|
||||
|
||||
|
||||
@router.get("/{chat_id}")
|
||||
async def get_chat_by_id(chat_id: UUID, user: CurrentUser, session: DbSession) -> Chat:
|
||||
return await get_chat(session, user, chat_id)
|
||||
@@ -0,0 +1,112 @@
|
||||
import base64
|
||||
import binascii
|
||||
from collections.abc import AsyncIterator
|
||||
from typing import Annotated
|
||||
|
||||
from fastapi import Depends, Request, Security
|
||||
from fastapi.openapi.models import HTTPBase, HTTPBearer
|
||||
from fastapi.security.base import SecurityBase
|
||||
from redis.asyncio import Redis
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.config import Settings
|
||||
from app.core.request_capacity import RequestCapacity
|
||||
from app.domain.auth import authenticate_token
|
||||
from app.errors.exceptions import unauthorized_basic, unauthorized_bearer
|
||||
from app.schemas.user import User
|
||||
from app.storage.s3 import MinioStorage
|
||||
|
||||
|
||||
async def get_settings(request: Request) -> Settings:
|
||||
settings: Settings = request.app.state.settings
|
||||
return settings
|
||||
|
||||
|
||||
async def get_db(request: Request) -> AsyncIterator[AsyncSession]:
|
||||
"""Одна AsyncSession на HTTP-запрос; незакоммиченная транзакция откатывается."""
|
||||
session_factory = request.app.state.session_factory
|
||||
async with session_factory() as session:
|
||||
yield session
|
||||
|
||||
|
||||
async def get_redis(request: Request) -> Redis:
|
||||
redis: Redis = request.app.state.redis
|
||||
return redis
|
||||
|
||||
|
||||
def get_s3(request: Request) -> MinioStorage | None:
|
||||
return request.app.state.s3
|
||||
|
||||
|
||||
def get_upload_capacity(request: Request) -> RequestCapacity:
|
||||
return request.app.state.upload_capacity
|
||||
|
||||
|
||||
class AuthorizationHeader(SecurityBase):
|
||||
"""Отдаёт сырой заголовок Authorization и описывает схему для OpenAPI."""
|
||||
|
||||
def __init__(self, model: HTTPBase, scheme_name: str) -> None:
|
||||
self.model = model
|
||||
self.scheme_name = scheme_name
|
||||
|
||||
async def __call__(self, request: Request) -> str | None:
|
||||
return request.headers.get("Authorization")
|
||||
|
||||
|
||||
basic_auth = AuthorizationHeader(HTTPBase(scheme="basic"), "BasicAuth")
|
||||
bearer_auth = AuthorizationHeader(HTTPBearer(), "BearerAuth")
|
||||
|
||||
|
||||
def _split_authorization(authorization: str | None) -> tuple[str, str] | None:
|
||||
if authorization is None:
|
||||
return None
|
||||
scheme, _, value = authorization.partition(" ")
|
||||
if not value.strip():
|
||||
return None
|
||||
return scheme.lower(), value.strip()
|
||||
|
||||
|
||||
async def get_bearer_token(
|
||||
authorization: Annotated[str | None, Security(bearer_auth)],
|
||||
) -> str:
|
||||
parts = _split_authorization(authorization)
|
||||
if parts is None or parts[0] != "bearer":
|
||||
raise unauthorized_bearer()
|
||||
return parts[1]
|
||||
|
||||
|
||||
async def get_basic_credentials(
|
||||
authorization: Annotated[str | None, Security(basic_auth)],
|
||||
) -> tuple[str, str]:
|
||||
"""(username, password) из `Authorization: Basic`; пароль может содержать ':'."""
|
||||
parts = _split_authorization(authorization)
|
||||
if parts is None or parts[0] != "basic":
|
||||
raise unauthorized_basic()
|
||||
|
||||
try:
|
||||
decoded = base64.b64decode(parts[1], validate=True).decode("utf-8")
|
||||
except (binascii.Error, UnicodeDecodeError, ValueError):
|
||||
raise unauthorized_basic() from None
|
||||
|
||||
username, separator, password = decoded.partition(":")
|
||||
if not separator or not username:
|
||||
raise unauthorized_basic()
|
||||
return username, password
|
||||
|
||||
|
||||
DbSession = Annotated[AsyncSession, Depends(get_db)]
|
||||
RedisClient = Annotated[Redis, Depends(get_redis)]
|
||||
AppSettings = Annotated[Settings, Depends(get_settings)]
|
||||
S3Storage = Annotated[MinioStorage | None, Depends(get_s3)]
|
||||
UploadCapacity = Annotated[RequestCapacity, Depends(get_upload_capacity)]
|
||||
BearerToken = Annotated[str, Depends(get_bearer_token)]
|
||||
BasicCredentials = Annotated[tuple[str, str], Depends(get_basic_credentials)]
|
||||
|
||||
|
||||
async def get_current_user(
|
||||
token: BearerToken, session: DbSession, redis: RedisClient
|
||||
) -> User:
|
||||
return await authenticate_token(session, redis, token)
|
||||
|
||||
|
||||
CurrentUser = Annotated[User, Depends(get_current_user)]
|
||||
@@ -0,0 +1,20 @@
|
||||
from fastapi import APIRouter, Request
|
||||
|
||||
from app.domain import health
|
||||
from app.schemas.base import Health
|
||||
|
||||
router = APIRouter(prefix='/health', tags=['health'])
|
||||
|
||||
|
||||
@router.get('/live')
|
||||
async def liveness() -> Health:
|
||||
return health.liveness()
|
||||
|
||||
|
||||
@router.get('/ready')
|
||||
async def readiness(request: Request) -> Health:
|
||||
state = request.app.state
|
||||
return await health.readiness(
|
||||
state.engine, state.redis, state.s3, state.lifecycle,
|
||||
state.settings.readiness_timeout_seconds,
|
||||
)
|
||||
@@ -0,0 +1,38 @@
|
||||
from typing import Annotated
|
||||
from uuid import UUID
|
||||
|
||||
from fastapi import APIRouter, Header, Query
|
||||
|
||||
from app.domain.idempotency import send_message_idempotent, validate_idempotency_key
|
||||
from app.domain.messages import list_messages
|
||||
from app.endpoints.dependencies import AppSettings, CurrentUser, DbSession
|
||||
from app.schemas.message import CreateMessage, Message, MessagePage
|
||||
|
||||
router = APIRouter(prefix="/api/v1/chats", tags=["messages"])
|
||||
|
||||
|
||||
@router.post("/{chat_id}/messages", status_code=201)
|
||||
async def send_new_message(
|
||||
chat_id: UUID,
|
||||
new_message: CreateMessage,
|
||||
sender: CurrentUser,
|
||||
session: DbSession,
|
||||
settings: AppSettings,
|
||||
idempotency_key: Annotated[str | None, Header(alias="Idempotency-Key")] = None,
|
||||
) -> Message:
|
||||
return await send_message_idempotent(
|
||||
session, sender, chat_id, new_message,
|
||||
validate_idempotency_key(idempotency_key),
|
||||
settings.max_messages, settings.idempotency_ttl_seconds,
|
||||
)
|
||||
|
||||
|
||||
@router.get("/{chat_id}/messages")
|
||||
async def get_history_messages(
|
||||
chat_id: UUID,
|
||||
user: CurrentUser,
|
||||
session: DbSession,
|
||||
limit: Annotated[int, Query(ge=1, le=100)] = 50,
|
||||
cursor: Annotated[str | None, Query(min_length=1)] = None,
|
||||
) -> MessagePage:
|
||||
return await list_messages(session, user, chat_id, cursor, limit)
|
||||
@@ -0,0 +1,17 @@
|
||||
from fastapi import APIRouter
|
||||
|
||||
from app.domain.users import register_user
|
||||
from app.endpoints.dependencies import CurrentUser, DbSession
|
||||
from app.schemas.user import CreateUser, User
|
||||
|
||||
router = APIRouter(prefix="/api/v1/users", tags=["users"])
|
||||
|
||||
|
||||
@router.post("", status_code=201)
|
||||
async def create_user(new_user: CreateUser, session: DbSession) -> User:
|
||||
return await register_user(session, new_user)
|
||||
|
||||
|
||||
@router.get("/me")
|
||||
async def get_me(user: CurrentUser) -> User:
|
||||
return user
|
||||
Reference in New Issue
Block a user