forked from mtusi2026/mtusi2026lab6
lab5_files
This commit is contained in:
@@ -0,0 +1,230 @@
|
||||
import hashlib
|
||||
import io
|
||||
import tempfile
|
||||
import uuid
|
||||
import json
|
||||
|
||||
from fastapi import APIRouter, Depends, Request, Query
|
||||
from fastapi.responses import StreamingResponse
|
||||
from psycopg.rows import dict_row
|
||||
|
||||
from ..db import transaction, connection
|
||||
from ..errors import ApiError
|
||||
from ..s3 import upload_fileobj, download_fileobj, delete_file
|
||||
from ..image_check import check_image
|
||||
from ..serializers import iso_z
|
||||
from .sessions import require_actor
|
||||
|
||||
router = APIRouter(prefix="/api/v1")
|
||||
MAX_SIZE = 10 * 1024 * 1024
|
||||
|
||||
@router.post("/chats/{chat_id}/attachments", status_code=202)
|
||||
async def upload_attachment(
|
||||
chat_id: str,
|
||||
request: Request,
|
||||
filename: str = Query(..., max_length=255),
|
||||
actor: dict = Depends(require_actor),
|
||||
):
|
||||
try:
|
||||
uuid.UUID(chat_id)
|
||||
except ValueError:
|
||||
raise ApiError(400, "invalid_request", "Неверный chat_id")
|
||||
|
||||
if "/" in filename or "\\" in filename or "\0" in filename:
|
||||
raise ApiError(400, "invalid_request", "Опасное имя файла")
|
||||
|
||||
with 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, actor["user_id"]),
|
||||
)
|
||||
if cur.fetchone() is None:
|
||||
raise ApiError(404, "not_found", "Чат не найден")
|
||||
|
||||
sha256 = hashlib.sha256()
|
||||
size = 0
|
||||
first_chunk = b""
|
||||
|
||||
with tempfile.SpooledTemporaryFile(max_size=MAX_SIZE, mode="w+b") as spooled:
|
||||
async for chunk in request.stream():
|
||||
size += len(chunk)
|
||||
if size > MAX_SIZE:
|
||||
raise ApiError(413, "payload_too_large", "Файл слишком большой")
|
||||
if not first_chunk:
|
||||
first_chunk = chunk[:16]
|
||||
sha256.update(chunk)
|
||||
spooled.write(chunk)
|
||||
|
||||
if size == 0:
|
||||
raise ApiError(400, "invalid_request", "Пустой файл")
|
||||
|
||||
try:
|
||||
content_type, _, _ = check_image(first_chunk, ["image/png", "image/jpeg"])
|
||||
except ValueError:
|
||||
raise ApiError(415, "unsupported_media_type", "Неподдерживаемый формат")
|
||||
|
||||
sha256_hex = sha256.hexdigest()
|
||||
object_key = f"chats/{chat_id}/{uuid.uuid4().hex}"
|
||||
|
||||
try:
|
||||
spooled.seek(0)
|
||||
upload_fileobj(spooled, object_key, content_type)
|
||||
except Exception as e:
|
||||
print(f"S3 error: {e}")
|
||||
raise ApiError(503, "unavailable", "S3 недоступен")
|
||||
|
||||
try:
|
||||
with transaction() as conn:
|
||||
with conn.cursor(row_factory=dict_row) as cur:
|
||||
# 1. Сохраняем вложение
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO attachments (chat_id, owner_id, filename, content_type, size_bytes, sha256, object_key, status)
|
||||
VALUES (%s, %s, %s, %s, %s, %s, %s, 'queued')
|
||||
RETURNING id, chat_id, owner_id, filename, content_type, size_bytes, sha256, status, created_at, updated_at
|
||||
""",
|
||||
(chat_id, actor["user_id"], filename, content_type, size, sha256_hex, object_key),
|
||||
)
|
||||
att = cur.fetchone()
|
||||
|
||||
# 2. Сохраняем задачу в Outbox в ТОЙ ЖЕ транзакции
|
||||
payload = {"attachment_id": str(att["id"]), "object_key": object_key}
|
||||
cur.execute(
|
||||
"INSERT INTO outbox_messages (attachment_id, payload) VALUES (%s, %s)",
|
||||
(att["id"], json.dumps(payload))
|
||||
)
|
||||
except Exception as e:
|
||||
print(f"DB failed, compensating S3: {e}")
|
||||
try:
|
||||
delete_file(object_key)
|
||||
except Exception as s3_e:
|
||||
print(f"Failed to compensate S3: {s3_e}")
|
||||
raise ApiError(500, "internal_error", "Ошибка сохранения")
|
||||
|
||||
return {
|
||||
"id": str(att["id"]),
|
||||
"chat_id": str(att["chat_id"]),
|
||||
"owner_id": str(att["owner_id"]),
|
||||
"filename": att["filename"],
|
||||
"content_type": att["content_type"],
|
||||
"size_bytes": att["size_bytes"],
|
||||
"sha256": att["sha256"],
|
||||
"status": att["status"],
|
||||
"variants": [],
|
||||
"error_code": None,
|
||||
"created_at": iso_z(att["created_at"]),
|
||||
"updated_at": iso_z(att["updated_at"]),
|
||||
}
|
||||
|
||||
|
||||
@router.get("/attachments/{attachment_id}")
|
||||
def get_attachment(attachment_id: str, actor: dict = Depends(require_actor)):
|
||||
try:
|
||||
uuid.UUID(attachment_id)
|
||||
except ValueError:
|
||||
raise ApiError(400, "invalid_request", "Неверный id")
|
||||
|
||||
with connection() as conn:
|
||||
with conn.cursor(row_factory=dict_row) as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT a.*
|
||||
FROM attachments a
|
||||
JOIN chat_members cm ON cm.chat_id = a.chat_id AND cm.user_id = %s
|
||||
WHERE a.id = %s
|
||||
""",
|
||||
(actor["user_id"], attachment_id),
|
||||
)
|
||||
att = cur.fetchone()
|
||||
|
||||
if att:
|
||||
cur.execute("SELECT * FROM attachment_variants WHERE attachment_id = %s", (attachment_id,))
|
||||
variants = cur.fetchall()
|
||||
else:
|
||||
variants = []
|
||||
|
||||
if att is None:
|
||||
raise ApiError(404, "not_found", "Вложение не найдено")
|
||||
|
||||
return {
|
||||
"id": str(att["id"]),
|
||||
"chat_id": str(att["chat_id"]),
|
||||
"owner_id": str(att["owner_id"]),
|
||||
"filename": att["filename"],
|
||||
"content_type": att["content_type"],
|
||||
"size_bytes": att["size_bytes"],
|
||||
"sha256": att["sha256"],
|
||||
"status": att["status"],
|
||||
"variants": [
|
||||
{
|
||||
"name": v["name"],
|
||||
"content_type": v["content_type"],
|
||||
"size_bytes": v["size_bytes"],
|
||||
"width": v["width"],
|
||||
"height": v["height"],
|
||||
"sha256": v["sha256"],
|
||||
} for v in variants
|
||||
],
|
||||
"error_code": att["error_code"],
|
||||
"created_at": iso_z(att["created_at"]),
|
||||
"updated_at": iso_z(att["updated_at"]),
|
||||
}
|
||||
|
||||
|
||||
@router.get("/attachments/{attachment_id}/content")
|
||||
def download_attachment(
|
||||
attachment_id: str,
|
||||
variant: str = Query("original", pattern="^(original|thumbnail|crop|optimized)$"),
|
||||
actor: dict = Depends(require_actor)
|
||||
):
|
||||
try:
|
||||
uuid.UUID(attachment_id)
|
||||
except ValueError:
|
||||
raise ApiError(400, "invalid_request", "Неверный id")
|
||||
|
||||
with connection() as conn:
|
||||
with conn.cursor(row_factory=dict_row) as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT a.object_key, a.content_type, a.filename, a.status
|
||||
FROM attachments a
|
||||
JOIN chat_members cm ON cm.chat_id = a.chat_id AND cm.user_id = %s
|
||||
WHERE a.id = %s
|
||||
""",
|
||||
(actor["user_id"], attachment_id),
|
||||
)
|
||||
att = cur.fetchone()
|
||||
|
||||
if att is None:
|
||||
raise ApiError(404, "not_found", "Вложение не найдено")
|
||||
|
||||
if variant == "original":
|
||||
if att["status"] == "failed":
|
||||
raise ApiError(409, "conflict", "Обработка вложения завершилась ошибкой")
|
||||
obj_key = att["object_key"]
|
||||
content_type = att["content_type"]
|
||||
else:
|
||||
cur.execute(
|
||||
"SELECT object_key, content_type FROM attachment_variants WHERE attachment_id = %s AND name = %s",
|
||||
(attachment_id, variant)
|
||||
)
|
||||
var = cur.fetchone()
|
||||
if not var:
|
||||
raise ApiError(404, "not_found", "Вариант еще не готов или недоступен")
|
||||
obj_key = var["object_key"]
|
||||
content_type = var["content_type"]
|
||||
|
||||
try:
|
||||
body = download_fileobj(obj_key)
|
||||
except Exception:
|
||||
raise ApiError(503, "unavailable", "S3 недоступен")
|
||||
|
||||
def iter_body():
|
||||
yield from body.iter_chunks(1024 * 1024)
|
||||
|
||||
return StreamingResponse(
|
||||
iter_body(),
|
||||
media_type=content_type,
|
||||
headers={"Content-Disposition": f'attachment; filename="{att["filename"]}"'},
|
||||
)
|
||||
@@ -0,0 +1,169 @@
|
||||
import base64
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
|
||||
import psycopg
|
||||
from fastapi import APIRouter, Depends, Query
|
||||
from pydantic import BaseModel, ConfigDict, Field, field_validator
|
||||
from psycopg.rows import dict_row
|
||||
|
||||
from ..db import connection, transaction
|
||||
from ..errors import ApiError
|
||||
from ..serializers import row_to_chat
|
||||
from .sessions import require_actor
|
||||
|
||||
router = APIRouter(prefix="/api/v1")
|
||||
|
||||
|
||||
class CreateChat(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
title: str = Field(min_length=1, max_length=100)
|
||||
member_ids: list[str] = Field(min_length=1, max_length=100)
|
||||
|
||||
@field_validator("title")
|
||||
@classmethod
|
||||
def title_not_blank(cls, v: str) -> str:
|
||||
if not v.strip():
|
||||
raise ValueError("title must not be blank")
|
||||
return v
|
||||
|
||||
@field_validator("member_ids")
|
||||
@classmethod
|
||||
def unique_members(cls, v: list[str]) -> list[str]:
|
||||
if len(set(v)) != len(v):
|
||||
raise ValueError("duplicate member_ids")
|
||||
for s in v:
|
||||
try:
|
||||
uuid.UUID(s)
|
||||
except ValueError:
|
||||
raise ValueError("invalid uuid in member_ids")
|
||||
return v
|
||||
|
||||
|
||||
def _encode_cursor(created_at: datetime, id_) -> str:
|
||||
raw = f"{created_at.isoformat()}|{id_}"
|
||||
return base64.urlsafe_b64encode(raw.encode("utf-8")).decode("ascii").rstrip("=")
|
||||
|
||||
|
||||
def _decode_cursor(cursor: str):
|
||||
pad = "=" * (-len(cursor) % 4)
|
||||
raw = base64.urlsafe_b64decode(cursor + pad).decode("utf-8")
|
||||
ts, id_ = raw.split("|", 1)
|
||||
return datetime.fromisoformat(ts), id_
|
||||
|
||||
|
||||
@router.post("/chats", status_code=201)
|
||||
def create_chat(body: CreateChat, actor: dict = Depends(require_actor)):
|
||||
me = actor["user_id"]
|
||||
if str(me) not in body.member_ids:
|
||||
raise ApiError(400, "invalid_request", "Вызывающий должен входить в member_ids")
|
||||
|
||||
try:
|
||||
with transaction() as conn:
|
||||
with conn.cursor(row_factory=dict_row) as cur:
|
||||
cur.execute(
|
||||
"SELECT id FROM users WHERE id = ANY(%s::uuid[])",
|
||||
(body.member_ids,),
|
||||
)
|
||||
found = {str(r["id"]) for r in cur.fetchall()}
|
||||
missing = set(body.member_ids) - found
|
||||
if missing:
|
||||
raise ApiError(400, "invalid_request", "Неизвестные участники")
|
||||
|
||||
cur.execute(
|
||||
"INSERT INTO chats (title) VALUES (%s) RETURNING id, title, created_at",
|
||||
(body.title,),
|
||||
)
|
||||
chat = cur.fetchone()
|
||||
|
||||
cur.executemany(
|
||||
"INSERT INTO chat_members (chat_id, user_id) VALUES (%s, %s)",
|
||||
[(chat["id"], m) for m in body.member_ids],
|
||||
)
|
||||
except ApiError:
|
||||
raise
|
||||
except psycopg.errors.ForeignKeyViolation:
|
||||
raise ApiError(400, "invalid_request", "Неизвестные участники")
|
||||
|
||||
chat["member_ids"] = body.member_ids
|
||||
return row_to_chat(chat)
|
||||
|
||||
|
||||
@router.get("/chats")
|
||||
def list_chats(
|
||||
limit: int = Query(default=50, ge=1, le=100),
|
||||
cursor: Optional[str] = Query(default=None),
|
||||
actor: dict = Depends(require_actor),
|
||||
):
|
||||
params: list = []
|
||||
where = ["cm.user_id = %s"]
|
||||
params.append(actor["user_id"])
|
||||
|
||||
if cursor:
|
||||
try:
|
||||
c_ts, c_id = _decode_cursor(cursor)
|
||||
except Exception:
|
||||
raise ApiError(400, "invalid_request", "Неверный cursor")
|
||||
where.append("(c.created_at, c.id) > (%s, %s)")
|
||||
params.extend([c_ts, c_id])
|
||||
|
||||
sql = f"""
|
||||
SELECT c.id, c.title, c.created_at,
|
||||
ARRAY(
|
||||
SELECT cm2.user_id::text
|
||||
FROM chat_members cm2
|
||||
WHERE cm2.chat_id = c.id
|
||||
ORDER BY cm2.user_id
|
||||
) AS member_ids
|
||||
FROM chats c
|
||||
JOIN chat_members cm ON cm.chat_id = c.id
|
||||
WHERE {' AND '.join(where)}
|
||||
ORDER BY c.created_at, c.id
|
||||
LIMIT %s
|
||||
"""
|
||||
params.append(limit + 1)
|
||||
|
||||
with connection() as conn:
|
||||
with conn.cursor(row_factory=dict_row) as cur:
|
||||
cur.execute(sql, params)
|
||||
rows = cur.fetchall()
|
||||
|
||||
next_cursor = None
|
||||
if len(rows) > limit:
|
||||
last = rows[limit - 1]
|
||||
next_cursor = _encode_cursor(last["created_at"], str(last["id"]))
|
||||
rows = rows[:limit]
|
||||
|
||||
return {"items": [row_to_chat(r) for r in rows], "next_cursor": next_cursor}
|
||||
|
||||
|
||||
@router.get("/chats/{chat_id}")
|
||||
def get_chat(chat_id: str, actor: dict = Depends(require_actor)):
|
||||
try:
|
||||
uuid.UUID(chat_id)
|
||||
except ValueError:
|
||||
raise ApiError(400, "invalid_request", "Неверный chat_id")
|
||||
|
||||
with connection() as conn:
|
||||
with conn.cursor(row_factory=dict_row) as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT c.id, c.title, c.created_at,
|
||||
ARRAY(
|
||||
SELECT cm2.user_id::text
|
||||
FROM chat_members cm2
|
||||
WHERE cm2.chat_id = c.id
|
||||
ORDER BY cm2.user_id
|
||||
) AS member_ids
|
||||
FROM chats c
|
||||
JOIN chat_members cm ON cm.chat_id = c.id
|
||||
WHERE c.id = %s AND cm.user_id = %s
|
||||
""",
|
||||
(chat_id, actor["user_id"]),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if row is None:
|
||||
raise ApiError(404, "not_found", "Чат не найден")
|
||||
return row_to_chat(row)
|
||||
@@ -0,0 +1,42 @@
|
||||
from fastapi import APIRouter, Request
|
||||
from fastapi.responses import JSONResponse
|
||||
import socket
|
||||
from urllib.parse import urlparse
|
||||
|
||||
from ..config import get_settings
|
||||
from ..db import connection
|
||||
from ..errors import error_response
|
||||
from ..s3 import get_s3_client
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@router.get("/health/live")
|
||||
def live():
|
||||
return {"status": "ok"}
|
||||
|
||||
@router.get("/health/ready")
|
||||
def ready(request: Request):
|
||||
try:
|
||||
|
||||
with connection() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute("SELECT 1")
|
||||
cur.fetchone()
|
||||
|
||||
|
||||
get_s3_client().head_bucket(Bucket=get_settings().s3_bucket)
|
||||
|
||||
# 3. Broker (простая проверка TCP-порта)
|
||||
settings = get_settings()
|
||||
parsed = urlparse(settings.broker_url)
|
||||
host = parsed.hostname or "broker"
|
||||
port = parsed.port or 5672
|
||||
with socket.create_connection((host, port), timeout=2):
|
||||
pass
|
||||
|
||||
except Exception as e:
|
||||
print(f"Readiness check failed: {e}")
|
||||
return error_response(
|
||||
request, 503, "unavailable", "Зависимость недоступна"
|
||||
)
|
||||
return {"status": "ok"}
|
||||
@@ -0,0 +1,171 @@
|
||||
import re
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, Header, Query
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
from psycopg.rows import dict_row
|
||||
|
||||
from ..db import connection
|
||||
from ..errors import ApiError
|
||||
from ..idempotency import run_idempotent
|
||||
from ..serializers import row_to_message
|
||||
from .sessions import require_actor
|
||||
|
||||
router = APIRouter(prefix="/api/v1")
|
||||
|
||||
KEY_RE = re.compile(r"^[A-Za-z0-9._:-]{1,128}$")
|
||||
|
||||
|
||||
class CreateMessage(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
text: str = Field(max_length=4000)
|
||||
attachment_ids: list[str] = Field(default_factory=list, max_length=10)
|
||||
|
||||
|
||||
def _check_chat_member(conn, chat_id: str, user_id: str) -> None:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"SELECT 1 FROM chat_members WHERE chat_id = %s AND user_id = %s",
|
||||
(chat_id, user_id),
|
||||
)
|
||||
if cur.fetchone() is None:
|
||||
raise ApiError(404, "not_found", "Чат не найден")
|
||||
|
||||
|
||||
def _encode_cursor(created_at: datetime, id_) -> str:
|
||||
import base64
|
||||
raw = f"{created_at.isoformat()}|{id_}"
|
||||
return base64.urlsafe_b64encode(raw.encode("utf-8")).decode("ascii").rstrip("=")
|
||||
|
||||
|
||||
def _decode_cursor(cursor: str):
|
||||
import base64
|
||||
pad = "=" * (-len(cursor) % 4)
|
||||
raw = base64.urlsafe_b64decode(cursor + pad).decode("utf-8")
|
||||
ts, id_ = raw.split("|", 1)
|
||||
return datetime.fromisoformat(ts), id_
|
||||
|
||||
|
||||
@router.post("/chats/{chat_id}/messages", status_code=201)
|
||||
def create_message(
|
||||
chat_id: str,
|
||||
body: CreateMessage,
|
||||
idempotency_key: str = Header(..., alias="Idempotency-Key"),
|
||||
actor: dict = Depends(require_actor),
|
||||
):
|
||||
try:
|
||||
uuid.UUID(chat_id)
|
||||
except ValueError:
|
||||
raise ApiError(400, "invalid_request", "Неверный chat_id")
|
||||
|
||||
if not KEY_RE.fullmatch(idempotency_key or ""):
|
||||
raise ApiError(400, "invalid_request", "Неверный Idempotency-Key")
|
||||
|
||||
if not body.text.strip() and not body.attachment_ids:
|
||||
raise ApiError(400, "invalid_request", "Нужен текст или вложение")
|
||||
|
||||
scope = f"POST /api/v1/chats/{chat_id}/messages"
|
||||
|
||||
def action(conn):
|
||||
_check_chat_member(conn, chat_id, actor["user_id"])
|
||||
with conn.cursor(row_factory=dict_row) as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO messages (chat_id, sender_id, text)
|
||||
VALUES (%s, %s, %s)
|
||||
RETURNING id, chat_id, sender_id, text, created_at
|
||||
""",
|
||||
(chat_id, actor["user_id"], body.text),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
|
||||
if body.attachment_ids:
|
||||
for att_id in body.attachment_ids:
|
||||
cur.execute(
|
||||
"SELECT 1 FROM attachments WHERE id = %s AND chat_id = %s",
|
||||
(att_id, chat_id),
|
||||
)
|
||||
if cur.fetchone() is None:
|
||||
raise ApiError(404, "not_found", "Вложение не найдено")
|
||||
|
||||
cur.executemany(
|
||||
"INSERT INTO message_attachments (message_id, attachment_id) VALUES (%s, %s)",
|
||||
[(row["id"], att_id) for att_id in body.attachment_ids]
|
||||
)
|
||||
|
||||
row["attachment_ids"] = body.attachment_ids
|
||||
|
||||
return 201, row_to_message(row)
|
||||
|
||||
_, payload = run_idempotent(
|
||||
user_id=actor["user_id"],
|
||||
scope=scope,
|
||||
key=idempotency_key,
|
||||
body=body.model_dump(),
|
||||
action=action,
|
||||
)
|
||||
return payload
|
||||
|
||||
|
||||
@router.get("/chats/{chat_id}/messages")
|
||||
def list_messages(
|
||||
chat_id: str,
|
||||
limit: int = Query(default=50, ge=1, le=100),
|
||||
cursor: Optional[str] = Query(default=None),
|
||||
actor: dict = Depends(require_actor),
|
||||
):
|
||||
try:
|
||||
uuid.UUID(chat_id)
|
||||
except ValueError:
|
||||
raise ApiError(400, "invalid_request", "Неверный chat_id")
|
||||
|
||||
with 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, actor["user_id"]),
|
||||
)
|
||||
if cur.fetchone() is None:
|
||||
raise ApiError(404, "not_found", "Чат не найден")
|
||||
|
||||
params: list = [chat_id]
|
||||
where = ["m.chat_id = %s"]
|
||||
if cursor:
|
||||
try:
|
||||
c_ts, c_id = _decode_cursor(cursor)
|
||||
except Exception:
|
||||
raise ApiError(400, "invalid_request", "Неверный cursor")
|
||||
where.append("(m.created_at, m.id) > (%s, %s)")
|
||||
params.extend([c_ts, c_id])
|
||||
|
||||
sql = f"""
|
||||
SELECT m.id, m.chat_id, m.sender_id, m.text, m.created_at,
|
||||
COALESCE(
|
||||
ARRAY(
|
||||
SELECT ma.attachment_id::text
|
||||
FROM message_attachments ma
|
||||
WHERE ma.message_id = m.id
|
||||
), ARRAY[]::text[]
|
||||
) AS attachment_ids
|
||||
FROM messages m
|
||||
WHERE {' AND '.join(where)}
|
||||
ORDER BY m.created_at, m.id
|
||||
LIMIT %s
|
||||
"""
|
||||
params.append(limit + 1)
|
||||
|
||||
with connection() as conn:
|
||||
with conn.cursor(row_factory=dict_row) as cur:
|
||||
cur.execute(sql, params)
|
||||
rows = cur.fetchall()
|
||||
|
||||
next_cursor = None
|
||||
if len(rows) > limit:
|
||||
last = rows[limit - 1]
|
||||
next_cursor = _encode_cursor(last["created_at"], str(last["id"]))
|
||||
rows = rows[:limit]
|
||||
|
||||
return {"items": [row_to_message(r) for r in rows], "next_cursor": next_cursor}
|
||||
@@ -0,0 +1,112 @@
|
||||
import base64
|
||||
import json
|
||||
import redis
|
||||
from fastapi import APIRouter, Depends, Request
|
||||
from fastapi.responses import Response
|
||||
from psycopg.rows import dict_row
|
||||
|
||||
from ..config import get_settings
|
||||
from ..db import connection
|
||||
from ..errors import ApiError
|
||||
from ..security import (
|
||||
new_session_token,
|
||||
session_expiry,
|
||||
token_digest,
|
||||
verify_password,
|
||||
)
|
||||
from ..serializers import row_to_user
|
||||
|
||||
router = APIRouter(prefix="/api/v1")
|
||||
|
||||
WWW_BASIC = 'Basic realm="messenger", charset="UTF-8"'
|
||||
WWW_BEARER = 'Bearer realm="messenger"'
|
||||
|
||||
# Подключение к Redis
|
||||
redis_client = redis.Redis.from_url(get_settings().redis_url, decode_responses=True)
|
||||
|
||||
def _parse_basic(header: str | None) -> tuple[str, str]:
|
||||
if not header or not header.lower().startswith("basic "):
|
||||
raise ApiError(401, "unauthorized", "Требуется Basic", {"WWW-Authenticate": WWW_BASIC})
|
||||
try:
|
||||
decoded = base64.b64decode(header[6:].strip(), validate=True).decode("utf-8")
|
||||
except Exception:
|
||||
raise ApiError(401, "unauthorized", "Неверные учётные данные", {"WWW-Authenticate": WWW_BASIC})
|
||||
|
||||
if ":" not in decoded:
|
||||
raise ApiError(401, "unauthorized", "Неверные учётные данные", {"WWW-Authenticate": WWW_BASIC})
|
||||
|
||||
username, password = decoded.split(":", 1)
|
||||
return username, password
|
||||
|
||||
@router.post("/auth/sessions", status_code=201)
|
||||
def create_session(request: Request):
|
||||
header = request.headers.get("Authorization")
|
||||
username, password = _parse_basic(header)
|
||||
|
||||
with connection() as conn:
|
||||
with conn.cursor(row_factory=dict_row) 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 or not verify_password(password, row["password_hash"]):
|
||||
raise ApiError(401, "unauthorized", "Неверные учётные данные", {"WWW-Authenticate": WWW_BASIC})
|
||||
|
||||
settings = get_settings()
|
||||
token = new_session_token()
|
||||
ttl = settings.session_ttl_seconds
|
||||
digest = token_digest(token)
|
||||
|
||||
# СОХРАНЯЕМ В REDIS
|
||||
redis_client.setex(f"session:{digest}", ttl, str(row["id"]))
|
||||
|
||||
return {
|
||||
"token": token,
|
||||
"token_type": "Bearer",
|
||||
"expires_at": session_expiry(ttl).isoformat().replace("+00:00", "Z"),
|
||||
"user": row_to_user(row),
|
||||
}
|
||||
|
||||
def _extract_bearer(request: Request) -> str:
|
||||
header = request.headers.get("Authorization")
|
||||
if not header or not header.lower().startswith("bearer "):
|
||||
raise ApiError(401, "unauthorized", "Требуется Bearer", {"WWW-Authenticate": WWW_BEARER})
|
||||
token = header[7:].strip()
|
||||
if not token:
|
||||
raise ApiError(401, "unauthorized", "Требуется Bearer", {"WWW-Authenticate": WWW_BEARER})
|
||||
return token
|
||||
|
||||
def require_actor(request: Request) -> dict:
|
||||
token = _extract_bearer(request)
|
||||
digest = token_digest(token)
|
||||
|
||||
# ЧИТАЕМ ИЗ REDIS
|
||||
user_id = redis_client.get(f"session:{digest}")
|
||||
if user_id is None:
|
||||
raise ApiError(401, "unauthorized", "Сессия недействительна или истекла", {"WWW-Authenticate": WWW_BEARER})
|
||||
|
||||
with connection() as conn:
|
||||
with conn.cursor(row_factory=dict_row) as cur:
|
||||
cur.execute(
|
||||
"SELECT id, username, display_name, created_at FROM users WHERE id = %s",
|
||||
(user_id,),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
|
||||
if row is None:
|
||||
raise ApiError(401, "unauthorized", "Пользователь не найден", {"WWW-Authenticate": WWW_BEARER})
|
||||
|
||||
return {
|
||||
"user": row_to_user(row),
|
||||
"user_id": user_id,
|
||||
"token_hash": digest,
|
||||
}
|
||||
|
||||
@router.delete("/auth/sessions/current", status_code=204)
|
||||
def revoke_session(request: Request, actor: dict = Depends(require_actor)):
|
||||
# УДАЛЯЕМ ИЗ REDIS
|
||||
redis_client.delete(f"session:{actor['token_hash']}")
|
||||
return Response(status_code=204)
|
||||
@@ -0,0 +1,52 @@
|
||||
from fastapi import APIRouter, Depends
|
||||
from pydantic import BaseModel, ConfigDict, Field, field_validator
|
||||
import psycopg
|
||||
|
||||
from ..db import transaction
|
||||
from ..errors import ApiError
|
||||
from ..security import hash_password
|
||||
from ..serializers import row_to_user
|
||||
from .sessions import require_actor
|
||||
|
||||
router = APIRouter(prefix="/api/v1")
|
||||
|
||||
|
||||
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)
|
||||
|
||||
@field_validator("display_name")
|
||||
@classmethod
|
||||
def not_blank(cls, v: str) -> str:
|
||||
if not v.strip():
|
||||
raise ValueError("display_name must not be blank")
|
||||
return v
|
||||
|
||||
|
||||
@router.post("/users", status_code=201)
|
||||
def create_user(body: CreateUser):
|
||||
pwd_hash = hash_password(body.password)
|
||||
try:
|
||||
with transaction() as conn:
|
||||
with conn.cursor(row_factory=psycopg.rows.dict_row) as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO users (username, display_name, password_hash)
|
||||
VALUES (%s, %s, %s)
|
||||
RETURNING id, username, display_name, created_at
|
||||
""",
|
||||
(body.username, body.display_name, pwd_hash),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
except psycopg.errors.UniqueViolation:
|
||||
raise ApiError(409, "conflict", "Имя пользователя занято")
|
||||
|
||||
return row_to_user(row)
|
||||
|
||||
|
||||
@router.get("/users/me")
|
||||
def current_user(actor: dict = Depends(require_actor)):
|
||||
return actor["user"]
|
||||
Reference in New Issue
Block a user