forked from mtusi2026/mtusi2026lab4
Основа из lab3
This commit is contained in:
@@ -0,0 +1 @@
|
||||
"""MTUSI Messenger — лабораторная 2: PostgreSQL, сессии и Redis-кэш."""
|
||||
@@ -0,0 +1,15 @@
|
||||
import os
|
||||
import uuid
|
||||
|
||||
|
||||
class Settings:
|
||||
def __init__(self) -> None:
|
||||
self.database_url = os.environ["DATABASE_URL"]
|
||||
self.session_ttl_seconds = int(os.environ.get("SESSION_TTL_SECONDS", "3600"))
|
||||
self.idempotency_ttl_seconds = int(os.environ.get("IDEMPOTENCY_TTL_SECONDS", "86400"))
|
||||
self.instance_id = os.environ.get("INSTANCE_ID") or uuid.uuid4().hex
|
||||
self.host = os.environ.get("APP_HOST", "0.0.0.0")
|
||||
self.port = int(os.environ.get("APP_PORT", "8080"))
|
||||
|
||||
|
||||
settings = Settings()
|
||||
@@ -0,0 +1,33 @@
|
||||
from contextlib import contextmanager
|
||||
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import DeclarativeBase, Session, sessionmaker
|
||||
|
||||
from .config import settings
|
||||
|
||||
|
||||
class Base(DeclarativeBase):
|
||||
pass
|
||||
|
||||
|
||||
engine = create_engine(
|
||||
settings.database_url,
|
||||
pool_pre_ping=True,
|
||||
pool_size=10,
|
||||
max_overflow=10,
|
||||
future=True,
|
||||
)
|
||||
SessionLocal = sessionmaker(bind=engine, autoflush=False, expire_on_commit=False, class_=Session)
|
||||
|
||||
|
||||
@contextmanager
|
||||
def session_scope():
|
||||
s = SessionLocal()
|
||||
try:
|
||||
yield s
|
||||
s.commit()
|
||||
except Exception:
|
||||
s.rollback()
|
||||
raise
|
||||
finally:
|
||||
s.close()
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
import uuid
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from fastapi import Depends, Request
|
||||
from fastapi.security import HTTPAuthorizationCredentials, HTTPBasic, HTTPBearer
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from .db import SessionLocal
|
||||
from .errors import ApiError
|
||||
from .models import SessionRow, User
|
||||
from .security import token_hash
|
||||
|
||||
# Схемы безопасности для Swagger UI и /openapi.json.
|
||||
# auto_error=False — 401 формирует current_user в едином формате ошибки.
|
||||
bearer_scheme = HTTPBearer(auto_error=False, scheme_name="bearerAuth", description="Bearer <token>")
|
||||
basic_scheme = HTTPBasic(auto_error=False, scheme_name="basicAuth")
|
||||
|
||||
|
||||
def get_db():
|
||||
s = SessionLocal()
|
||||
try:
|
||||
yield s
|
||||
finally:
|
||||
s.close()
|
||||
|
||||
|
||||
def current_user(
|
||||
request: Request,
|
||||
credentials: HTTPAuthorizationCredentials | None = Depends(bearer_scheme),
|
||||
db: Session = Depends(get_db),
|
||||
) -> User:
|
||||
# Swagger UI для bearerAuth подставляет токен без префикса "Bearer ",
|
||||
# но HTTPBearer уже нормализует заголовок. Fallback на сырой заголовок
|
||||
# нужен для клиентов, присылающих токен без схемы.
|
||||
if credentials is not None and credentials.scheme.lower() == "bearer":
|
||||
token = credentials.credentials.strip()
|
||||
else:
|
||||
auth = request.headers.get("authorization", "").strip()
|
||||
if not auth:
|
||||
raise ApiError(401, "unauthorized", "Требуется Bearer-токен")
|
||||
token = auth
|
||||
while token.lower().startswith("bearer "):
|
||||
token = token[7:].strip()
|
||||
if not token:
|
||||
raise ApiError(401, "unauthorized", "Пустой токен")
|
||||
row = db.get(SessionRow, token_hash(token))
|
||||
if row is None:
|
||||
raise ApiError(401, "unauthorized", "Неизвестный токен")
|
||||
if row.expires_at <= datetime.now(timezone.utc):
|
||||
raise ApiError(401, "unauthorized", "Сессия истекла")
|
||||
user = db.get(User, row.user_id)
|
||||
if user is None:
|
||||
raise ApiError(401, "unauthorized", "Пользователь не найден")
|
||||
request.state.user = user
|
||||
request.state.token_hash = row.token_hash
|
||||
return user
|
||||
|
||||
|
||||
def parse_uuid(value: str) -> uuid.UUID:
|
||||
try:
|
||||
return uuid.UUID(value)
|
||||
except (ValueError, TypeError):
|
||||
raise ApiError(400, "invalid_request", "Некорректный UUID")
|
||||
@@ -0,0 +1,24 @@
|
||||
from fastapi import Request
|
||||
from fastapi.responses import JSONResponse
|
||||
|
||||
|
||||
class ApiError(Exception):
|
||||
def __init__(self, status: int, code: str, message: str):
|
||||
self.status = status
|
||||
self.code = code
|
||||
self.message = message
|
||||
|
||||
|
||||
def error_response(request: Request, status: int, code: str, message: str) -> JSONResponse:
|
||||
rid = getattr(request.state, "request_id", "")
|
||||
headers = {}
|
||||
if status == 401:
|
||||
if request.url.path == "/api/v1/auth/sessions":
|
||||
headers["WWW-Authenticate"] = 'Basic realm="messenger", charset="UTF-8"'
|
||||
else:
|
||||
headers["WWW-Authenticate"] = 'Bearer realm="messenger"'
|
||||
return JSONResponse(
|
||||
status_code=status,
|
||||
content={"error": {"code": code, "message": message, "request_id": rid}},
|
||||
headers=headers,
|
||||
)
|
||||
+242
@@ -0,0 +1,242 @@
|
||||
"""HTTP-обработчики FastAPI для lab2: Basic/Bearer, PostgreSQL, Redis-кэш сессий."""
|
||||
import base64
|
||||
import binascii
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter, Body, Header, Query, Request
|
||||
from fastapi.responses import JSONResponse, Response
|
||||
|
||||
from .errors import ApiError
|
||||
from .security import hash_password, verify_password
|
||||
from .sessions import SessionStore
|
||||
from .store import Store
|
||||
from .validation import (
|
||||
encode_cursor,
|
||||
parse_cursor,
|
||||
parse_limit,
|
||||
validate_chat_id,
|
||||
validate_create_chat,
|
||||
validate_create_message,
|
||||
validate_create_user,
|
||||
)
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
logger = logging.getLogger("messenger.handlers")
|
||||
|
||||
BASIC_CHALLENGE = 'Basic realm="messenger", charset="UTF-8"'
|
||||
BEARER_CHALLENGE = 'Bearer realm="messenger"'
|
||||
|
||||
|
||||
def get_store(request: Request) -> Store:
|
||||
return request.app.state.store
|
||||
|
||||
|
||||
def get_sessions(request: Request) -> SessionStore:
|
||||
return request.app.state.sessions
|
||||
|
||||
|
||||
def _unauthorized(message: str, challenge: str) -> ApiError:
|
||||
err = ApiError(401, "unauthorized", message)
|
||||
err.challenge = challenge # type: ignore[attr-defined]
|
||||
return err
|
||||
|
||||
|
||||
def current_user_id(request: Request, authorization: str | None) -> str:
|
||||
"""lab2: только Bearer. X-User-Id игнорируется."""
|
||||
if not authorization or not authorization.lower().startswith("bearer "):
|
||||
raise _unauthorized("Требуется Bearer-токен", BEARER_CHALLENGE)
|
||||
token = authorization[7:].strip()
|
||||
if not token:
|
||||
raise _unauthorized("Пустой Bearer-токен", BEARER_CHALLENGE)
|
||||
user_id = get_sessions(request).resolve(token)
|
||||
if user_id is None:
|
||||
raise _unauthorized("Недействительная сессия", BEARER_CHALLENGE)
|
||||
return user_id
|
||||
|
||||
|
||||
def _parse_basic(authorization: str | None) -> tuple[str, str]:
|
||||
if not authorization or not authorization.lower().startswith("basic "):
|
||||
raise _unauthorized("Требуется Basic-аутентификация", BASIC_CHALLENGE)
|
||||
try:
|
||||
decoded = base64.b64decode(authorization[6:].strip(), validate=True).decode("utf-8")
|
||||
except (binascii.Error, UnicodeDecodeError):
|
||||
raise _unauthorized("Некорректный Basic", BASIC_CHALLENGE)
|
||||
if ":" not in decoded:
|
||||
raise _unauthorized("Некорректный Basic", BASIC_CHALLENGE)
|
||||
username, password = decoded.split(":", 1)
|
||||
return username, password
|
||||
|
||||
|
||||
@router.get("/health/live")
|
||||
def health_live() -> dict[str, str]:
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
@router.get("/health/ready")
|
||||
def health_ready(request: Request) -> JSONResponse:
|
||||
"""Ready, если доступна БД (обязательный синхронный путь). Redis — кэш."""
|
||||
try:
|
||||
with get_store(request).pool.connection() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute("SELECT 1")
|
||||
cur.fetchone()
|
||||
except Exception as exc: # noqa: BLE001
|
||||
logger.warning("readiness failed: %s", type(exc).__name__)
|
||||
raise ApiError(503, "unavailable", "Зависимость недоступна")
|
||||
return JSONResponse({"status": "ok"})
|
||||
|
||||
|
||||
@router.post("/api/v1/users", status_code=201)
|
||||
def register_user(request: Request, body: Any = Body(...)) -> JSONResponse:
|
||||
username, display_name, password = validate_create_user(body)
|
||||
store = get_store(request)
|
||||
user = store.create_user(username, display_name, hash_password(password))
|
||||
if user is None:
|
||||
raise ApiError(409, "conflict", "username уже занят")
|
||||
return JSONResponse(user, status_code=201)
|
||||
|
||||
|
||||
@router.post("/api/v1/auth/sessions", status_code=201)
|
||||
def create_session(
|
||||
request: Request,
|
||||
authorization: str | None = Header(default=None),
|
||||
) -> JSONResponse:
|
||||
username, password = _parse_basic(authorization)
|
||||
store = get_store(request)
|
||||
found = store.get_user_by_username(username)
|
||||
if found is None:
|
||||
# Одинаковый 401 для неверного username и пароля.
|
||||
raise _unauthorized("Неверные учётные данные", BASIC_CHALLENGE)
|
||||
user, password_hash = found
|
||||
if not verify_password(password_hash, password):
|
||||
raise _unauthorized("Неверные учётные данные", BASIC_CHALLENGE)
|
||||
session = get_sessions(request).create(user["id"])
|
||||
return JSONResponse(
|
||||
{
|
||||
"token": session["token"],
|
||||
"token_type": "Bearer",
|
||||
"expires_at": session["expires_at"],
|
||||
"user": user,
|
||||
},
|
||||
status_code=201,
|
||||
)
|
||||
|
||||
|
||||
@router.delete("/api/v1/auth/sessions/current", status_code=204)
|
||||
def revoke_session(
|
||||
request: Request,
|
||||
authorization: str | None = Header(default=None),
|
||||
) -> JSONResponse:
|
||||
if not authorization or not authorization.lower().startswith("bearer "):
|
||||
raise _unauthorized("Требуется Bearer-токен", BEARER_CHALLENGE)
|
||||
token = authorization[7:].strip()
|
||||
if not token or get_sessions(request).resolve(token) is None:
|
||||
raise _unauthorized("Недействительная сессия", BEARER_CHALLENGE)
|
||||
get_sessions(request).revoke(token)
|
||||
return Response(status_code=204)
|
||||
|
||||
|
||||
@router.get("/api/v1/users/me")
|
||||
def current_user(
|
||||
request: Request, authorization: str | None = Header(default=None)
|
||||
) -> dict[str, Any]:
|
||||
user_id = current_user_id(request, authorization)
|
||||
user = get_store(request).get_user(user_id)
|
||||
if user is None:
|
||||
raise _unauthorized("Недействительная сессия", BEARER_CHALLENGE)
|
||||
return user
|
||||
|
||||
|
||||
@router.post("/api/v1/chats", status_code=201)
|
||||
def create_chat(
|
||||
request: Request,
|
||||
body: Any = Body(...),
|
||||
authorization: str | None = Header(default=None),
|
||||
) -> JSONResponse:
|
||||
caller = current_user_id(request, authorization)
|
||||
title, member_ids = validate_create_chat(body, caller)
|
||||
store = get_store(request)
|
||||
for mid in member_ids:
|
||||
if store.get_user(mid) is None:
|
||||
raise ApiError(400, "invalid_request", "Неизвестный участник чата")
|
||||
chat = store.create_chat(title, member_ids)
|
||||
return JSONResponse(chat, status_code=201)
|
||||
|
||||
|
||||
@router.get("/api/v1/chats")
|
||||
def list_chats(
|
||||
request: Request,
|
||||
limit: str | None = Query(default=None),
|
||||
cursor: str | None = Query(default=None),
|
||||
authorization: str | None = Header(default=None),
|
||||
) -> dict[str, Any]:
|
||||
caller = current_user_id(request, authorization)
|
||||
page_size = parse_limit(limit)
|
||||
scope = f"chats:{caller}"
|
||||
after = parse_cursor(cursor, scope)
|
||||
items, has_more = get_store(request).list_chats_for(caller, page_size, after)
|
||||
next_cursor = None
|
||||
if has_more and items:
|
||||
last = items[-1]
|
||||
next_cursor = encode_cursor(last["created_at"], last["id"], scope)
|
||||
return {"items": items, "next_cursor": next_cursor}
|
||||
|
||||
|
||||
@router.get("/api/v1/chats/{chat_id}")
|
||||
def get_chat(
|
||||
chat_id: str,
|
||||
request: Request,
|
||||
authorization: str | None = Header(default=None),
|
||||
) -> dict[str, Any]:
|
||||
caller = current_user_id(request, authorization)
|
||||
chat_id = validate_chat_id(chat_id)
|
||||
store = get_store(request)
|
||||
if not store.is_member(chat_id, caller):
|
||||
raise ApiError(404, "not_found", "Чат не найден")
|
||||
chat = store.get_chat(chat_id)
|
||||
if chat is None:
|
||||
raise ApiError(404, "not_found", "Чат не найден")
|
||||
return chat
|
||||
|
||||
|
||||
@router.post("/api/v1/chats/{chat_id}/messages", status_code=201)
|
||||
def create_message(
|
||||
chat_id: str,
|
||||
request: Request,
|
||||
body: Any = Body(...),
|
||||
authorization: str | None = Header(default=None),
|
||||
) -> JSONResponse:
|
||||
caller = current_user_id(request, authorization)
|
||||
chat_id = validate_chat_id(chat_id)
|
||||
store = get_store(request)
|
||||
if not store.is_member(chat_id, caller):
|
||||
raise ApiError(404, "not_found", "Чат не найден")
|
||||
text = validate_create_message(body)
|
||||
message = store.add_message(chat_id, caller, text)
|
||||
return JSONResponse(message, status_code=201)
|
||||
|
||||
|
||||
@router.get("/api/v1/chats/{chat_id}/messages")
|
||||
def list_messages(
|
||||
chat_id: str,
|
||||
request: Request,
|
||||
limit: str | None = Query(default=None),
|
||||
cursor: str | None = Query(default=None),
|
||||
authorization: str | None = Header(default=None),
|
||||
) -> dict[str, Any]:
|
||||
caller = current_user_id(request, authorization)
|
||||
chat_id = validate_chat_id(chat_id)
|
||||
store = get_store(request)
|
||||
if not store.is_member(chat_id, caller):
|
||||
raise ApiError(404, "not_found", "Чат не найден")
|
||||
page_size = parse_limit(limit)
|
||||
scope = f"messages:{chat_id}"
|
||||
after = parse_cursor(cursor, scope)
|
||||
items, has_more = store.list_messages(chat_id, page_size, after)
|
||||
next_cursor = None
|
||||
if has_more and items:
|
||||
last = items[-1]
|
||||
next_cursor = encode_cursor(last["created_at"], last["id"], scope)
|
||||
return {"items": items, "next_cursor": next_cursor}
|
||||
+68
@@ -0,0 +1,68 @@
|
||||
import logging
|
||||
import signal
|
||||
import sys
|
||||
import uuid
|
||||
|
||||
from fastapi import FastAPI, Request
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from fastapi.responses import JSONResponse
|
||||
from starlette.exceptions import HTTPException as StarletteHTTPException
|
||||
|
||||
from .config import settings
|
||||
from .errors import ApiError, error_response
|
||||
from .routers import auth, chats, health, messages, users
|
||||
|
||||
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s %(message)s")
|
||||
log = logging.getLogger("app")
|
||||
|
||||
app = FastAPI(title="Messenger", version="1.3.0")
|
||||
|
||||
|
||||
@app.middleware("http")
|
||||
async def add_headers(request: Request, call_next):
|
||||
rid = request.headers.get("x-request-id") or uuid.uuid4().hex
|
||||
request.state.request_id = rid
|
||||
try:
|
||||
response = await call_next(request)
|
||||
except ApiError as exc:
|
||||
response = error_response(request, exc.status, exc.code, exc.message)
|
||||
response.headers["X-Request-Id"] = rid
|
||||
response.headers["X-Instance-Id"] = settings.instance_id
|
||||
return response
|
||||
|
||||
|
||||
@app.exception_handler(ApiError)
|
||||
async def api_error_handler(request: Request, exc: ApiError):
|
||||
return error_response(request, exc.status, exc.code, exc.message)
|
||||
|
||||
|
||||
@app.exception_handler(RequestValidationError)
|
||||
async def validation_handler(request: Request, exc: RequestValidationError):
|
||||
return error_response(request, 400, "invalid_request", "Некорректный запрос")
|
||||
|
||||
|
||||
@app.exception_handler(StarletteHTTPException)
|
||||
async def http_handler(request: Request, exc: StarletteHTTPException):
|
||||
code = {401: "unauthorized", 404: "not_found", 405: "invalid_request"}.get(exc.status_code, "invalid_request")
|
||||
return error_response(request, exc.status_code, code, str(exc.detail) or "Ошибка")
|
||||
|
||||
|
||||
@app.exception_handler(Exception)
|
||||
async def unhandled(request: Request, exc: Exception):
|
||||
log.exception("unhandled error")
|
||||
return error_response(request, 500, "internal_error", "Внутренняя ошибка")
|
||||
|
||||
|
||||
app.include_router(health.router)
|
||||
app.include_router(users.router)
|
||||
app.include_router(auth.router)
|
||||
app.include_router(chats.router)
|
||||
app.include_router(messages.router)
|
||||
|
||||
|
||||
def _shutdown(signum, frame):
|
||||
log.info("received signal %s, shutting down", signum)
|
||||
sys.exit(0)
|
||||
|
||||
|
||||
signal.signal(signal.SIGTERM, _shutdown)
|
||||
@@ -0,0 +1,39 @@
|
||||
import os
|
||||
from logging.config import fileConfig
|
||||
|
||||
from alembic import context
|
||||
from sqlalchemy import engine_from_config, pool
|
||||
|
||||
from app.db import Base
|
||||
from app import models # noqa: F401
|
||||
|
||||
config = context.config
|
||||
if config.config_file_name is not None:
|
||||
fileConfig(config.config_file_name)
|
||||
|
||||
config.set_main_option("sqlalchemy.url", os.environ["DATABASE_URL"])
|
||||
target_metadata = Base.metadata
|
||||
|
||||
|
||||
def run_migrations_offline() -> None:
|
||||
context.configure(url=os.environ["DATABASE_URL"], target_metadata=target_metadata, literal_binds=True)
|
||||
with context.begin_transaction():
|
||||
context.run_migrations()
|
||||
|
||||
|
||||
def run_migrations_online() -> None:
|
||||
connectable = engine_from_config(
|
||||
config.get_section(config.config_ini_section, {}),
|
||||
prefix="sqlalchemy.",
|
||||
poolclass=pool.NullPool,
|
||||
)
|
||||
with connectable.connect() as connection:
|
||||
context.configure(connection=connection, target_metadata=target_metadata)
|
||||
with context.begin_transaction():
|
||||
context.run_migrations()
|
||||
|
||||
|
||||
if context.is_offline_mode():
|
||||
run_migrations_offline()
|
||||
else:
|
||||
run_migrations_online()
|
||||
@@ -0,0 +1,22 @@
|
||||
"""${message}
|
||||
|
||||
Revision ID: ${up_revision}
|
||||
Revises: ${down_revision | comma,n}
|
||||
Create Date: ${create_date}
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
${imports if imports else ""}
|
||||
|
||||
revision = ${repr(up_revision)}
|
||||
down_revision = ${repr(down_revision)}
|
||||
branch_labels = ${repr(branch_labels)}
|
||||
depends_on = ${repr(depends_on)}
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
${upgrades if upgrades else "pass"}
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
${downgrades if downgrades else "pass"}
|
||||
@@ -0,0 +1,74 @@
|
||||
"""init
|
||||
|
||||
Revision ID: 0001
|
||||
Revises:
|
||||
Create Date: 2026-11-06
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
from sqlalchemy.dialects import postgresql
|
||||
|
||||
revision = "0001"
|
||||
down_revision = None
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.create_table(
|
||||
"users",
|
||||
sa.Column("id", postgresql.UUID(as_uuid=True), primary_key=True),
|
||||
sa.Column("username", sa.String(32), nullable=False, unique=True),
|
||||
sa.Column("display_name", sa.String(100), nullable=False),
|
||||
sa.Column("password_hash", sa.Text(), nullable=False),
|
||||
sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.func.now(), nullable=False),
|
||||
)
|
||||
op.create_table(
|
||||
"sessions",
|
||||
sa.Column("token_hash", sa.String(64), primary_key=True),
|
||||
sa.Column("user_id", postgresql.UUID(as_uuid=True), sa.ForeignKey("users.id", ondelete="CASCADE"), nullable=False),
|
||||
sa.Column("expires_at", sa.DateTime(timezone=True), nullable=False),
|
||||
sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.func.now(), nullable=False),
|
||||
)
|
||||
op.create_index("ix_sessions_user_id", "sessions", ["user_id"])
|
||||
op.create_index("ix_sessions_expires_at", "sessions", ["expires_at"])
|
||||
op.create_table(
|
||||
"chats",
|
||||
sa.Column("id", postgresql.UUID(as_uuid=True), primary_key=True),
|
||||
sa.Column("title", sa.String(100), nullable=False),
|
||||
sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.func.now(), nullable=False),
|
||||
)
|
||||
op.create_table(
|
||||
"chat_members",
|
||||
sa.Column("chat_id", postgresql.UUID(as_uuid=True), sa.ForeignKey("chats.id", ondelete="CASCADE"), primary_key=True),
|
||||
sa.Column("user_id", postgresql.UUID(as_uuid=True), sa.ForeignKey("users.id", ondelete="CASCADE"), primary_key=True),
|
||||
)
|
||||
op.create_table(
|
||||
"messages",
|
||||
sa.Column("id", postgresql.UUID(as_uuid=True), primary_key=True),
|
||||
sa.Column("chat_id", postgresql.UUID(as_uuid=True), sa.ForeignKey("chats.id", ondelete="CASCADE"), nullable=False),
|
||||
sa.Column("sender_id", postgresql.UUID(as_uuid=True), sa.ForeignKey("users.id"), nullable=False),
|
||||
sa.Column("text", sa.Text(), nullable=False),
|
||||
sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.func.now(), nullable=False),
|
||||
)
|
||||
op.create_index("ix_messages_chat_created_id", "messages", ["chat_id", "created_at", "id"])
|
||||
op.create_table(
|
||||
"idempotency_keys",
|
||||
sa.Column("user_id", postgresql.UUID(as_uuid=True), sa.ForeignKey("users.id", ondelete="CASCADE"), primary_key=True),
|
||||
sa.Column("method", sa.String(8), primary_key=True),
|
||||
sa.Column("path", sa.String(255), primary_key=True),
|
||||
sa.Column("key", sa.String(128), primary_key=True),
|
||||
sa.Column("body_hash", sa.String(64), nullable=False),
|
||||
sa.Column("message_id", postgresql.UUID(as_uuid=True), sa.ForeignKey("messages.id", ondelete="CASCADE"), nullable=False),
|
||||
sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.func.now(), nullable=False),
|
||||
)
|
||||
op.create_index("ix_idem_created", "idempotency_keys", ["created_at"])
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.drop_table("idempotency_keys")
|
||||
op.drop_table("messages")
|
||||
op.drop_table("chat_members")
|
||||
op.drop_table("chats")
|
||||
op.drop_table("sessions")
|
||||
op.drop_table("users")
|
||||
@@ -0,0 +1,75 @@
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
|
||||
from sqlalchemy import (
|
||||
DateTime,
|
||||
ForeignKey,
|
||||
Index,
|
||||
Integer,
|
||||
String,
|
||||
Text,
|
||||
UniqueConstraint,
|
||||
func,
|
||||
)
|
||||
from sqlalchemy.dialects.postgresql import UUID
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
|
||||
from .db import Base
|
||||
|
||||
|
||||
def _uuid() -> uuid.UUID:
|
||||
return uuid.uuid4()
|
||||
|
||||
|
||||
class User(Base):
|
||||
__tablename__ = "users"
|
||||
id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=_uuid)
|
||||
username: Mapped[str] = mapped_column(String(32), unique=True, nullable=False)
|
||||
display_name: Mapped[str] = mapped_column(String(100), nullable=False)
|
||||
password_hash: Mapped[str] = mapped_column(Text, nullable=False)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now(), nullable=False)
|
||||
|
||||
|
||||
class SessionRow(Base):
|
||||
__tablename__ = "sessions"
|
||||
token_hash: Mapped[str] = mapped_column(String(64), primary_key=True)
|
||||
user_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), ForeignKey("users.id", ondelete="CASCADE"), nullable=False, index=True)
|
||||
expires_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, index=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now(), nullable=False)
|
||||
|
||||
|
||||
class Chat(Base):
|
||||
__tablename__ = "chats"
|
||||
id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=_uuid)
|
||||
title: Mapped[str] = mapped_column(String(100), nullable=False)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now(), nullable=False)
|
||||
members: Mapped[list["ChatMember"]] = relationship(back_populates="chat", cascade="all, delete-orphan")
|
||||
|
||||
|
||||
class ChatMember(Base):
|
||||
__tablename__ = "chat_members"
|
||||
chat_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), ForeignKey("chats.id", ondelete="CASCADE"), primary_key=True)
|
||||
user_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), ForeignKey("users.id", ondelete="CASCADE"), primary_key=True)
|
||||
chat: Mapped[Chat] = relationship(back_populates="members")
|
||||
|
||||
|
||||
class Message(Base):
|
||||
__tablename__ = "messages"
|
||||
id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=_uuid)
|
||||
chat_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), ForeignKey("chats.id", ondelete="CASCADE"), nullable=False)
|
||||
sender_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), ForeignKey("users.id"), nullable=False)
|
||||
text: Mapped[str] = mapped_column(Text, nullable=False)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now(), nullable=False)
|
||||
__table_args__ = (Index("ix_messages_chat_created_id", "chat_id", "created_at", "id"),)
|
||||
|
||||
|
||||
class IdempotencyKey(Base):
|
||||
__tablename__ = "idempotency_keys"
|
||||
user_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), ForeignKey("users.id", ondelete="CASCADE"), primary_key=True)
|
||||
method: Mapped[str] = mapped_column(String(8), primary_key=True)
|
||||
path: Mapped[str] = mapped_column(String(255), primary_key=True)
|
||||
key: Mapped[str] = mapped_column(String(128), primary_key=True)
|
||||
body_hash: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
message_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), ForeignKey("messages.id", ondelete="CASCADE"), nullable=False)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now(), nullable=False)
|
||||
__table_args__ = (Index("ix_idem_created", "created_at"),)
|
||||
@@ -0,0 +1,54 @@
|
||||
import base64
|
||||
import binascii
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from fastapi import APIRouter, Depends, Request, Security
|
||||
from fastapi.security import HTTPBasicCredentials
|
||||
from sqlalchemy import delete, select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..config import settings
|
||||
from ..deps import basic_scheme, current_user, get_db
|
||||
from ..errors import ApiError
|
||||
from ..models import SessionRow, User
|
||||
from ..schemas import SessionOut, UserOut
|
||||
from ..security import new_token, session_expiry, token_hash, verify_password
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
def _parse_basic(header: str):
|
||||
if not header.lower().startswith("basic "):
|
||||
raise ApiError(401, "unauthorized", "Требуется Basic")
|
||||
try:
|
||||
raw = base64.b64decode(header[6:].strip(), validate=True).decode("utf-8")
|
||||
except (binascii.Error, UnicodeDecodeError):
|
||||
raise ApiError(401, "unauthorized", "Некорректный Basic")
|
||||
if ":" not in raw:
|
||||
raise ApiError(401, "unauthorized", "Некорректный Basic")
|
||||
username, password = raw.split(":", 1)
|
||||
return username, password
|
||||
|
||||
|
||||
@router.post("/api/v1/auth/sessions", response_model=SessionOut, status_code=201)
|
||||
def login(
|
||||
request: Request,
|
||||
_basic: HTTPBasicCredentials | None = Security(basic_scheme),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
username, password = _parse_basic(request.headers.get("authorization", ""))
|
||||
user = db.scalar(select(User).where(User.username == username))
|
||||
if user is None or not verify_password(password, user.password_hash):
|
||||
raise ApiError(401, "unauthorized", "Неверные учётные данные")
|
||||
token = new_token()
|
||||
expires = session_expiry(settings.session_ttl_seconds)
|
||||
db.add(SessionRow(token_hash=token_hash(token), user_id=user.id, expires_at=expires))
|
||||
db.commit()
|
||||
return SessionOut(token=token, token_type="Bearer", expires_at=expires, user=UserOut.model_validate(user, from_attributes=True))
|
||||
|
||||
|
||||
@router.delete("/api/v1/auth/sessions/current", status_code=204)
|
||||
def logout(request: Request, user: User = Security(current_user), db: Session = Depends(get_db)):
|
||||
db.execute(delete(SessionRow).where(SessionRow.token_hash == request.state.token_hash))
|
||||
db.commit()
|
||||
return None
|
||||
@@ -0,0 +1,100 @@
|
||||
import base64
|
||||
import json
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
|
||||
from fastapi import APIRouter, Depends, Query, Security
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..deps import current_user, get_db, parse_uuid
|
||||
from ..errors import ApiError
|
||||
from ..models import Chat, ChatMember, User
|
||||
from ..schemas import ChatOut, ChatPage, CreateChat
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
def _chat_out(chat: Chat, member_ids) -> ChatOut:
|
||||
return ChatOut(id=chat.id, title=chat.title, member_ids=list(member_ids), created_at=chat.created_at)
|
||||
|
||||
|
||||
def _member_ids(db: Session, chat_id) -> list:
|
||||
return list(db.scalars(select(ChatMember.user_id).where(ChatMember.chat_id == chat_id)))
|
||||
|
||||
|
||||
def _require_member(db: Session, chat_id, user_id) -> Chat:
|
||||
chat = db.get(Chat, chat_id)
|
||||
if chat is None:
|
||||
raise ApiError(404, "not_found", "Чат не найден")
|
||||
if db.get(ChatMember, (chat_id, user_id)) is None:
|
||||
raise ApiError(404, "not_found", "Чат не найден")
|
||||
return chat
|
||||
|
||||
|
||||
def _encode_cursor(created_at: datetime, id_: uuid.UUID) -> str:
|
||||
payload = json.dumps({"t": created_at.isoformat(), "i": str(id_)}).encode()
|
||||
return base64.urlsafe_b64encode(payload).decode().rstrip("=")
|
||||
|
||||
|
||||
def _decode_cursor(cursor: str):
|
||||
try:
|
||||
pad = "=" * (-len(cursor) % 4)
|
||||
data = json.loads(base64.urlsafe_b64decode(cursor + pad))
|
||||
return datetime.fromisoformat(data["t"]), uuid.UUID(data["i"])
|
||||
except Exception:
|
||||
raise ApiError(400, "invalid_request", "Некорректный cursor")
|
||||
|
||||
|
||||
@router.post("/api/v1/chats", response_model=ChatOut, status_code=201)
|
||||
def create_chat(body: CreateChat, user: User = Security(current_user), db: Session = Depends(get_db)):
|
||||
if not body.title.strip():
|
||||
raise ApiError(400, "invalid_request", "title не может быть пустым")
|
||||
ids = list(dict.fromkeys(body.member_ids))
|
||||
if user.id not in ids:
|
||||
raise ApiError(400, "invalid_request", "Вызывающий должен быть участником")
|
||||
found = set(db.scalars(select(User.id).where(User.id.in_(ids))))
|
||||
if found != set(ids):
|
||||
raise ApiError(400, "invalid_request", "Неизвестный участник")
|
||||
chat = Chat(title=body.title)
|
||||
db.add(chat)
|
||||
db.flush()
|
||||
for uid in ids:
|
||||
db.add(ChatMember(chat_id=chat.id, user_id=uid))
|
||||
db.commit()
|
||||
db.refresh(chat)
|
||||
return _chat_out(chat, ids)
|
||||
|
||||
|
||||
@router.get("/api/v1/chats", response_model=ChatPage)
|
||||
def list_chats(
|
||||
limit: int = Query(50, ge=1, le=100),
|
||||
cursor: str | None = Query(None),
|
||||
user: User = Security(current_user),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
stmt = (
|
||||
select(Chat)
|
||||
.join(ChatMember, ChatMember.chat_id == Chat.id)
|
||||
.where(ChatMember.user_id == user.id)
|
||||
.order_by(Chat.created_at.asc(), Chat.id.asc())
|
||||
.limit(limit + 1)
|
||||
)
|
||||
if cursor:
|
||||
t, i = _decode_cursor(cursor)
|
||||
stmt = stmt.where((Chat.created_at > t) | ((Chat.created_at == t) & (Chat.id > i)))
|
||||
rows = list(db.scalars(stmt))
|
||||
next_cursor = None
|
||||
if len(rows) > limit:
|
||||
rows = rows[:limit]
|
||||
last = rows[-1]
|
||||
next_cursor = _encode_cursor(last.created_at, last.id)
|
||||
items = [_chat_out(c, _member_ids(db, c.id)) for c in rows]
|
||||
return ChatPage(items=items, next_cursor=next_cursor)
|
||||
|
||||
|
||||
@router.get("/api/v1/chats/{chat_id}", response_model=ChatOut)
|
||||
def get_chat(chat_id: str, user: User = Security(current_user), db: Session = Depends(get_db)):
|
||||
cid = parse_uuid(chat_id)
|
||||
chat = _require_member(db, cid, user.id)
|
||||
return _chat_out(chat, _member_ids(db, cid))
|
||||
@@ -0,0 +1,23 @@
|
||||
from fastapi import APIRouter, Depends
|
||||
from sqlalchemy import text
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..deps import get_db
|
||||
from ..errors import ApiError
|
||||
from ..schemas import Health
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.get("/health/live", response_model=Health)
|
||||
def live():
|
||||
return Health()
|
||||
|
||||
|
||||
@router.get("/health/ready", response_model=Health)
|
||||
def ready(db: Session = Depends(get_db)):
|
||||
try:
|
||||
db.execute(text("SELECT 1"))
|
||||
except Exception:
|
||||
raise ApiError(503, "unavailable", "База данных недоступна")
|
||||
return Health()
|
||||
@@ -0,0 +1,98 @@
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
import uuid
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
from fastapi import APIRouter, Depends, Header, Query, Request, Security
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..config import settings
|
||||
from ..deps import current_user, get_db, parse_uuid
|
||||
from ..errors import ApiError
|
||||
from ..models import Chat, ChatMember, IdempotencyKey, Message, User
|
||||
from ..schemas import CreateMessage, MessageOut, MessagePage
|
||||
from .chats import _decode_cursor, _encode_cursor, _require_member
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
_KEY_RE = re.compile(r"^[A-Za-z0-9._:-]{1,128}$")
|
||||
|
||||
|
||||
def _body_hash(body: CreateMessage) -> str:
|
||||
canonical = json.dumps({"text": body.text}, sort_keys=True, ensure_ascii=False)
|
||||
return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
@router.post("/api/v1/chats/{chat_id}/messages", response_model=MessageOut, status_code=201)
|
||||
def create_message(
|
||||
chat_id: str,
|
||||
body: CreateMessage,
|
||||
request: Request,
|
||||
idempotency_key: str | None = Header(default=None, alias="Idempotency-Key"),
|
||||
user: User = Security(current_user),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
cid = parse_uuid(chat_id)
|
||||
_require_member(db, cid, user.id)
|
||||
if not body.text.strip():
|
||||
raise ApiError(400, "invalid_request", "text не может быть пустым")
|
||||
if not idempotency_key or not _KEY_RE.match(idempotency_key):
|
||||
raise ApiError(400, "invalid_request", "Некорректный Idempotency-Key")
|
||||
path = f"/api/v1/chats/{cid}/messages"
|
||||
bh = _body_hash(body)
|
||||
|
||||
existing = db.get(IdempotencyKey, (user.id, "POST", path, idempotency_key))
|
||||
if existing is not None:
|
||||
if existing.body_hash != bh:
|
||||
raise ApiError(409, "conflict", "Ключ уже использован с другим телом")
|
||||
msg = db.get(Message, existing.message_id)
|
||||
return MessageOut.model_validate(msg, from_attributes=True)
|
||||
|
||||
msg = Message(chat_id=cid, sender_id=user.id, text=body.text)
|
||||
db.add(msg)
|
||||
db.flush()
|
||||
db.add(IdempotencyKey(user_id=user.id, method="POST", path=path, key=idempotency_key, body_hash=bh, message_id=msg.id))
|
||||
try:
|
||||
db.commit()
|
||||
except IntegrityError:
|
||||
db.rollback()
|
||||
existing = db.get(IdempotencyKey, (user.id, "POST", path, idempotency_key))
|
||||
if existing is None:
|
||||
raise ApiError(500, "internal_error", "Не удалось сохранить сообщение")
|
||||
if existing.body_hash != bh:
|
||||
raise ApiError(409, "conflict", "Ключ уже использован с другим телом")
|
||||
msg = db.get(Message, existing.message_id)
|
||||
return MessageOut.model_validate(msg, from_attributes=True)
|
||||
db.refresh(msg)
|
||||
return MessageOut.model_validate(msg, from_attributes=True)
|
||||
|
||||
|
||||
@router.get("/api/v1/chats/{chat_id}/messages", response_model=MessagePage)
|
||||
def list_messages(
|
||||
chat_id: str,
|
||||
limit: int = Query(50, ge=1, le=100),
|
||||
cursor: str | None = Query(None),
|
||||
user: User = Security(current_user),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
cid = parse_uuid(chat_id)
|
||||
_require_member(db, cid, user.id)
|
||||
stmt = (
|
||||
select(Message)
|
||||
.where(Message.chat_id == cid)
|
||||
.order_by(Message.created_at.asc(), Message.id.asc())
|
||||
.limit(limit + 1)
|
||||
)
|
||||
if cursor:
|
||||
t, i = _decode_cursor(cursor)
|
||||
stmt = stmt.where((Message.created_at > t) | ((Message.created_at == t) & (Message.id > i)))
|
||||
rows = list(db.scalars(stmt))
|
||||
next_cursor = None
|
||||
if len(rows) > limit:
|
||||
rows = rows[:limit]
|
||||
last = rows[-1]
|
||||
next_cursor = _encode_cursor(last.created_at, last.id)
|
||||
return MessagePage(items=[MessageOut.model_validate(m, from_attributes=True) for m in rows], next_cursor=next_cursor)
|
||||
@@ -0,0 +1,32 @@
|
||||
from fastapi import APIRouter, Depends, Security
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..deps import current_user, get_db
|
||||
from ..errors import ApiError
|
||||
from ..models import User
|
||||
from ..schemas import CreateUser, UserOut
|
||||
from ..security import hash_password
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.post("/api/v1/users", response_model=UserOut, status_code=201)
|
||||
def register(body: CreateUser, db: Session = Depends(get_db)):
|
||||
if not body.display_name.strip():
|
||||
raise ApiError(400, "invalid_request", "display_name не может быть пустым")
|
||||
user = User(username=body.username, display_name=body.display_name, password_hash=hash_password(body.password))
|
||||
db.add(user)
|
||||
try:
|
||||
db.commit()
|
||||
except IntegrityError:
|
||||
db.rollback()
|
||||
raise ApiError(409, "conflict", "username занят")
|
||||
db.refresh(user)
|
||||
return user
|
||||
|
||||
|
||||
@router.get("/api/v1/users/me", response_model=UserOut)
|
||||
def me(user: User = Security(current_user)):
|
||||
return user
|
||||
@@ -0,0 +1,73 @@
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
from typing import List, Optional
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
|
||||
class UserOut(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
id: uuid.UUID
|
||||
username: str
|
||||
display_name: str
|
||||
created_at: datetime
|
||||
|
||||
|
||||
class CreateUser(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
username: str = Field(pattern=r"^[a-z0-9_]{3,32}$")
|
||||
display_name: str = Field(min_length=1, max_length=100)
|
||||
password: str = Field(min_length=12, max_length=128)
|
||||
|
||||
|
||||
class SessionOut(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
token: str
|
||||
token_type: str = "Bearer"
|
||||
expires_at: datetime
|
||||
user: UserOut
|
||||
|
||||
|
||||
class ChatOut(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
id: uuid.UUID
|
||||
title: str
|
||||
member_ids: List[uuid.UUID]
|
||||
created_at: datetime
|
||||
|
||||
|
||||
class CreateChat(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
title: str = Field(min_length=1, max_length=100)
|
||||
member_ids: List[uuid.UUID] = Field(min_length=1, max_length=100)
|
||||
|
||||
|
||||
class MessageOut(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
id: uuid.UUID
|
||||
chat_id: uuid.UUID
|
||||
sender_id: uuid.UUID
|
||||
text: str
|
||||
created_at: datetime
|
||||
|
||||
|
||||
class CreateMessage(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
text: str = Field(min_length=1, max_length=4000)
|
||||
|
||||
|
||||
class ChatPage(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
items: List[ChatOut]
|
||||
next_cursor: Optional[str]
|
||||
|
||||
|
||||
class MessagePage(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
items: List[MessageOut]
|
||||
next_cursor: Optional[str]
|
||||
|
||||
|
||||
class Health(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
status: str = "ok"
|
||||
@@ -0,0 +1,33 @@
|
||||
import hashlib
|
||||
import secrets
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
from argon2 import PasswordHasher
|
||||
from argon2.exceptions import VerifyMismatchError
|
||||
|
||||
_ph = PasswordHasher()
|
||||
|
||||
|
||||
def hash_password(password: str) -> str:
|
||||
return _ph.hash(password)
|
||||
|
||||
|
||||
def verify_password(password: str, hashed: str) -> bool:
|
||||
try:
|
||||
return _ph.verify(hashed, password)
|
||||
except VerifyMismatchError:
|
||||
return False
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def new_token() -> str:
|
||||
return secrets.token_urlsafe(48)
|
||||
|
||||
|
||||
def token_hash(token: str) -> str:
|
||||
return hashlib.sha256(token.encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
def session_expiry(ttl_seconds: int) -> datetime:
|
||||
return datetime.now(timezone.utc) + timedelta(seconds=ttl_seconds)
|
||||
+129
@@ -0,0 +1,129 @@
|
||||
"""Сессии: PostgreSQL — источник истины, Redis — кэш с TTL.
|
||||
|
||||
При недоступности Redis работаем напрямую с БД (не принимаем анонимов).
|
||||
При logout инвалидируем и БД, и кэш.
|
||||
"""
|
||||
import logging
|
||||
import os
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Any
|
||||
|
||||
import redis
|
||||
from psycopg_pool import ConnectionPool
|
||||
|
||||
from .security import new_token, token_hash
|
||||
|
||||
logger = logging.getLogger("messenger.sessions")
|
||||
|
||||
|
||||
def _now() -> datetime:
|
||||
return datetime.now(timezone.utc)
|
||||
|
||||
|
||||
def _ttl_seconds() -> int:
|
||||
return int(os.environ.get("SESSION_TTL_SECONDS", "3600"))
|
||||
|
||||
|
||||
class SessionStore:
|
||||
def __init__(self, pool: ConnectionPool, cache: redis.Redis | None) -> None:
|
||||
self.pool = pool
|
||||
self.cache = cache
|
||||
|
||||
# --- кэш --------------------------------------------------------------
|
||||
def _cache_get(self, th: str) -> dict[str, Any] | None:
|
||||
if self.cache is None:
|
||||
return None
|
||||
try:
|
||||
raw = self.cache.hgetall("session:" + th)
|
||||
except redis.RedisError as exc:
|
||||
logger.warning("redis get failed: %s", type(exc).__name__)
|
||||
return None
|
||||
if not raw:
|
||||
return None
|
||||
return {
|
||||
"user_id": raw[b"user_id"].decode(),
|
||||
"expires_at": raw[b"expires_at"].decode(),
|
||||
}
|
||||
|
||||
def _cache_put(self, th: str, user_id: str, expires_at: datetime) -> None:
|
||||
if self.cache is None:
|
||||
return
|
||||
ttl = max(1, int((expires_at - _now()).total_seconds()))
|
||||
try:
|
||||
pipe = self.cache.pipeline()
|
||||
pipe.hset(
|
||||
"session:" + th,
|
||||
mapping={
|
||||
"user_id": user_id,
|
||||
"expires_at": expires_at.strftime("%Y-%m-%dT%H:%M:%SZ"),
|
||||
},
|
||||
)
|
||||
pipe.expire("session:" + th, ttl)
|
||||
pipe.execute()
|
||||
except redis.RedisError as exc:
|
||||
logger.warning("redis put failed: %s", type(exc).__name__)
|
||||
|
||||
def _cache_del(self, th: str) -> None:
|
||||
if self.cache is None:
|
||||
return
|
||||
try:
|
||||
self.cache.delete("session:" + th)
|
||||
except redis.RedisError as exc:
|
||||
logger.warning("redis del failed: %s", type(exc).__name__)
|
||||
|
||||
# --- публичный API ----------------------------------------------------
|
||||
def create(self, user_id: str) -> dict[str, Any]:
|
||||
token = new_token()
|
||||
th = token_hash(token)
|
||||
expires_at = _now() + timedelta(seconds=_ttl_seconds())
|
||||
with self.pool.connection() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"INSERT INTO sessions(token_hash, user_id, created_at, expires_at)"
|
||||
" VALUES (%s, %s, now(), %s)",
|
||||
(th, user_id, expires_at),
|
||||
)
|
||||
conn.commit()
|
||||
self._cache_put(th, user_id, expires_at)
|
||||
return {
|
||||
"token": token,
|
||||
"expires_at": expires_at.strftime("%Y-%m-%dT%H:%M:%SZ"),
|
||||
}
|
||||
|
||||
def resolve(self, token: str) -> str | None:
|
||||
"""Возвращает user_id для действующей сессии или None."""
|
||||
th = token_hash(token)
|
||||
cached = self._cache_get(th)
|
||||
if cached is not None:
|
||||
try:
|
||||
exp = datetime.strptime(cached["expires_at"], "%Y-%m-%dT%H:%M:%SZ").replace(
|
||||
tzinfo=timezone.utc
|
||||
)
|
||||
except ValueError:
|
||||
exp = None
|
||||
if exp is not None and exp > _now():
|
||||
return cached["user_id"]
|
||||
self._cache_del(th)
|
||||
with self.pool.connection() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"SELECT user_id, expires_at FROM sessions WHERE token_hash = %s",
|
||||
(th,),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if row is None:
|
||||
return None
|
||||
user_id, expires_at = row
|
||||
if expires_at <= _now():
|
||||
self.revoke(token)
|
||||
return None
|
||||
self._cache_put(th, str(user_id), expires_at)
|
||||
return str(user_id)
|
||||
|
||||
def revoke(self, token: str) -> None:
|
||||
th = token_hash(token)
|
||||
with self.pool.connection() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute("DELETE FROM sessions WHERE token_hash = %s", (th,))
|
||||
conn.commit()
|
||||
self._cache_del(th)
|
||||
+204
@@ -0,0 +1,204 @@
|
||||
"""Хранилище на PostgreSQL: пользователи, чаты, участники, сообщения."""
|
||||
import uuid
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any
|
||||
|
||||
import psycopg
|
||||
from psycopg_pool import ConnectionPool
|
||||
|
||||
|
||||
def utc_now() -> str:
|
||||
"""RFC 3339 UTC с суффиксом Z, секунды — как в примерах контракта."""
|
||||
return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
|
||||
|
||||
|
||||
def new_id() -> str:
|
||||
return str(uuid.uuid4())
|
||||
|
||||
|
||||
def _iso(dt: datetime) -> str:
|
||||
"""RFC 3339 UTC с суффиксом Z, микросекунды сохраняются для keyset-пагинации."""
|
||||
return dt.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%fZ")
|
||||
|
||||
|
||||
def _user_row(row: tuple) -> dict[str, Any]:
|
||||
uid, username, display_name, created_at = row
|
||||
return {
|
||||
"id": str(uid),
|
||||
"username": username,
|
||||
"display_name": display_name,
|
||||
"created_at": _iso(created_at),
|
||||
}
|
||||
|
||||
|
||||
def _chat_row(row: tuple, member_ids: list[str]) -> dict[str, Any]:
|
||||
cid, title, created_at = row
|
||||
return {
|
||||
"id": str(cid),
|
||||
"title": title,
|
||||
"member_ids": member_ids,
|
||||
"created_at": _iso(created_at),
|
||||
}
|
||||
|
||||
|
||||
def _message_row(row: tuple) -> dict[str, Any]:
|
||||
mid, chat_id, sender_id, text, created_at = row
|
||||
return {
|
||||
"id": str(mid),
|
||||
"chat_id": str(chat_id),
|
||||
"sender_id": str(sender_id),
|
||||
"text": text,
|
||||
"created_at": _iso(created_at),
|
||||
}
|
||||
|
||||
|
||||
class Store:
|
||||
"""Все данные в PostgreSQL; соединения берутся из пула."""
|
||||
|
||||
def __init__(self, pool: ConnectionPool) -> None:
|
||||
self.pool = pool
|
||||
|
||||
# --- пользователи -----------------------------------------------------
|
||||
def create_user(
|
||||
self, username: str, display_name: str, password_hash: str
|
||||
) -> dict[str, Any] | None:
|
||||
user_id = new_id()
|
||||
try:
|
||||
with self.pool.connection() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"INSERT INTO users(id, username, display_name, password_hash, created_at)"
|
||||
" VALUES (%s, %s, %s, %s, now())"
|
||||
" RETURNING id, username, display_name, created_at",
|
||||
(user_id, username, display_name, password_hash),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
conn.commit()
|
||||
except psycopg.errors.UniqueViolation:
|
||||
return None
|
||||
return _user_row(row)
|
||||
|
||||
def get_user(self, user_id: str) -> dict[str, Any] | None:
|
||||
with self.pool.connection() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"SELECT id, username, display_name, created_at FROM users WHERE id = %s",
|
||||
(user_id,),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
return _user_row(row) if row else None
|
||||
|
||||
def get_user_by_username(self, username: str) -> tuple[dict[str, Any], str] | None:
|
||||
with self.pool.connection() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"SELECT id, username, display_name, created_at, password_hash"
|
||||
" FROM users WHERE username = %s",
|
||||
(username,),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if row is None:
|
||||
return None
|
||||
return _user_row(row[:4]), row[4]
|
||||
|
||||
# --- чаты -------------------------------------------------------------
|
||||
def create_chat(self, title: str, member_ids: list[str]) -> dict[str, Any]:
|
||||
chat_id = new_id()
|
||||
with self.pool.connection() as conn:
|
||||
with conn.transaction():
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"INSERT INTO chats(id, title, created_at) VALUES (%s, %s, now())"
|
||||
" RETURNING id, title, created_at",
|
||||
(chat_id, title),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
cur.executemany(
|
||||
"INSERT INTO chat_members(chat_id, user_id) VALUES (%s, %s)",
|
||||
[(chat_id, mid) for mid in member_ids],
|
||||
)
|
||||
return _chat_row(row, list(member_ids))
|
||||
|
||||
def _members(self, cur, chat_id: str) -> list[str]:
|
||||
cur.execute(
|
||||
"SELECT user_id FROM chat_members WHERE chat_id = %s ORDER BY user_id",
|
||||
(chat_id,),
|
||||
)
|
||||
return [str(r[0]) for r in cur.fetchall()]
|
||||
|
||||
def get_chat(self, chat_id: str) -> dict[str, Any] | None:
|
||||
with self.pool.connection() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"SELECT id, title, created_at FROM chats WHERE id = %s", (chat_id,)
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if row is None:
|
||||
return None
|
||||
members = self._members(cur, chat_id)
|
||||
return _chat_row(row, members)
|
||||
|
||||
def is_member(self, chat_id: str, user_id: str) -> bool:
|
||||
with self.pool.connection() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"SELECT 1 FROM chat_members WHERE chat_id = %s AND user_id = %s",
|
||||
(chat_id, user_id),
|
||||
)
|
||||
return cur.fetchone() is not None
|
||||
|
||||
def list_chats_for(
|
||||
self, user_id: str, limit: int, after: tuple[str, str] | None
|
||||
) -> tuple[list[dict[str, Any]], bool]:
|
||||
with self.pool.connection() as conn:
|
||||
with conn.cursor() as cur:
|
||||
sql = (
|
||||
"SELECT c.id, c.title, c.created_at FROM chats c"
|
||||
" JOIN chat_members m ON m.chat_id = c.id"
|
||||
" WHERE m.user_id = %s"
|
||||
)
|
||||
params: list[Any] = [user_id]
|
||||
if after is not None:
|
||||
sql += " AND (c.created_at, c.id) > (%s, %s)"
|
||||
params.extend(after)
|
||||
sql += " ORDER BY c.created_at, c.id LIMIT %s"
|
||||
params.append(limit + 1)
|
||||
cur.execute(sql, params)
|
||||
rows = cur.fetchall()
|
||||
items = []
|
||||
for row in rows[:limit]:
|
||||
items.append(_chat_row(row, self._members(cur, str(row[0]))))
|
||||
return items, len(rows) > limit
|
||||
|
||||
# --- сообщения --------------------------------------------------------
|
||||
def add_message(self, chat_id: str, sender_id: str, text: str) -> dict[str, Any]:
|
||||
with self.pool.connection() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"INSERT INTO messages(id, chat_id, sender_id, text, created_at)"
|
||||
" VALUES (%s, %s, %s, %s, now())"
|
||||
" RETURNING id, chat_id, sender_id, text, created_at",
|
||||
(new_id(), chat_id, sender_id, text),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
conn.commit()
|
||||
return _message_row(row)
|
||||
|
||||
def list_messages(
|
||||
self, chat_id: str, limit: int, after: tuple[str, str] | None
|
||||
) -> tuple[list[dict[str, Any]], bool]:
|
||||
with self.pool.connection() as conn:
|
||||
with conn.cursor() as cur:
|
||||
sql = (
|
||||
"SELECT id, chat_id, sender_id, text, created_at FROM messages"
|
||||
" WHERE chat_id = %s"
|
||||
)
|
||||
params: list[Any] = [chat_id]
|
||||
if after is not None:
|
||||
sql += " AND (created_at, id) > (%s, %s)"
|
||||
params.extend(after)
|
||||
sql += " ORDER BY created_at, id LIMIT %s"
|
||||
params.append(limit + 1)
|
||||
cur.execute(sql, params)
|
||||
rows = cur.fetchall()
|
||||
return [_message_row(r) for r in rows[:limit]], len(rows) > limit
|
||||
@@ -0,0 +1,122 @@
|
||||
"""Валидация тел запросов и параметров вручную, без pydantic-моделей контракта."""
|
||||
import base64
|
||||
import re
|
||||
import uuid
|
||||
from typing import Any
|
||||
|
||||
from .errors import ApiError
|
||||
|
||||
USERNAME_RE = re.compile(r"\A[a-z0-9_]{3,32}\Z")
|
||||
|
||||
|
||||
def _is_blank(value: str) -> bool:
|
||||
return value.strip() == ""
|
||||
|
||||
|
||||
def require_object(body: Any) -> dict[str, Any]:
|
||||
if not isinstance(body, dict):
|
||||
raise ApiError(400, "invalid_request", "Тело запроса должно быть JSON-объектом")
|
||||
return body
|
||||
|
||||
|
||||
def reject_extra(body: dict[str, Any], allowed: set[str]) -> None:
|
||||
if set(body) - allowed:
|
||||
raise ApiError(400, "invalid_request", "Неизвестные поля в теле запроса")
|
||||
|
||||
|
||||
def validate_create_user(body: Any) -> tuple[str, str, str]:
|
||||
body = require_object(body)
|
||||
reject_extra(body, {"username", "display_name", "password"})
|
||||
username = body.get("username")
|
||||
display_name = body.get("display_name")
|
||||
password = body.get("password")
|
||||
if not isinstance(username, str) or not USERNAME_RE.match(username):
|
||||
raise ApiError(400, "invalid_request", "Некорректный username")
|
||||
if not isinstance(display_name, str) or not (1 <= len(display_name) <= 100) or _is_blank(display_name):
|
||||
raise ApiError(400, "invalid_request", "Некорректный display_name")
|
||||
if not isinstance(password, str) or not (12 <= len(password) <= 128):
|
||||
raise ApiError(400, "invalid_request", "Пароль должен быть 12..128 символов")
|
||||
return username, display_name, password
|
||||
|
||||
|
||||
def validate_create_chat(body: Any, caller_id: str) -> tuple[str, list[str]]:
|
||||
body = require_object(body)
|
||||
reject_extra(body, {"title", "member_ids"})
|
||||
title = body.get("title")
|
||||
member_ids = body.get("member_ids")
|
||||
if not isinstance(title, str) or not (1 <= len(title) <= 100) or _is_blank(title):
|
||||
raise ApiError(400, "invalid_request", "Некорректный title")
|
||||
if not isinstance(member_ids, list) or not (1 <= len(member_ids) <= 100):
|
||||
raise ApiError(400, "invalid_request", "member_ids должен быть непустым массивом")
|
||||
seen: set[str] = set()
|
||||
for mid in member_ids:
|
||||
if not isinstance(mid, str):
|
||||
raise ApiError(400, "invalid_request", "member_ids содержит не строку")
|
||||
try:
|
||||
uuid.UUID(mid)
|
||||
except ValueError:
|
||||
raise ApiError(400, "invalid_request", "member_ids содержит не UUID")
|
||||
if mid in seen:
|
||||
raise ApiError(400, "invalid_request", "member_ids содержит дубликаты")
|
||||
seen.add(mid)
|
||||
if caller_id not in seen:
|
||||
raise ApiError(400, "invalid_request", "Вызывающий должен входить в member_ids")
|
||||
return title, list(member_ids)
|
||||
|
||||
|
||||
def validate_create_message(body: Any) -> str:
|
||||
body = require_object(body)
|
||||
reject_extra(body, {"text"})
|
||||
text = body.get("text")
|
||||
if not isinstance(text, str) or not (1 <= len(text) <= 4000) or _is_blank(text):
|
||||
raise ApiError(400, "invalid_request", "Некорректный text")
|
||||
return text
|
||||
|
||||
|
||||
def validate_chat_id(raw: str) -> str:
|
||||
"""chat_id в пути должен быть UUID, иначе 400 invalid_request."""
|
||||
try:
|
||||
uuid.UUID(raw)
|
||||
except (ValueError, TypeError):
|
||||
raise ApiError(400, "invalid_request", "Некорректный chat_id")
|
||||
return raw
|
||||
|
||||
|
||||
def parse_limit(raw: str | None, default: int = 50) -> int:
|
||||
if raw is None:
|
||||
return default
|
||||
try:
|
||||
value = int(raw)
|
||||
except (TypeError, ValueError):
|
||||
raise ApiError(400, "invalid_request", "limit должен быть целым числом")
|
||||
if not (1 <= value <= 100):
|
||||
raise ApiError(400, "invalid_request", "limit вне диапазона 1..100")
|
||||
return value
|
||||
|
||||
|
||||
def parse_cursor(raw: str | None, scope: str) -> tuple[str, str] | None:
|
||||
"""Cursor — непрозрачная строка base64url от 'scope|created_at|id'.
|
||||
|
||||
Cursor привязан к ресурсу (scope). Значения created_at/id — из БД,
|
||||
поэтому cursor переживает рестарт процесса.
|
||||
"""
|
||||
if raw is None:
|
||||
return None
|
||||
try:
|
||||
decoded = base64.urlsafe_b64decode(raw.encode("ascii")).decode("utf-8")
|
||||
except Exception:
|
||||
raise ApiError(400, "invalid_request", "Некорректный cursor")
|
||||
parts = decoded.split("|")
|
||||
if len(parts) != 3:
|
||||
raise ApiError(400, "invalid_request", "Некорректный cursor")
|
||||
cursor_scope, created_at, item_id = parts
|
||||
if cursor_scope != scope:
|
||||
raise ApiError(400, "invalid_request", "Некорректный cursor")
|
||||
if not created_at or not item_id:
|
||||
raise ApiError(400, "invalid_request", "Некорректный cursor")
|
||||
return created_at, item_id
|
||||
|
||||
|
||||
def encode_cursor(created_at: str, item_id: str, scope: str) -> str:
|
||||
raw = "|".join([scope, created_at, item_id]).encode("utf-8")
|
||||
return base64.urlsafe_b64encode(raw).decode("ascii")
|
||||
Reference in New Issue
Block a user