create skeleton for lab 3
This commit is contained in:
@@ -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,100 @@
|
||||
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.domain.auth import authenticate_token
|
||||
from app.errors.exceptions import unauthorized_basic, unauthorized_bearer
|
||||
from app.schemas.user import User
|
||||
|
||||
|
||||
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
|
||||
|
||||
|
||||
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)]
|
||||
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,26 @@
|
||||
from fastapi import APIRouter, Request
|
||||
|
||||
from app.core.database import check_database
|
||||
from app.core.redis import check_redis
|
||||
from app.errors.exceptions import unavailable
|
||||
from app.schemas.base import Health
|
||||
|
||||
router = APIRouter(prefix="/health", tags=["health"])
|
||||
|
||||
|
||||
@router.get("/live")
|
||||
async def liveness() -> Health:
|
||||
return Health(status="ok")
|
||||
|
||||
|
||||
@router.get("/ready")
|
||||
async def readiness(request: Request) -> Health:
|
||||
# TODO(4.1): если реплика получила SIGTERM (lifecycle.draining) — сразу 503,
|
||||
# чтобы LB исключил её до закрытия сокета.
|
||||
# TODO(4.1): проверки зависимостей должны укладываться в timeout healthcheck;
|
||||
# зафиксируйте в REPORT.md, какие зависимости критичны.
|
||||
if not await check_database(request.app.state.engine):
|
||||
raise unavailable()
|
||||
if not await check_redis(request.app.state.redis):
|
||||
raise unavailable()
|
||||
return Health(status="ok")
|
||||
@@ -0,0 +1,39 @@
|
||||
from typing import Annotated
|
||||
from uuid import UUID
|
||||
|
||||
from fastapi import APIRouter, Query
|
||||
|
||||
from app.domain.messages import list_messages, send_message
|
||||
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,
|
||||
# TODO(3.4): принять заголовок Idempotency-Key:
|
||||
# idempotency_key: Annotated[str | None, Header(alias="Idempotency-Key")] = None
|
||||
# и вызывать app.domain.idempotency.send_message_idempotent(...) вместо send_message.
|
||||
# Нет/неверный ключ -> 400 (validate_idempotency_key). Валидацию делайте сами,
|
||||
# а не через pattern= у Header, чтобы текст ошибки был в общем формате.
|
||||
) -> Message:
|
||||
return await send_message(
|
||||
session, sender, chat_id, new_message, settings.max_messages
|
||||
)
|
||||
|
||||
|
||||
@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