forked from mtusi2026/mtusi2026lab2
feat: ЛР2 - PostgreSQL, Redis сессии и keyset-пагинация
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)
|
||||
@@ -1,8 +1,10 @@
|
||||
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"])
|
||||
|
||||
@@ -11,6 +13,7 @@ router = APIRouter(tags=["health"])
|
||||
"/health/live", response_model=HealthResponse, status_code=status.HTTP_200_OK
|
||||
)
|
||||
async def health_live() -> HealthResponse:
|
||||
"""Проверка жизни процесса (Liveness)."""
|
||||
return HealthResponse(status="ok")
|
||||
|
||||
|
||||
@@ -18,4 +21,11 @@ async def health_live() -> HealthResponse:
|
||||
"/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")
|
||||
|
||||
@@ -36,7 +36,7 @@ async def create_message(
|
||||
) -> MessageResponse:
|
||||
"""Отправка сообщения в чат."""
|
||||
valid_id = validate_uuid(chat_id, "chat_id")
|
||||
msg = await storage.create_message(
|
||||
msg = await storage.send_message(
|
||||
caller_id=current_user.id,
|
||||
chat_id=valid_id,
|
||||
text=body.text,
|
||||
|
||||
+3
-1
@@ -13,7 +13,9 @@ router = APIRouter(prefix="/api/v1/users", tags=["users"])
|
||||
async def create_user(body: CreateUserRequest) -> UserResponse:
|
||||
"""Регистрация нового пользователя."""
|
||||
user = await storage.create_user(
|
||||
username=body.username, display_name=body.display_name
|
||||
username=body.username,
|
||||
display_name=body.display_name,
|
||||
password=body.password,
|
||||
)
|
||||
return user
|
||||
|
||||
|
||||
Reference in New Issue
Block a user