forked from mtusi2026/mtusi2026lab2
Выполение лабораторной 2
This commit is contained in:
@@ -0,0 +1,7 @@
|
||||
import uvicorn
|
||||
|
||||
from .config import settings
|
||||
from .main import app
|
||||
|
||||
if __name__ == "__main__":
|
||||
uvicorn.run(app, host=settings.host, port=settings.port, log_level="info", access_log=False)
|
||||
+276
@@ -0,0 +1,276 @@
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
import uuid
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
import psycopg2
|
||||
from fastapi import APIRouter, Request
|
||||
from fastapi.responses import JSONResponse, Response
|
||||
|
||||
from . import db, store
|
||||
from .cache import session_cache
|
||||
from .config import settings
|
||||
from .errors import ApiError, conflict, invalid, not_found, unauthorized
|
||||
from .security import (
|
||||
bearer_token,
|
||||
hash_password,
|
||||
new_token,
|
||||
parse_basic,
|
||||
token_fingerprint,
|
||||
verify_password,
|
||||
)
|
||||
from .serialization import (
|
||||
chat_json,
|
||||
decode_cursor,
|
||||
encode_cursor,
|
||||
iso,
|
||||
message_json,
|
||||
user_json,
|
||||
)
|
||||
|
||||
logger = logging.getLogger("app.api")
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
USERNAME_RE = re.compile(r"^[a-z0-9_]{3,32}$")
|
||||
DEFAULT_LIMIT = 50
|
||||
MAX_LIMIT = 100
|
||||
|
||||
|
||||
async def read_json(request, allowed, required):
|
||||
body = await request.body()
|
||||
if not body:
|
||||
raise invalid("Ожидается JSON-тело")
|
||||
content_type = request.headers.get("content-type", "")
|
||||
if content_type and "application/json" not in content_type.lower():
|
||||
raise ApiError(415, "unsupported_media_type", "Ожидается application/json")
|
||||
try:
|
||||
data = json.loads(body.decode("utf-8"))
|
||||
except (ValueError, UnicodeDecodeError):
|
||||
raise invalid("Некорректный JSON")
|
||||
if not isinstance(data, dict):
|
||||
raise invalid("Ожидается JSON-объект")
|
||||
if set(data) - set(allowed):
|
||||
raise invalid("Лишние поля запроса")
|
||||
if set(required) - set(data):
|
||||
raise invalid("Отсутствуют обязательные поля")
|
||||
return data
|
||||
|
||||
|
||||
def valid_username(value):
|
||||
return isinstance(value, str) and USERNAME_RE.match(value) is not None
|
||||
|
||||
|
||||
def valid_required_text(value, max_length):
|
||||
return isinstance(value, str) and 1 <= len(value) <= max_length and value.strip() != ""
|
||||
|
||||
|
||||
def valid_password(value):
|
||||
return isinstance(value, str) and 12 <= len(value) <= 128
|
||||
|
||||
|
||||
def parse_uuid(value):
|
||||
try:
|
||||
return str(uuid.UUID(value))
|
||||
except (ValueError, AttributeError, TypeError):
|
||||
raise invalid("Некорректный UUID")
|
||||
|
||||
|
||||
def parse_limit(raw):
|
||||
if raw is None:
|
||||
return DEFAULT_LIMIT
|
||||
try:
|
||||
value = int(raw)
|
||||
except (ValueError, TypeError):
|
||||
raise invalid("Некорректный limit")
|
||||
if value < 1 or value > MAX_LIMIT:
|
||||
raise invalid("Некорректный limit")
|
||||
return value
|
||||
|
||||
|
||||
def authenticate(request):
|
||||
token = bearer_token(request.headers.get("authorization"))
|
||||
if not token:
|
||||
raise unauthorized()
|
||||
fingerprint = token_fingerprint(token)
|
||||
cached = session_cache.get(fingerprint)
|
||||
if cached and isinstance(cached.get("uid"), str):
|
||||
return cached["uid"]
|
||||
with db.cursor() as cur:
|
||||
row = store.get_valid_session(cur, fingerprint)
|
||||
if not row:
|
||||
raise unauthorized()
|
||||
user_id = str(row["user_id"])
|
||||
ttl = int((row["expires_at"] - datetime.now(timezone.utc)).total_seconds())
|
||||
session_cache.set(fingerprint, user_id, ttl)
|
||||
return user_id
|
||||
|
||||
|
||||
@router.post("/api/v1/users")
|
||||
async def register_user(request: Request):
|
||||
data = await read_json(
|
||||
request,
|
||||
allowed={"username", "display_name", "password"},
|
||||
required={"username", "display_name", "password"},
|
||||
)
|
||||
username = data.get("username")
|
||||
display_name = data.get("display_name")
|
||||
password = data.get("password")
|
||||
if not valid_username(username):
|
||||
raise invalid("Некорректный username")
|
||||
if not valid_required_text(display_name, 100):
|
||||
raise invalid("Некорректный display_name")
|
||||
if not valid_password(password):
|
||||
raise invalid("Некорректный пароль")
|
||||
user_id = str(uuid.uuid4())
|
||||
password_hash = hash_password(password)
|
||||
try:
|
||||
with db.cursor(commit=True) as cur:
|
||||
row = store.create_user(cur, user_id, username, display_name, password_hash)
|
||||
except psycopg2.errors.UniqueViolation:
|
||||
raise conflict("username уже занят")
|
||||
return JSONResponse(status_code=201, content=user_json(row))
|
||||
|
||||
|
||||
@router.post("/api/v1/auth/sessions")
|
||||
async def create_session(request: Request):
|
||||
credentials = parse_basic(request.headers.get("authorization"))
|
||||
if credentials is None:
|
||||
raise unauthorized()
|
||||
username, password = credentials
|
||||
with db.cursor() as cur:
|
||||
user = store.get_user_by_username(cur, username)
|
||||
if not user or not verify_password(user["password_hash"], password):
|
||||
raise unauthorized()
|
||||
token = new_token()
|
||||
fingerprint = token_fingerprint(token)
|
||||
expires_at = datetime.now(timezone.utc) + timedelta(seconds=settings.session_ttl)
|
||||
with db.cursor(commit=True) as cur:
|
||||
store.create_session(cur, fingerprint, str(user["id"]), expires_at)
|
||||
session_cache.set(fingerprint, str(user["id"]), settings.session_ttl)
|
||||
return JSONResponse(
|
||||
status_code=201,
|
||||
content={
|
||||
"token": token,
|
||||
"token_type": "Bearer",
|
||||
"expires_at": iso(expires_at),
|
||||
"user": user_json(user),
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
@router.delete("/api/v1/auth/sessions/current")
|
||||
async def revoke_current(request: Request):
|
||||
authenticate(request)
|
||||
fingerprint = token_fingerprint(bearer_token(request.headers.get("authorization")))
|
||||
with db.cursor(commit=True) as cur:
|
||||
store.revoke_session(cur, fingerprint)
|
||||
session_cache.delete(fingerprint)
|
||||
return Response(status_code=204)
|
||||
|
||||
|
||||
@router.get("/api/v1/users/me")
|
||||
async def current_user(request: Request):
|
||||
user_id = authenticate(request)
|
||||
with db.cursor() as cur:
|
||||
user = store.get_user_by_id(cur, user_id)
|
||||
if not user:
|
||||
raise unauthorized()
|
||||
return JSONResponse(status_code=200, content=user_json(user))
|
||||
|
||||
|
||||
@router.post("/api/v1/chats")
|
||||
async def create_chat(request: Request):
|
||||
user_id = authenticate(request)
|
||||
data = await read_json(
|
||||
request, allowed={"title", "member_ids"}, required={"title", "member_ids"}
|
||||
)
|
||||
title = data.get("title")
|
||||
member_ids = data.get("member_ids")
|
||||
if not valid_required_text(title, 100):
|
||||
raise invalid("Некорректный title")
|
||||
if not isinstance(member_ids, list) or not 1 <= len(member_ids) <= 100:
|
||||
raise invalid("Некорректный member_ids")
|
||||
normalized = []
|
||||
for value in member_ids:
|
||||
if not isinstance(value, str):
|
||||
raise invalid("member_ids должен содержать UUID")
|
||||
normalized.append(parse_uuid(value))
|
||||
if len(set(normalized)) != len(normalized):
|
||||
raise invalid("Дубликаты участников")
|
||||
if user_id not in normalized:
|
||||
raise invalid("Вызывающий должен входить в member_ids")
|
||||
with db.cursor(commit=True) as cur:
|
||||
row = store.create_chat(cur, str(uuid.uuid4()), title, normalized)
|
||||
return JSONResponse(status_code=201, content=chat_json(row, sorted(normalized)))
|
||||
|
||||
|
||||
@router.get("/api/v1/chats")
|
||||
async def list_chats(request: Request):
|
||||
user_id = authenticate(request)
|
||||
limit = parse_limit(request.query_params.get("limit"))
|
||||
cursor = request.query_params.get("cursor")
|
||||
after = decode_cursor(cursor, "c", user_id) if cursor else None
|
||||
with db.cursor() as cur:
|
||||
rows = store.list_chats(cur, user_id, after, limit + 1)
|
||||
has_more = len(rows) > limit
|
||||
rows = rows[:limit]
|
||||
members = store.chat_members(cur, [str(row["id"]) for row in rows])
|
||||
items = [chat_json(row, members.get(str(row["id"]), [])) for row in rows]
|
||||
next_cursor = None
|
||||
if has_more and rows:
|
||||
last = rows[-1]
|
||||
next_cursor = encode_cursor("c", user_id, iso(last["created_at"]), str(last["id"]))
|
||||
return JSONResponse(status_code=200, content={"items": items, "next_cursor": next_cursor})
|
||||
|
||||
|
||||
@router.get("/api/v1/chats/{chat_id}")
|
||||
async def get_chat(chat_id: str, request: Request):
|
||||
user_id = authenticate(request)
|
||||
cid = parse_uuid(chat_id)
|
||||
with db.cursor() as cur:
|
||||
if not store.is_member(cur, cid, user_id):
|
||||
raise not_found()
|
||||
row = store.get_chat(cur, cid)
|
||||
members = store.chat_members(cur, [cid])
|
||||
if not row:
|
||||
raise not_found()
|
||||
return JSONResponse(status_code=200, content=chat_json(row, members.get(cid, [])))
|
||||
|
||||
|
||||
@router.post("/api/v1/chats/{chat_id}/messages")
|
||||
async def create_message(chat_id: str, request: Request):
|
||||
user_id = authenticate(request)
|
||||
cid = parse_uuid(chat_id)
|
||||
with db.cursor() as cur:
|
||||
if not store.is_member(cur, cid, user_id):
|
||||
raise not_found()
|
||||
data = await read_json(request, allowed={"text"}, required={"text"})
|
||||
text = data.get("text")
|
||||
if not valid_required_text(text, 4000):
|
||||
raise invalid("Некорректный text")
|
||||
with db.cursor(commit=True) as cur:
|
||||
row = store.create_message(cur, str(uuid.uuid4()), cid, user_id, text)
|
||||
return JSONResponse(status_code=201, content=message_json(row))
|
||||
|
||||
|
||||
@router.get("/api/v1/chats/{chat_id}/messages")
|
||||
async def list_messages(chat_id: str, request: Request):
|
||||
user_id = authenticate(request)
|
||||
cid = parse_uuid(chat_id)
|
||||
limit = parse_limit(request.query_params.get("limit"))
|
||||
cursor = request.query_params.get("cursor")
|
||||
after = decode_cursor(cursor, "m", cid) if cursor else None
|
||||
with db.cursor() as cur:
|
||||
if not store.is_member(cur, cid, user_id):
|
||||
raise not_found()
|
||||
rows = store.list_messages(cur, cid, after, limit + 1)
|
||||
has_more = len(rows) > limit
|
||||
rows = rows[:limit]
|
||||
items = [message_json(row) for row in rows]
|
||||
next_cursor = None
|
||||
if has_more and rows:
|
||||
last = rows[-1]
|
||||
next_cursor = encode_cursor("m", cid, iso(last["created_at"]), str(last["id"]))
|
||||
return JSONResponse(status_code=200, content={"items": items, "next_cursor": next_cursor})
|
||||
@@ -0,0 +1,53 @@
|
||||
import json
|
||||
import logging
|
||||
|
||||
import redis
|
||||
|
||||
from .config import settings
|
||||
|
||||
logger = logging.getLogger("app.cache")
|
||||
|
||||
PREFIX = "sess:"
|
||||
|
||||
|
||||
class SessionCache:
|
||||
def __init__(self, url):
|
||||
self.client = None
|
||||
if url:
|
||||
self.client = redis.Redis.from_url(
|
||||
url, socket_connect_timeout=1, socket_timeout=1, decode_responses=True
|
||||
)
|
||||
|
||||
def get(self, fingerprint):
|
||||
if self.client is None:
|
||||
return None
|
||||
try:
|
||||
value = self.client.get(PREFIX + fingerprint)
|
||||
except redis.RedisError as exc:
|
||||
logger.warning("cache get failed: %s", type(exc).__name__)
|
||||
return None
|
||||
if not value:
|
||||
return None
|
||||
try:
|
||||
return json.loads(value)
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
def set(self, fingerprint, user_id, ttl_seconds):
|
||||
if self.client is None or ttl_seconds <= 0:
|
||||
return
|
||||
try:
|
||||
self.client.setex(PREFIX + fingerprint, ttl_seconds, json.dumps({"uid": user_id}))
|
||||
except redis.RedisError as exc:
|
||||
logger.warning("cache set failed: %s", type(exc).__name__)
|
||||
|
||||
def delete(self, fingerprint):
|
||||
if self.client is None:
|
||||
return
|
||||
try:
|
||||
self.client.delete(PREFIX + fingerprint)
|
||||
except redis.RedisError as exc:
|
||||
logger.warning("cache delete failed: %s", type(exc).__name__)
|
||||
|
||||
|
||||
session_cache = SessionCache(settings.cache_url)
|
||||
@@ -0,0 +1,34 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def _secret(value_name, file_name):
|
||||
value = os.environ.get(value_name)
|
||||
if value:
|
||||
return value.strip()
|
||||
path = os.environ.get(file_name)
|
||||
if path:
|
||||
candidate = Path(path)
|
||||
if candidate.is_file():
|
||||
return candidate.read_text(encoding="utf-8").strip()
|
||||
return None
|
||||
|
||||
|
||||
class Settings:
|
||||
def __init__(self):
|
||||
self.host = os.environ.get("APP_HOST", "0.0.0.0")
|
||||
self.port = int(os.environ.get("APP_PORT", "8080"))
|
||||
self.app_env = os.environ.get("APP_ENV", "lab")
|
||||
self.session_ttl = int(os.environ.get("SESSION_TTL_SECONDS", "3600"))
|
||||
self.session_store = os.environ.get("SESSION_STORE", "postgres")
|
||||
self.database_url = _secret("DATABASE_URL", "DATABASE_URL_FILE")
|
||||
self.cache_url = _secret("CACHE_URL", "CACHE_URL_FILE")
|
||||
self.pool_min = int(os.environ.get("DB_POOL_MIN", "1"))
|
||||
self.pool_max = int(os.environ.get("DB_POOL_MAX", "10"))
|
||||
self.db_statement_timeout_ms = int(os.environ.get("DB_STATEMENT_TIMEOUT_MS", "5000"))
|
||||
self.db_connect_timeout_s = int(os.environ.get("DB_CONNECT_TIMEOUT_SECONDS", "5"))
|
||||
default_migrations = Path(__file__).resolve().parents[2] / "migrations"
|
||||
self.migrations_dir = os.environ.get("MIGRATIONS_DIR", str(default_migrations))
|
||||
|
||||
|
||||
settings = Settings()
|
||||
+107
@@ -0,0 +1,107 @@
|
||||
import logging
|
||||
from contextlib import contextmanager
|
||||
from pathlib import Path
|
||||
|
||||
import psycopg2
|
||||
import psycopg2.extras
|
||||
from psycopg2 import pool as pg_pool
|
||||
|
||||
from .config import settings
|
||||
from .errors import unavailable
|
||||
|
||||
logger = logging.getLogger("app.db")
|
||||
|
||||
MIGRATION_LOCK = 727001
|
||||
_pool = None
|
||||
|
||||
|
||||
def init_pool():
|
||||
global _pool
|
||||
if not settings.database_url:
|
||||
raise RuntimeError("DATABASE_URL / DATABASE_URL_FILE is not configured")
|
||||
_pool = pg_pool.ThreadedConnectionPool(
|
||||
settings.pool_min,
|
||||
settings.pool_max,
|
||||
settings.database_url,
|
||||
options="-c statement_timeout={} -c application_name=messenger-api".format(
|
||||
settings.db_statement_timeout_ms
|
||||
),
|
||||
connect_timeout=settings.db_connect_timeout_s,
|
||||
)
|
||||
logger.info("database pool ready (min=%d max=%d)", settings.pool_min, settings.pool_max)
|
||||
|
||||
|
||||
def close_pool():
|
||||
global _pool
|
||||
if _pool is not None:
|
||||
_pool.closeall()
|
||||
_pool = None
|
||||
|
||||
|
||||
@contextmanager
|
||||
def cursor(commit=False):
|
||||
if _pool is None:
|
||||
raise unavailable("Хранилище недоступно")
|
||||
try:
|
||||
conn = _pool.getconn()
|
||||
except psycopg2.Error as exc:
|
||||
logger.warning("database connection unavailable: %s", type(exc).__name__)
|
||||
raise unavailable("Хранилище недоступно") from None
|
||||
discard = False
|
||||
try:
|
||||
cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
|
||||
try:
|
||||
yield cur
|
||||
if commit:
|
||||
conn.commit()
|
||||
else:
|
||||
conn.rollback()
|
||||
finally:
|
||||
cur.close()
|
||||
except (psycopg2.OperationalError, psycopg2.InterfaceError) as exc:
|
||||
discard = True
|
||||
logger.warning("database connection lost: %s", type(exc).__name__)
|
||||
raise unavailable("Хранилище недоступно") from None
|
||||
except Exception:
|
||||
try:
|
||||
conn.rollback()
|
||||
except Exception:
|
||||
pass
|
||||
raise
|
||||
finally:
|
||||
_pool.putconn(conn, close=discard)
|
||||
|
||||
|
||||
def ping():
|
||||
with cursor() as cur:
|
||||
cur.execute("SELECT 1")
|
||||
cur.fetchone()
|
||||
|
||||
|
||||
def run_migrations():
|
||||
directory = Path(settings.migrations_dir)
|
||||
files = sorted(directory.glob("*.sql"))
|
||||
conn = _pool.getconn()
|
||||
try:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute("SELECT pg_advisory_lock(%s)", (MIGRATION_LOCK,))
|
||||
cur.execute(
|
||||
"CREATE TABLE IF NOT EXISTS schema_migrations ("
|
||||
"version text PRIMARY KEY, applied_at timestamptz NOT NULL DEFAULT now())"
|
||||
)
|
||||
cur.execute("SELECT version FROM schema_migrations")
|
||||
applied = {row[0] for row in cur.fetchall()}
|
||||
for path in files:
|
||||
version = path.stem
|
||||
if version in applied:
|
||||
continue
|
||||
cur.execute(path.read_text(encoding="utf-8"))
|
||||
cur.execute("INSERT INTO schema_migrations (version) VALUES (%s)", (version,))
|
||||
logger.info("applied migration %s", version)
|
||||
cur.execute("SELECT pg_advisory_unlock(%s)", (MIGRATION_LOCK,))
|
||||
conn.commit()
|
||||
except Exception:
|
||||
conn.rollback()
|
||||
raise
|
||||
finally:
|
||||
_pool.putconn(conn)
|
||||
@@ -0,0 +1,26 @@
|
||||
class ApiError(Exception):
|
||||
def __init__(self, status, code, message):
|
||||
super().__init__(message)
|
||||
self.status = status
|
||||
self.code = code
|
||||
self.message = message
|
||||
|
||||
|
||||
def invalid(message="Некорректный запрос"):
|
||||
return ApiError(400, "invalid_request", message)
|
||||
|
||||
|
||||
def unauthorized(message="Требуется аутентификация"):
|
||||
return ApiError(401, "unauthorized", message)
|
||||
|
||||
|
||||
def not_found(message="Объект не найден или недоступен"):
|
||||
return ApiError(404, "not_found", message)
|
||||
|
||||
|
||||
def conflict(message="Конфликт состояния"):
|
||||
return ApiError(409, "conflict", message)
|
||||
|
||||
|
||||
def unavailable(message="Сервис временно недоступен"):
|
||||
return ApiError(503, "unavailable", message)
|
||||
+106
@@ -0,0 +1,106 @@
|
||||
import logging
|
||||
import uuid
|
||||
from contextlib import asynccontextmanager
|
||||
|
||||
from fastapi import FastAPI, Request
|
||||
from fastapi.responses import JSONResponse
|
||||
from starlette.exceptions import HTTPException as StarletteHTTPException
|
||||
|
||||
from . import db
|
||||
from .api import router
|
||||
from .config import settings
|
||||
from .errors import ApiError
|
||||
|
||||
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s %(message)s")
|
||||
logger = logging.getLogger("app")
|
||||
|
||||
INSTANCE_ID = uuid.uuid4().hex[:12]
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(_app):
|
||||
db.init_pool()
|
||||
db.run_migrations()
|
||||
logger.info(
|
||||
"instance %s ready (env=%s, ttl=%ss, session_store=%s)",
|
||||
INSTANCE_ID,
|
||||
settings.app_env,
|
||||
settings.session_ttl,
|
||||
settings.session_store,
|
||||
)
|
||||
yield
|
||||
db.close_pool()
|
||||
|
||||
app = FastAPI(
|
||||
title="MTUSI Messenger — lab 2",
|
||||
version="1.2.0",
|
||||
lifespan=lifespan,
|
||||
docs_url=None,
|
||||
redoc_url=None,
|
||||
openapi_url=None,
|
||||
)
|
||||
|
||||
def error_payload(request, code, message):
|
||||
request_id = getattr(request.state, "request_id", None) or uuid.uuid4().hex
|
||||
return {"error": {"code": code, "message": message, "request_id": request_id}}
|
||||
|
||||
|
||||
def challenge_for(request):
|
||||
if request.url.path == "/api/v1/auth/sessions":
|
||||
return 'Basic realm="messenger", charset="UTF-8"'
|
||||
return 'Bearer realm="messenger"'
|
||||
|
||||
@app.middleware("http")
|
||||
async def request_context(request: Request, call_next):
|
||||
request_id = request.headers.get("x-request-id") or uuid.uuid4().hex
|
||||
request.state.request_id = request_id
|
||||
try:
|
||||
response = await call_next(request)
|
||||
except ApiError as exc:
|
||||
response = JSONResponse(status_code=exc.status, content=error_payload(request, exc.code, exc.message))
|
||||
if exc.status == 401:
|
||||
response.headers["WWW-Authenticate"] = challenge_for(request)
|
||||
except Exception:
|
||||
logger.exception("unhandled error")
|
||||
response = JSONResponse(
|
||||
status_code=500, content=error_payload(request, "internal_error", "Внутренняя ошибка")
|
||||
)
|
||||
response.headers["X-Request-Id"] = request_id
|
||||
response.headers["X-Instance-Id"] = INSTANCE_ID
|
||||
return response
|
||||
|
||||
@app.exception_handler(ApiError)
|
||||
async def handle_api_error(request: Request, exc: ApiError):
|
||||
response = JSONResponse(status_code=exc.status, content=error_payload(request, exc.code, exc.message))
|
||||
if exc.status == 401:
|
||||
response.headers["WWW-Authenticate"] = challenge_for(request)
|
||||
return response
|
||||
|
||||
@app.exception_handler(StarletteHTTPException)
|
||||
async def handle_http_error(request: Request, exc: StarletteHTTPException):
|
||||
mapping = {
|
||||
400: "invalid_request",
|
||||
401: "unauthorized",
|
||||
404: "not_found",
|
||||
405: "invalid_request",
|
||||
415: "unsupported_media_type",
|
||||
}
|
||||
code = mapping.get(exc.status_code, "invalid_request")
|
||||
response = JSONResponse(status_code=exc.status_code, content=error_payload(request, code, "Ошибка запроса"))
|
||||
if exc.status_code == 401:
|
||||
response.headers["WWW-Authenticate"] = challenge_for(request)
|
||||
return response
|
||||
|
||||
@app.get("/health/live")
|
||||
async def health_live():
|
||||
return JSONResponse(status_code=200, content={"status": "ok"})
|
||||
|
||||
@app.get("/health/ready")
|
||||
async def health_ready():
|
||||
try:
|
||||
db.ping()
|
||||
except Exception as exc:
|
||||
logger.warning("readiness check failed: %s", type(exc).__name__)
|
||||
raise ApiError(503, "unavailable", "Хранилище недоступно")
|
||||
return JSONResponse(status_code=200, content={"status": "ok"})
|
||||
|
||||
app.include_router(router)
|
||||
@@ -0,0 +1,59 @@
|
||||
import base64
|
||||
import hashlib
|
||||
import secrets
|
||||
|
||||
from argon2 import PasswordHasher
|
||||
from argon2.exceptions import Argon2Error
|
||||
|
||||
_hasher = PasswordHasher()
|
||||
|
||||
|
||||
def hash_password(password):
|
||||
return _hasher.hash(password)
|
||||
|
||||
|
||||
def verify_password(password_hash, password):
|
||||
try:
|
||||
return _hasher.verify(password_hash, password)
|
||||
except Argon2Error:
|
||||
return False
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def new_token():
|
||||
return secrets.token_urlsafe(32)
|
||||
|
||||
|
||||
def token_fingerprint(token):
|
||||
return hashlib.sha256(token.encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
def parse_basic(header):
|
||||
if not header:
|
||||
return None
|
||||
parts = header.split(" ", 1)
|
||||
if len(parts) != 2 or parts[0].lower() != "basic":
|
||||
return None
|
||||
try:
|
||||
raw = base64.b64decode(parts[1].strip(), validate=True)
|
||||
except Exception:
|
||||
return None
|
||||
try:
|
||||
decoded = raw.decode("utf-8")
|
||||
except UnicodeDecodeError:
|
||||
return None
|
||||
if ":" not in decoded:
|
||||
return None
|
||||
username, password = decoded.split(":", 1)
|
||||
return username, password
|
||||
|
||||
|
||||
def bearer_token(header):
|
||||
if not header:
|
||||
return None
|
||||
parts = header.split(" ", 1)
|
||||
if len(parts) != 2 or parts[0].lower() != "bearer":
|
||||
return None
|
||||
token = parts[1].strip()
|
||||
return token or None
|
||||
@@ -0,0 +1,66 @@
|
||||
import base64
|
||||
import json
|
||||
import uuid
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from .errors import invalid
|
||||
|
||||
|
||||
def iso(value):
|
||||
if value.tzinfo is None:
|
||||
value = value.replace(tzinfo=timezone.utc)
|
||||
return value.astimezone(timezone.utc).isoformat(timespec="microseconds").replace("+00:00", "Z")
|
||||
|
||||
|
||||
def user_json(row):
|
||||
return {
|
||||
"id": str(row["id"]),
|
||||
"username": row["username"],
|
||||
"display_name": row["display_name"],
|
||||
"created_at": iso(row["created_at"]),
|
||||
}
|
||||
|
||||
|
||||
def chat_json(row, member_ids):
|
||||
return {
|
||||
"id": str(row["id"]),
|
||||
"title": row["title"],
|
||||
"member_ids": member_ids,
|
||||
"created_at": iso(row["created_at"]),
|
||||
}
|
||||
|
||||
|
||||
def message_json(row):
|
||||
return {
|
||||
"id": str(row["id"]),
|
||||
"chat_id": str(row["chat_id"]),
|
||||
"sender_id": str(row["sender_id"]),
|
||||
"text": row["text"],
|
||||
"created_at": iso(row["created_at"]),
|
||||
}
|
||||
|
||||
|
||||
def encode_cursor(kind, scope, created_at, item_id):
|
||||
payload = {"k": kind, "s": scope, "t": created_at, "i": item_id}
|
||||
raw = json.dumps(payload, separators=(",", ":")).encode("utf-8")
|
||||
return base64.urlsafe_b64encode(raw).decode("ascii").rstrip("=")
|
||||
|
||||
|
||||
def decode_cursor(value, kind, scope):
|
||||
try:
|
||||
padded = value + "=" * (-len(value) % 4)
|
||||
data = json.loads(base64.urlsafe_b64decode(padded.encode("ascii")).decode("utf-8"))
|
||||
except Exception:
|
||||
raise invalid("Некорректный cursor")
|
||||
if not isinstance(data, dict) or data.get("k") != kind or data.get("s") != scope:
|
||||
raise invalid("Некорректный cursor")
|
||||
created_at = data.get("t")
|
||||
item_id = data.get("i")
|
||||
if not isinstance(created_at, str) or not isinstance(item_id, str):
|
||||
raise invalid("Некорректный cursor")
|
||||
try:
|
||||
uuid.UUID(item_id)
|
||||
datetime.fromisoformat(created_at.replace("Z", "+00:00"))
|
||||
except (ValueError, AttributeError):
|
||||
raise invalid("Некорректный cursor")
|
||||
return created_at, item_id
|
||||
@@ -0,0 +1,135 @@
|
||||
from .errors import invalid
|
||||
|
||||
|
||||
def create_user(cur, user_id, username, display_name, password_hash):
|
||||
cur.execute(
|
||||
"INSERT INTO users (id, username, display_name, password_hash) "
|
||||
"VALUES (%s, %s, %s, %s) RETURNING id, username, display_name, created_at",
|
||||
(user_id, username, display_name, password_hash),
|
||||
)
|
||||
return cur.fetchone()
|
||||
|
||||
|
||||
def get_user_by_username(cur, username):
|
||||
cur.execute(
|
||||
"SELECT id, username, display_name, password_hash, created_at FROM users WHERE username = %s",
|
||||
(username,),
|
||||
)
|
||||
return cur.fetchone()
|
||||
|
||||
|
||||
def get_user_by_id(cur, user_id):
|
||||
cur.execute(
|
||||
"SELECT id, username, display_name, created_at FROM users WHERE id = %s",
|
||||
(user_id,),
|
||||
)
|
||||
return cur.fetchone()
|
||||
|
||||
|
||||
def create_session(cur, fingerprint, user_id, expires_at):
|
||||
cur.execute(
|
||||
"INSERT INTO sessions (token_hash, user_id, expires_at) VALUES (%s, %s, %s)",
|
||||
(fingerprint, user_id, expires_at),
|
||||
)
|
||||
|
||||
|
||||
def get_valid_session(cur, fingerprint):
|
||||
cur.execute(
|
||||
"SELECT user_id, expires_at FROM sessions "
|
||||
"WHERE token_hash = %s AND revoked_at IS NULL AND expires_at > now()",
|
||||
(fingerprint,),
|
||||
)
|
||||
return cur.fetchone()
|
||||
|
||||
|
||||
def revoke_session(cur, fingerprint):
|
||||
cur.execute(
|
||||
"UPDATE sessions SET revoked_at = now() WHERE token_hash = %s AND revoked_at IS NULL",
|
||||
(fingerprint,),
|
||||
)
|
||||
return cur.rowcount
|
||||
|
||||
|
||||
def is_member(cur, chat_id, user_id):
|
||||
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 create_chat(cur, chat_id, title, member_ids):
|
||||
cur.execute(
|
||||
"SELECT id FROM users WHERE id = ANY(%s::uuid[])",
|
||||
(list(member_ids),),
|
||||
)
|
||||
found = {str(row["id"]) for row in cur.fetchall()}
|
||||
if found != set(member_ids):
|
||||
raise invalid("Неизвестные участники чата")
|
||||
cur.execute(
|
||||
"INSERT INTO chats (id, title) VALUES (%s, %s) 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, member) for member in member_ids],
|
||||
)
|
||||
return row
|
||||
|
||||
|
||||
def get_chat(cur, chat_id):
|
||||
cur.execute("SELECT id, title, created_at FROM chats WHERE id = %s", (chat_id,))
|
||||
return cur.fetchone()
|
||||
|
||||
|
||||
def chat_members(cur, chat_ids):
|
||||
if not chat_ids:
|
||||
return {}
|
||||
cur.execute(
|
||||
"SELECT chat_id, user_id FROM chat_members WHERE chat_id = ANY(%s::uuid[]) "
|
||||
"ORDER BY chat_id, user_id",
|
||||
(list(chat_ids),),
|
||||
)
|
||||
result = {}
|
||||
for row in cur.fetchall():
|
||||
result.setdefault(str(row["chat_id"]), []).append(str(row["user_id"]))
|
||||
return result
|
||||
|
||||
|
||||
def list_chats(cur, user_id, after, limit):
|
||||
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 = [user_id]
|
||||
if after is not None:
|
||||
sql += " AND (c.created_at, c.id) > (%s::timestamptz, %s::uuid)"
|
||||
params.extend([after[0], after[1]])
|
||||
sql += " ORDER BY c.created_at ASC, c.id ASC LIMIT %s"
|
||||
params.append(limit)
|
||||
cur.execute(sql, params)
|
||||
return cur.fetchall()
|
||||
|
||||
|
||||
def create_message(cur, message_id, chat_id, sender_id, text):
|
||||
cur.execute(
|
||||
"INSERT INTO messages (id, chat_id, sender_id, text) VALUES (%s, %s, %s, %s) "
|
||||
"RETURNING id, chat_id, sender_id, text, created_at",
|
||||
(message_id, chat_id, sender_id, text),
|
||||
)
|
||||
return cur.fetchone()
|
||||
|
||||
|
||||
def list_messages(cur, chat_id, after, limit):
|
||||
sql = (
|
||||
"SELECT id, chat_id, sender_id, text, created_at FROM messages WHERE chat_id = %s"
|
||||
)
|
||||
params = [chat_id]
|
||||
if after is not None:
|
||||
sql += " AND (created_at, id) > (%s::timestamptz, %s::uuid)"
|
||||
params.extend([after[0], after[1]])
|
||||
sql += " ORDER BY created_at ASC, id ASC LIMIT %s"
|
||||
params.append(limit)
|
||||
cur.execute(sql, params)
|
||||
return cur.fetchall()
|
||||
Reference in New Issue
Block a user