forked from mtusi2026/mtusi2026lab4
feat: перенос структуры приложения из третьей лабы
This commit is contained in:
@@ -0,0 +1,63 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
from fastapi import APIRouter, Depends, Header, Request, Response, status
|
||||
|
||||
from app.dependencies import get_current_token
|
||||
from app.errors import InvalidRequestError, UnauthorizedError
|
||||
from app.schemas import SessionResponse
|
||||
from app.storage import storage
|
||||
|
||||
router = APIRouter(prefix="/api/v1/auth/sessions", tags=["auth"])
|
||||
|
||||
|
||||
@router.post("", response_model=SessionResponse, status_code=status.HTTP_201_CREATED)
|
||||
async def create_session(
|
||||
request: Request,
|
||||
authorization: str | None = Header(default=None, alias="Authorization"),
|
||||
) -> SessionResponse:
|
||||
"""Аутентификация пользователя через Basic Auth и создание новой сессии."""
|
||||
body = await request.body()
|
||||
if body and body.strip():
|
||||
raise InvalidRequestError("Тело запроса для создания сессии должно быть пустым")
|
||||
|
||||
if not authorization or not authorization.strip():
|
||||
raise UnauthorizedError("Отсутствует заголовок Authorization")
|
||||
|
||||
parts = authorization.strip().split(maxsplit=1)
|
||||
if len(parts) != 2 or parts[0].lower() != "basic":
|
||||
raise UnauthorizedError("Неверная схема авторизации (ожидается Basic)")
|
||||
|
||||
try:
|
||||
raw_bytes = base64.b64decode(parts[1].strip())
|
||||
raw_str = raw_bytes.decode("utf-8")
|
||||
if ":" not in raw_str:
|
||||
raise UnauthorizedError("Некорректный формат Basic credentials")
|
||||
username, password = raw_str.split(":", 1)
|
||||
except Exception:
|
||||
raise UnauthorizedError("Некорректный заголовок Basic авторизации")
|
||||
|
||||
user = await storage.authenticate_user(username, password)
|
||||
if not user:
|
||||
raise UnauthorizedError("Неверное имя пользователя или пароль")
|
||||
|
||||
session = await storage.create_session(user)
|
||||
return session
|
||||
|
||||
|
||||
@router.delete("/current", status_code=status.HTTP_204_NO_CONTENT)
|
||||
async def delete_current_session(
|
||||
request: Request,
|
||||
token: str = Depends(get_current_token),
|
||||
) -> Response:
|
||||
"""Отзыв текущей сессии."""
|
||||
body = await request.body()
|
||||
if body and body.strip():
|
||||
raise InvalidRequestError("Тело запроса для отзыва сессии должно быть пустым")
|
||||
|
||||
user = await storage.get_session_user(token)
|
||||
if not user:
|
||||
raise UnauthorizedError("Недействительная или уже отозванная сессия")
|
||||
|
||||
await storage.delete_session(token)
|
||||
return Response(status_code=status.HTTP_204_NO_CONTENT)
|
||||
@@ -0,0 +1,64 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from uuid import UUID
|
||||
|
||||
from fastapi import APIRouter, Depends, Query, status
|
||||
|
||||
from app.dependencies import get_current_user
|
||||
from app.schemas import (
|
||||
ChatPageResponse,
|
||||
ChatResponse,
|
||||
CreateChatRequest,
|
||||
UserResponse,
|
||||
)
|
||||
from app.storage import InvalidRequestError, storage
|
||||
|
||||
router = APIRouter(prefix="/api/v1/chats", tags=["chats"])
|
||||
|
||||
|
||||
def validate_uuid(value: str, field_name: str = "id") -> str:
|
||||
try:
|
||||
UUID(value)
|
||||
return value
|
||||
except ValueError as exc:
|
||||
raise InvalidRequestError(f"Поле '{field_name}' не является валидным UUID") from exc
|
||||
|
||||
|
||||
@router.post("", response_model=ChatResponse, status_code=status.HTTP_201_CREATED)
|
||||
async def create_chat(
|
||||
body: CreateChatRequest,
|
||||
current_user: UserResponse = Depends(get_current_user),
|
||||
) -> ChatResponse:
|
||||
"""Создание нового чата."""
|
||||
chat = await storage.create_chat(
|
||||
caller_id=current_user.id,
|
||||
title=body.title,
|
||||
member_ids=body.member_ids,
|
||||
)
|
||||
return chat
|
||||
|
||||
|
||||
@router.get("", response_model=ChatPageResponse, status_code=status.HTTP_200_OK)
|
||||
async def list_chats(
|
||||
limit: int = Query(default=50, ge=1, le=100),
|
||||
cursor: str | None = Query(default=None),
|
||||
current_user: UserResponse = Depends(get_current_user),
|
||||
) -> ChatPageResponse:
|
||||
"""Список чатов, в которых состоит текущий пользователь."""
|
||||
items, next_cursor = await storage.list_chats(
|
||||
caller_id=current_user.id,
|
||||
limit=limit,
|
||||
cursor=cursor,
|
||||
)
|
||||
return ChatPageResponse(items=items, next_cursor=next_cursor)
|
||||
|
||||
|
||||
@router.get("/{chat_id}", response_model=ChatResponse, status_code=status.HTTP_200_OK)
|
||||
async def get_chat(
|
||||
chat_id: str,
|
||||
current_user: UserResponse = Depends(get_current_user),
|
||||
) -> ChatResponse:
|
||||
"""Получение информации о чате по ID."""
|
||||
valid_id = validate_uuid(chat_id, "chat_id")
|
||||
chat = await storage.get_chat(caller_id=current_user.id, chat_id=valid_id)
|
||||
return chat
|
||||
@@ -0,0 +1,31 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import APIRouter, status
|
||||
from starlette.exceptions import HTTPException as StarletteHTTPException
|
||||
|
||||
from app.schemas import HealthResponse
|
||||
from app.storage import storage
|
||||
|
||||
router = APIRouter(tags=["health"])
|
||||
|
||||
|
||||
@router.get(
|
||||
"/health/live", response_model=HealthResponse, status_code=status.HTTP_200_OK
|
||||
)
|
||||
async def health_live() -> HealthResponse:
|
||||
"""Проверка жизни процесса (Liveness)."""
|
||||
return HealthResponse(status="ok")
|
||||
|
||||
|
||||
@router.get(
|
||||
"/health/ready", response_model=HealthResponse, status_code=status.HTTP_200_OK
|
||||
)
|
||||
async def health_ready() -> HealthResponse:
|
||||
"""Проверка готовности сервиса и его зависимостей (Readiness)."""
|
||||
is_ready = await storage.check_health()
|
||||
if not is_ready:
|
||||
raise StarletteHTTPException(
|
||||
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
|
||||
detail="Сервис или его хранилища недоступны",
|
||||
)
|
||||
return HealthResponse(status="ok")
|
||||
@@ -0,0 +1,73 @@
|
||||
import re
|
||||
from uuid import UUID
|
||||
|
||||
from fastapi import APIRouter, Depends, Header, Query, status
|
||||
|
||||
from app.dependencies import get_current_user
|
||||
from app.schemas import (
|
||||
CreateMessageRequest,
|
||||
MessagePageResponse,
|
||||
MessageResponse,
|
||||
UserResponse,
|
||||
)
|
||||
from app.storage import InvalidRequestError, storage
|
||||
|
||||
router = APIRouter(prefix="/api/v1/chats", tags=["messages"])
|
||||
|
||||
IDEMPOTENCY_KEY_REGEX = re.compile(r"^[A-Za-z0-9._:-]{1,128}$")
|
||||
|
||||
|
||||
def validate_uuid(value: str, field_name: str = "id") -> str:
|
||||
try:
|
||||
UUID(value)
|
||||
return value
|
||||
except ValueError as exc:
|
||||
raise InvalidRequestError(f"Поле '{field_name}' не является валидным UUID") from exc
|
||||
|
||||
|
||||
@router.post(
|
||||
"/{chat_id}/messages",
|
||||
response_model=MessageResponse,
|
||||
status_code=status.HTTP_201_CREATED,
|
||||
)
|
||||
async def create_message(
|
||||
chat_id: str,
|
||||
body: CreateMessageRequest,
|
||||
idempotency_key: str | None = Header(default=None, alias="Idempotency-Key"),
|
||||
current_user: UserResponse = Depends(get_current_user),
|
||||
) -> MessageResponse:
|
||||
"""Отправка сообщения в чат."""
|
||||
if not idempotency_key or not IDEMPOTENCY_KEY_REGEX.match(idempotency_key):
|
||||
raise InvalidRequestError(
|
||||
"Заголовок 'Idempotency-Key' обязателен и должен соответствовать шаблону ^[A-Za-z0-9._:-]{1,128}$"
|
||||
)
|
||||
valid_id = validate_uuid(chat_id, "chat_id")
|
||||
msg = await storage.send_message(
|
||||
caller_id=current_user.id,
|
||||
chat_id=valid_id,
|
||||
text=body.text,
|
||||
idempotency_key=idempotency_key,
|
||||
)
|
||||
return msg
|
||||
|
||||
|
||||
@router.get(
|
||||
"/{chat_id}/messages",
|
||||
response_model=MessagePageResponse,
|
||||
status_code=status.HTTP_200_OK,
|
||||
)
|
||||
async def list_messages(
|
||||
chat_id: str,
|
||||
limit: int = Query(default=50, ge=1, le=100),
|
||||
cursor: str | None = Query(default=None),
|
||||
current_user: UserResponse = Depends(get_current_user),
|
||||
) -> MessagePageResponse:
|
||||
"""Получение истории сообщений чата с keyset-пагинацией."""
|
||||
valid_id = validate_uuid(chat_id, "chat_id")
|
||||
items, next_cursor = await storage.list_messages(
|
||||
caller_id=current_user.id,
|
||||
chat_id=valid_id,
|
||||
limit=limit,
|
||||
cursor=cursor,
|
||||
)
|
||||
return MessagePageResponse(items=items, next_cursor=next_cursor)
|
||||
@@ -0,0 +1,28 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import APIRouter, Depends, status
|
||||
|
||||
from app.dependencies import get_current_user
|
||||
from app.schemas import CreateUserRequest, UserResponse
|
||||
from app.storage import storage
|
||||
|
||||
router = APIRouter(prefix="/api/v1/users", tags=["users"])
|
||||
|
||||
|
||||
@router.post("", response_model=UserResponse, status_code=status.HTTP_201_CREATED)
|
||||
async def create_user(body: CreateUserRequest) -> UserResponse:
|
||||
"""Регистрация нового пользователя."""
|
||||
user = await storage.create_user(
|
||||
username=body.username,
|
||||
display_name=body.display_name,
|
||||
password=body.password,
|
||||
)
|
||||
return user
|
||||
|
||||
|
||||
@router.get("/me", response_model=UserResponse, status_code=status.HTTP_200_OK)
|
||||
async def get_me(
|
||||
current_user: UserResponse = Depends(get_current_user),
|
||||
) -> UserResponse:
|
||||
"""Получение профиля текущего пользователя."""
|
||||
return current_user
|
||||
Reference in New Issue
Block a user