forked from mtusi2026/mtusi2026lab4
ЛР4 - БВТ2302 - Никитина - на 5
This commit is contained in:
+595
@@ -0,0 +1,595 @@
|
||||
#!/usr/bin/env python3
|
||||
import base64
|
||||
import datetime as dt
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import secrets
|
||||
import uuid
|
||||
import socket
|
||||
import io
|
||||
import asyncio
|
||||
from contextlib import asynccontextmanager
|
||||
from typing import List, Optional
|
||||
from src.s3_client import upload_file, download_file
|
||||
import boto3
|
||||
from botocore.client import Config
|
||||
import redis.asyncio as redis
|
||||
from fastapi import FastAPI, Request, Response, HTTPException, Header, Depends, Query
|
||||
from fastapi.responses import JSONResponse
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from psycopg_pool import AsyncConnectionPool
|
||||
from pydantic import BaseModel, Field, ConfigDict
|
||||
from PIL import Image
|
||||
|
||||
# Configuration & S3 Setup
|
||||
DATABASE_URL = os.environ.get("DATABASE_URL", "postgresql://messenger:messenger@db:5432/messenger")
|
||||
REDIS_URL = os.environ.get("REDIS_URL", "redis://redis:6379/0")
|
||||
SESSION_TTL = int(os.environ.get("SESSION_TTL_SECONDS", "3600"))
|
||||
|
||||
S3_ENDPOINT = os.environ.get("S3_ENDPOINT", "http://minio:9000")
|
||||
S3_ACCESS_KEY = os.environ.get("S3_ACCESS_KEY", "minioadmin")
|
||||
S3_SECRET_KEY = os.environ.get("S3_SECRET_KEY", "minioadmin")
|
||||
S3_BUCKET = os.environ.get("S3_BUCKET", "attachments")
|
||||
|
||||
s3_client = boto3.client(
|
||||
"s3",
|
||||
endpoint_url=S3_ENDPOINT,
|
||||
aws_access_key_id=S3_ACCESS_KEY,
|
||||
aws_secret_access_key=S3_SECRET_KEY,
|
||||
config=Config(signature_version="s3v4"),
|
||||
region_name="us-east-1"
|
||||
)
|
||||
|
||||
MAX_FILE_SIZE = 10 * 1024 * 1024 # 10 MiB
|
||||
MAX_PIXELS = 40_000_000
|
||||
|
||||
# Global state
|
||||
pool: Optional[AsyncConnectionPool] = None
|
||||
redis_client: Optional[redis.Redis] = None
|
||||
|
||||
|
||||
# Pydantic Models
|
||||
class UserCreate(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 UserOut(BaseModel):
|
||||
id: str
|
||||
username: str
|
||||
display_name: str
|
||||
created_at: str
|
||||
|
||||
class ChatCreate(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)
|
||||
|
||||
class ChatOut(BaseModel):
|
||||
id: str
|
||||
title: str
|
||||
member_ids: List[str]
|
||||
created_at: str
|
||||
|
||||
class MessageCreate(BaseModel):
|
||||
model_config = ConfigDict(extra='forbid')
|
||||
text: str = Field(..., max_length=4000)
|
||||
attachment_ids: List[str] = Field(default_factory=list, max_length=10)
|
||||
|
||||
class MessageOut(BaseModel):
|
||||
id: str
|
||||
chat_id: str
|
||||
sender_id: str
|
||||
text: str
|
||||
created_at: str
|
||||
attachment_ids: List[str] = []
|
||||
|
||||
class PageResponse(BaseModel):
|
||||
items: List[dict]
|
||||
next_cursor: Optional[str]
|
||||
|
||||
class SessionResponse(BaseModel):
|
||||
token: str
|
||||
token_type: str = "Bearer"
|
||||
expires_at: str
|
||||
user: UserOut
|
||||
|
||||
|
||||
# Helpers
|
||||
def hash_password(password: str) -> str:
|
||||
salt = secrets.token_bytes(16)
|
||||
key = hashlib.scrypt(password.encode('utf-8'), salt=salt, n=16384, r=8, p=1, dklen=64)
|
||||
return f"{salt.hex()}${key.hex()}"
|
||||
|
||||
def verify_password(password: str, stored: str) -> bool:
|
||||
try:
|
||||
salt_hex, key_hex = stored.split("$")
|
||||
salt = bytes.fromhex(salt_hex)
|
||||
expected_key = bytes.fromhex(key_hex)
|
||||
actual_key = hashlib.scrypt(password.encode('utf-8'), salt=salt, n=16384, r=8, p=1, dklen=64)
|
||||
return secrets.compare_digest(actual_key, expected_key)
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
def generate_token() -> str:
|
||||
return secrets.token_urlsafe(48)
|
||||
|
||||
def encode_cursor(scope: str, created_at: str) -> str:
|
||||
payload = json.dumps({"s": scope, "t": created_at}, separators=(",", ":"))
|
||||
return base64.urlsafe_b64encode(payload.encode("utf-8")).decode("ascii").rstrip("=")
|
||||
|
||||
def decode_cursor(cursor: str, expected_scope: str) -> Optional[str]:
|
||||
try:
|
||||
pad = "=" * (-len(cursor) % 4)
|
||||
data = json.loads(base64.urlsafe_b64decode(cursor + pad))
|
||||
if data.get("s") == expected_scope and isinstance(data.get("t"), str):
|
||||
return data["t"]
|
||||
except Exception:
|
||||
pass
|
||||
return None
|
||||
|
||||
def validate_image(data: bytes, content_type: str) -> str:
|
||||
if len(data) > MAX_FILE_SIZE:
|
||||
raise HTTPException(413, "File too large")
|
||||
try:
|
||||
img = Image.open(io.BytesIO(data))
|
||||
img.verify()
|
||||
except Exception:
|
||||
raise HTTPException(415, "Invalid image file")
|
||||
if img.format not in ("PNG", "JPEG"):
|
||||
raise HTTPException(415, "Only PNG and JPEG are supported")
|
||||
if img.width * img.height > MAX_PIXELS:
|
||||
raise HTTPException(413, "Image has too many pixels")
|
||||
return "image/png" if img.format == "PNG" else "image/jpeg"
|
||||
|
||||
|
||||
# FastAPI Lifespan
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
global pool, redis_client
|
||||
pool = AsyncConnectionPool(DATABASE_URL, min_size=5, max_size=50, open=False)
|
||||
await pool.open()
|
||||
redis_client = redis.from_url(REDIS_URL, decode_responses=True)
|
||||
|
||||
async with pool.connection() as conn:
|
||||
await conn.execute("SELECT 1")
|
||||
await redis_client.ping()
|
||||
|
||||
try:
|
||||
await asyncio.to_thread(s3_client.head_bucket, Bucket=S3_BUCKET)
|
||||
except Exception:
|
||||
try:
|
||||
await asyncio.to_thread(s3_client.create_bucket, Bucket=S3_BUCKET)
|
||||
except Exception as e:
|
||||
print(f"Warning: Could not create S3 bucket: {e}")
|
||||
|
||||
yield
|
||||
|
||||
await pool.close()
|
||||
await redis_client.aclose()
|
||||
|
||||
app = FastAPI(lifespan=lifespan)
|
||||
|
||||
|
||||
# Middleware & Error Handling
|
||||
@app.middleware("http")
|
||||
async def add_instance_id(request: Request, call_next):
|
||||
response = await call_next(request)
|
||||
response.headers["X-Instance-Id"] = os.environ.get("HOSTNAME", socket.gethostname())
|
||||
return response
|
||||
|
||||
@app.middleware("http")
|
||||
async def add_request_id(request: Request, call_next):
|
||||
request.state.request_id = uuid.uuid4().hex
|
||||
response = await call_next(request)
|
||||
response.headers["X-Request-Id"] = request.state.request_id
|
||||
return response
|
||||
|
||||
@app.exception_handler(HTTPException)
|
||||
async def custom_http_exception_handler(request: Request, exc: HTTPException):
|
||||
code_map = {
|
||||
400: "invalid_request", 401: "unauthorized", 404: "not_found",
|
||||
409: "conflict", 413: "payload_too_large", 415: "unsupported_media_type",
|
||||
503: "unavailable", 500: "internal_error"
|
||||
}
|
||||
error_code = code_map.get(exc.status_code, "internal_error")
|
||||
payload = {
|
||||
"error": {
|
||||
"code": error_code,
|
||||
"message": str(exc.detail),
|
||||
"request_id": getattr(request.state, "request_id", "unknown")
|
||||
}
|
||||
}
|
||||
headers = {}
|
||||
if exc.status_code == 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=exc.status_code, content=payload, headers=headers)
|
||||
|
||||
@app.exception_handler(RequestValidationError)
|
||||
async def validation_exception_handler(request: Request, exc: RequestValidationError):
|
||||
payload = {
|
||||
"error": {
|
||||
"code": "invalid_request",
|
||||
"message": "Invalid request parameters",
|
||||
"request_id": getattr(request.state, "request_id", "unknown")
|
||||
}
|
||||
}
|
||||
return JSONResponse(status_code=400, content=payload)
|
||||
|
||||
|
||||
# Dependencies
|
||||
async def get_current_user(request: Request, authorization: Optional[str] = Header(None)) -> dict:
|
||||
if not authorization or not authorization.startswith("Bearer "):
|
||||
raise HTTPException(401, "Missing or invalid Authorization header")
|
||||
token = authorization[7:]
|
||||
user_id = await redis_client.get(f"session:{token}")
|
||||
if not user_id:
|
||||
raise HTTPException(401, "Session expired or invalid")
|
||||
|
||||
async with pool.connection() as conn:
|
||||
async with conn.cursor() as cur:
|
||||
await cur.execute(
|
||||
"SELECT id::text, username, display_name, to_char(created_at, 'YYYY-MM-DD\"T\"HH24:MI:SS.US\"Z\"') FROM users WHERE id = %s",
|
||||
(user_id,)
|
||||
)
|
||||
row = await cur.fetchone()
|
||||
if not row:
|
||||
raise HTTPException(401, "User no longer exists")
|
||||
return {"id": row[0], "username": row[1], "display_name": row[2], "created_at": row[3]}
|
||||
|
||||
# Health Endpoints
|
||||
@app.get("/health/live")
|
||||
async def health_live():
|
||||
return {"status": "ok"}
|
||||
|
||||
@app.get("/health/ready")
|
||||
async def health_ready():
|
||||
try:
|
||||
async with pool.connection() as conn:
|
||||
await conn.execute("SELECT 1")
|
||||
await redis_client.ping()
|
||||
return {"status": "ok"}
|
||||
except Exception:
|
||||
raise HTTPException(503, "Dependencies unavailable")
|
||||
|
||||
# Auth & Users
|
||||
@app.post("/api/v1/users", status_code=201, response_model=UserOut)
|
||||
async def create_user(body: UserCreate):
|
||||
pwd_hash = hash_password(body.password)
|
||||
async with pool.connection() as conn:
|
||||
try:
|
||||
async with conn.cursor() as cur:
|
||||
await cur.execute(
|
||||
"INSERT INTO users (username, display_name, password_hash) VALUES (%s, %s, %s) RETURNING id::text, username, display_name, to_char(created_at, 'YYYY-MM-DD\"T\"HH24:MI:SS.US\"Z\"')",
|
||||
(body.username, body.display_name, pwd_hash)
|
||||
)
|
||||
row = await cur.fetchone()
|
||||
await conn.commit()
|
||||
return {"id": row[0], "username": row[1], "display_name": row[2], "created_at": row[3]}
|
||||
except Exception as e:
|
||||
await conn.rollback()
|
||||
if "unique" in str(e).lower():
|
||||
raise HTTPException(409, "Username already taken")
|
||||
raise HTTPException(400, "Invalid user data")
|
||||
|
||||
@app.post("/api/v1/auth/sessions", status_code=201, response_model=SessionResponse)
|
||||
async def login(authorization: Optional[str] = Header(None)):
|
||||
if not authorization or not authorization.startswith("Basic "):
|
||||
raise HTTPException(401, "Basic authentication required")
|
||||
try:
|
||||
creds = base64.b64decode(authorization[6:]).decode('utf-8').split(":", 1)
|
||||
username, password = creds
|
||||
except Exception:
|
||||
raise HTTPException(401, "Invalid credentials")
|
||||
|
||||
async with pool.connection() as conn:
|
||||
async with conn.cursor() as cur:
|
||||
await cur.execute("SELECT id::text, password_hash, username, display_name, to_char(created_at, 'YYYY-MM-DD\"T\"HH24:MI:SS.US\"Z\"') FROM users WHERE username = %s", (username,))
|
||||
row = await cur.fetchone()
|
||||
|
||||
if not row or not verify_password(password, row[1]):
|
||||
raise HTTPException(401, "Invalid credentials")
|
||||
|
||||
token = generate_token()
|
||||
await redis_client.setex(f"session:{token}", SESSION_TTL, row[0])
|
||||
expires = (dt.datetime.now(dt.timezone.utc) + dt.timedelta(seconds=SESSION_TTL)).strftime("%Y-%m-%dT%H:%M:%S.%fZ")
|
||||
return {
|
||||
"token": token, "token_type": "Bearer", "expires_at": expires,
|
||||
"user": {"id": row[0], "username": row[2], "display_name": row[3], "created_at": row[4]}
|
||||
}
|
||||
|
||||
@app.delete("/api/v1/auth/sessions/current", status_code=204)
|
||||
async def logout(authorization: Optional[str] = Header(None)):
|
||||
if not authorization or not authorization.startswith("Bearer "):
|
||||
raise HTTPException(401, "Missing Authorization header")
|
||||
token = authorization[7:]
|
||||
deleted = await redis_client.delete(f"session:{token}")
|
||||
if not deleted:
|
||||
raise HTTPException(401, "Session invalid or already logged out")
|
||||
return Response(status_code=204)
|
||||
|
||||
@app.get("/api/v1/users/me", response_model=UserOut)
|
||||
async def get_me(user: dict = Depends(get_current_user)):
|
||||
return user
|
||||
|
||||
# Chats
|
||||
@app.post("/api/v1/chats", status_code=201, response_model=ChatOut)
|
||||
async def create_chat(body: ChatCreate, user: dict = Depends(get_current_user)):
|
||||
if user["id"] not in body.member_ids:
|
||||
raise HTTPException(400, "Caller must be a member of the chat")
|
||||
unique_members = list(set(body.member_ids))
|
||||
if len(unique_members) != len(body.member_ids):
|
||||
raise HTTPException(400, "Duplicate member IDs")
|
||||
|
||||
async with pool.connection() as conn:
|
||||
try:
|
||||
async with conn.transaction():
|
||||
async with conn.cursor() as cur:
|
||||
await cur.execute("SELECT id::text FROM users WHERE id = ANY(%s::uuid[])", (unique_members,))
|
||||
found_users = {r[0] for r in await cur.fetchall()}
|
||||
if len(found_users) != len(unique_members):
|
||||
raise HTTPException(400, "One or more members do not exist")
|
||||
|
||||
await cur.execute("INSERT INTO chats (title) VALUES (%s) RETURNING id::text, title, to_char(created_at, 'YYYY-MM-DD\"T\"HH24:MI:SS.US\"Z\"')", (body.title,))
|
||||
chat_row = await cur.fetchone()
|
||||
chat_id = chat_row[0]
|
||||
|
||||
for uid in unique_members:
|
||||
await cur.execute("INSERT INTO chat_members (chat_id, user_id) VALUES (%s, %s)", (chat_id, uid))
|
||||
return {"id": chat_id, "title": chat_row[1], "member_ids": unique_members, "created_at": chat_row[2]}
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception:
|
||||
raise HTTPException(500, "Failed to create chat")
|
||||
|
||||
@app.get("/api/v1/chats")
|
||||
async def list_chats(limit: int = 50, cursor: Optional[str] = None, user: dict = Depends(get_current_user)):
|
||||
if not (1 <= limit <= 100):
|
||||
raise HTTPException(400, "Invalid limit")
|
||||
cursor_ts = decode_cursor(cursor, "chats") if cursor else None
|
||||
if cursor and not cursor_ts:
|
||||
raise HTTPException(400, "Invalid cursor")
|
||||
|
||||
async with pool.connection() as conn:
|
||||
async with conn.cursor() as cur:
|
||||
if cursor_ts:
|
||||
await cur.execute("SELECT c.id::text, c.title, to_char(c.created_at, 'YYYY-MM-DD\"T\"HH24:MI:SS.US\"Z\"') FROM chats c JOIN chat_members cm ON c.id = cm.chat_id WHERE cm.user_id = %s AND c.created_at > %s ORDER BY c.created_at ASC LIMIT %s", (user["id"], cursor_ts, limit + 1))
|
||||
else:
|
||||
await cur.execute("SELECT c.id::text, c.title, to_char(c.created_at, 'YYYY-MM-DD\"T\"HH24:MI:SS.US\"Z\"') FROM chats c JOIN chat_members cm ON c.id = cm.chat_id WHERE cm.user_id = %s ORDER BY c.created_at ASC LIMIT %s", (user["id"], limit + 1))
|
||||
rows = await cur.fetchall()
|
||||
|
||||
chat_ids = [r[0] for r in rows[:limit]]
|
||||
members_map = {}
|
||||
if chat_ids:
|
||||
await cur.execute("SELECT chat_id::text, user_id::text FROM chat_members WHERE chat_id = ANY(%s::uuid[])", (chat_ids,))
|
||||
for cid, uid in await cur.fetchall():
|
||||
members_map.setdefault(cid, []).append(uid)
|
||||
|
||||
items = [{"id": r[0], "title": r[1], "created_at": r[2], "member_ids": members_map.get(r[0], [])} for r in rows[:limit]]
|
||||
next_cursor = encode_cursor("chats", items[-1]["created_at"]) if len(rows) > limit else None
|
||||
return {"items": items, "next_cursor": next_cursor}
|
||||
|
||||
@app.get("/api/v1/chats/{chat_id}")
|
||||
async def get_chat(chat_id: str, user: dict = Depends(get_current_user)):
|
||||
async with pool.connection() as conn:
|
||||
async with conn.cursor() as cur:
|
||||
await cur.execute("SELECT 1 FROM chat_members WHERE chat_id = %s AND user_id = %s", (chat_id, user["id"]))
|
||||
if not await cur.fetchone():
|
||||
raise HTTPException(404, "Chat not found")
|
||||
await cur.execute("SELECT id::text, title, to_char(created_at, 'YYYY-MM-DD\"T\"HH24:MI:SS.US\"Z\"') FROM chats WHERE id = %s", (chat_id,))
|
||||
chat = await cur.fetchone()
|
||||
await cur.execute("SELECT user_id::text FROM chat_members WHERE chat_id = %s", (chat_id,))
|
||||
members = [r[0] for r in await cur.fetchall()]
|
||||
return {"id": chat[0], "title": chat[1], "created_at": chat[2], "member_ids": members}
|
||||
|
||||
|
||||
# Attachments (Lab 4)
|
||||
@app.post("/api/v1/chats/{chat_id}/attachments", status_code=201)
|
||||
async def upload_attachment(
|
||||
chat_id: str,
|
||||
request: Request,
|
||||
filename: str = Query(..., min_length=1, max_length=255),
|
||||
user: dict = Depends(get_current_user)
|
||||
):
|
||||
async with pool.connection() as conn:
|
||||
async with conn.cursor() as cur:
|
||||
await cur.execute("SELECT 1 FROM chat_members WHERE chat_id = %s AND user_id = %s", (chat_id, user["id"]))
|
||||
if not await cur.fetchone():
|
||||
raise HTTPException(404, "Chat not found")
|
||||
|
||||
data = await request.body()
|
||||
if len(data) == 0:
|
||||
raise HTTPException(400, "Empty file")
|
||||
|
||||
content_type_header = request.headers.get("content-type", "")
|
||||
real_content_type = validate_image(data, content_type_header)
|
||||
|
||||
sha256 = hashlib.sha256(data).hexdigest()
|
||||
file_id = str(uuid.uuid4())
|
||||
ext = "png" if real_content_type == "image/png" else "jpg"
|
||||
s3_key = f"{chat_id}/{file_id}.{ext}"
|
||||
|
||||
upload_file(s3_key, data, real_content_type)
|
||||
|
||||
async with pool.connection() as conn:
|
||||
async with conn.cursor() as cur:
|
||||
await cur.execute(
|
||||
"INSERT INTO attachments (id, chat_id, owner_id, filename, content_type, size_bytes, sha256, s3_key) "
|
||||
"VALUES (%s, %s, %s, %s, %s, %s, %s, %s) RETURNING id::text, filename, content_type, size_bytes, sha256, status, to_char(created_at, 'YYYY-MM-DD\"T\"HH24:MI:SS.US\"Z\"'), to_char(updated_at, 'YYYY-MM-DD\"T\"HH24:MI:SS.US\"Z\"')",
|
||||
(file_id, chat_id, user["id"], filename, real_content_type, len(data), sha256, s3_key)
|
||||
)
|
||||
row = await cur.fetchone()
|
||||
await conn.commit()
|
||||
|
||||
return {
|
||||
"id": row[0], "chat_id": chat_id, "owner_id": user["id"], "filename": row[1],
|
||||
"content_type": row[2], "size_bytes": row[3], "sha256": row[4],
|
||||
"status": row[5], "created_at": row[6], "updated_at": row[7],
|
||||
"error_code": None, "variants": []
|
||||
}
|
||||
|
||||
@app.get("/api/v1/attachments/{attachment_id}")
|
||||
async def get_attachment_meta(attachment_id: str, user: dict = Depends(get_current_user)):
|
||||
async with pool.connection() as conn:
|
||||
async with conn.cursor() as cur:
|
||||
await cur.execute(
|
||||
"SELECT a.id::text, a.chat_id::text, a.owner_id::text, a.filename, a.content_type, a.size_bytes, a.sha256, a.status, to_char(a.created_at, 'YYYY-MM-DD\"T\"HH24:MI:SS.US\"Z\"'), to_char(a.updated_at, 'YYYY-MM-DD\"T\"HH24:MI:SS.US\"Z\"') "
|
||||
"FROM attachments a JOIN chat_members cm ON a.chat_id = cm.chat_id "
|
||||
"WHERE a.id = %s AND cm.user_id = %s",
|
||||
(attachment_id, user["id"])
|
||||
)
|
||||
row = await cur.fetchone()
|
||||
if not row:
|
||||
raise HTTPException(404, "Attachment not found")
|
||||
return {
|
||||
"id": row[0], "chat_id": row[1], "owner_id": row[2], "filename": row[3],
|
||||
"content_type": row[4], "size_bytes": row[5], "sha256": row[6],
|
||||
"status": row[7], "created_at": row[8], "updated_at": row[9],
|
||||
"error_code": None, "variants": []
|
||||
}
|
||||
|
||||
@app.get("/api/v1/attachments/{attachment_id}/content")
|
||||
async def download_attachment(attachment_id: str, user: dict = Depends(get_current_user)):
|
||||
async with pool.connection() as conn:
|
||||
async with conn.cursor() as cur:
|
||||
await cur.execute(
|
||||
"SELECT a.s3_key, a.content_type, a.filename FROM attachments a "
|
||||
"JOIN chat_members cm ON a.chat_id = cm.chat_id "
|
||||
"WHERE a.id = %s AND cm.user_id = %s",
|
||||
(attachment_id, user["id"])
|
||||
)
|
||||
row = await cur.fetchone()
|
||||
if not row:
|
||||
raise HTTPException(404, "Attachment not found")
|
||||
|
||||
s3_key, content_type, filename = row
|
||||
try:
|
||||
s3_response = await asyncio.to_thread(s3_client.get_object, Bucket=S3_BUCKET, Key=s3_key)
|
||||
data = await asyncio.to_thread(s3_response['Body'].read)
|
||||
except Exception:
|
||||
raise HTTPException(404, "File content missing in S3")
|
||||
|
||||
return Response(
|
||||
content=data,
|
||||
media_type=content_type,
|
||||
headers={"Content-Disposition": f'attachment; filename="{filename}"'}
|
||||
)
|
||||
|
||||
# Messages
|
||||
@app.post("/api/v1/chats/{chat_id}/messages", status_code=201, response_model=MessageOut)
|
||||
async def create_message(
|
||||
chat_id: str,
|
||||
body: MessageCreate,
|
||||
user: dict = Depends(get_current_user),
|
||||
idempotency_key: str = Header(None, alias="Idempotency-Key")
|
||||
):
|
||||
if not idempotency_key:
|
||||
raise HTTPException(400, "Idempotency-Key is required")
|
||||
|
||||
# Валидация: либо текст, либо вложения
|
||||
if not body.text.strip() and not body.attachment_ids:
|
||||
raise HTTPException(400, "Message must have either text or attachments")
|
||||
|
||||
req_hash = hashlib.sha256(body.text.encode('utf-8')).hexdigest()
|
||||
new_msg_id = str(uuid.uuid4())
|
||||
attachments = body.attachment_ids if hasattr(body, 'attachment_ids') and body.attachment_ids else []
|
||||
|
||||
async with pool.connection() as conn:
|
||||
async with conn.transaction():
|
||||
async with conn.cursor() as cur:
|
||||
# 1. Проверяем доступ к чату
|
||||
await cur.execute("SELECT 1 FROM chat_members WHERE chat_id = %s AND user_id = %s", (chat_id, user["id"]))
|
||||
if not await cur.fetchone():
|
||||
raise HTTPException(404, "Chat not found")
|
||||
|
||||
# 2. ПРОВЕРКА: Существуют ли эти вложения и принадлежат ли они ЭТОМУ чату?
|
||||
if attachments:
|
||||
# Передаем список строк в PostgreSQL как массив UUID
|
||||
await cur.execute(
|
||||
"SELECT id::text FROM attachments WHERE id = ANY(%s::uuid[]) AND chat_id = %s",
|
||||
(attachments, chat_id)
|
||||
)
|
||||
found_attachments = {row[0] for row in await cur.fetchall()}
|
||||
|
||||
# Если найдено меньше, чем передано — значит есть чужие или фейковые ID
|
||||
if len(found_attachments) != len(attachments):
|
||||
raise HTTPException(404, "One or more attachments not found or belong to another chat")
|
||||
|
||||
# 3. Проверка идемпотентности
|
||||
await cur.execute(
|
||||
"INSERT INTO idempotency_keys (key, user_id, request_hash, message_id) "
|
||||
"VALUES (%s, %s, %s, %s) ON CONFLICT DO NOTHING",
|
||||
(idempotency_key, user["id"], req_hash, new_msg_id)
|
||||
)
|
||||
|
||||
if cur.rowcount == 1:
|
||||
# 4. Вставляем сообщение
|
||||
await cur.execute(
|
||||
"INSERT INTO messages (id, chat_id, sender_id, text, attachment_ids) "
|
||||
"VALUES (%s, %s, %s, %s, %s) "
|
||||
"RETURNING id::text, chat_id::text, sender_id::text, text, attachment_ids::text[], to_char(created_at, 'YYYY-MM-DD\"T\"HH24:MI:SS.US\"Z\"')",
|
||||
(new_msg_id, chat_id, user["id"], body.text, attachments)
|
||||
)
|
||||
row = await cur.fetchone()
|
||||
return {"id": row[0], "chat_id": row[1], "sender_id": row[2], "text": row[3], "attachment_ids": row[4] or [], "created_at": row[5]}
|
||||
else:
|
||||
# 5. Возврат кэшированного ответа при дубле
|
||||
await cur.execute(
|
||||
"SELECT request_hash, message_id FROM idempotency_keys WHERE key = %s AND user_id = %s",
|
||||
(idempotency_key, user["id"])
|
||||
)
|
||||
key_row = await cur.fetchone()
|
||||
if key_row[0] != req_hash:
|
||||
raise HTTPException(409, "Idempotency key reused with different body")
|
||||
|
||||
await cur.execute(
|
||||
"SELECT id::text, chat_id::text, sender_id::text, text, attachment_ids::text[], to_char(created_at, 'YYYY-MM-DD\"T\"HH24:MI:SS.US\"Z\"') "
|
||||
"FROM messages WHERE id = %s",
|
||||
(key_row[1],)
|
||||
)
|
||||
row = await cur.fetchone()
|
||||
return {"id": row[0], "chat_id": row[1], "sender_id": row[2], "text": row[3], "attachment_ids": row[4] or [], "created_at": row[5]}
|
||||
|
||||
|
||||
@app.get("/api/v1/chats/{chat_id}/messages", response_model=PageResponse)
|
||||
async def list_messages(chat_id: str, limit: int = 50, cursor: Optional[str] = None, user: dict = Depends(get_current_user)):
|
||||
if not (1 <= limit <= 100):
|
||||
raise HTTPException(400, "Invalid limit")
|
||||
|
||||
scope = f"chat:{chat_id}"
|
||||
cursor_ts = decode_cursor(cursor, scope) if cursor else None
|
||||
if cursor and not cursor_ts:
|
||||
raise HTTPException(400, "Invalid cursor")
|
||||
|
||||
async with pool.connection() as conn:
|
||||
async with conn.cursor() as cur:
|
||||
await cur.execute("SELECT 1 FROM chat_members WHERE chat_id = %s AND user_id = %s", (chat_id, user["id"]))
|
||||
if not await cur.fetchone():
|
||||
raise HTTPException(404, "Chat not found")
|
||||
|
||||
query = "SELECT id::text, chat_id::text, sender_id::text, text, attachment_ids::text[], to_char(created_at, 'YYYY-MM-DD\"T\"HH24:MI:SS.US\"Z\"') FROM messages WHERE chat_id = %s "
|
||||
params = [chat_id]
|
||||
if cursor_ts:
|
||||
query += "AND created_at > %s "
|
||||
params.append(cursor_ts)
|
||||
query += "ORDER BY created_at ASC LIMIT %s"
|
||||
params.append(limit + 1)
|
||||
|
||||
await cur.execute(query, tuple(params))
|
||||
rows = await cur.fetchall()
|
||||
|
||||
items = []
|
||||
for r in rows[:limit]:
|
||||
items.append({
|
||||
"id": r[0], "chat_id": r[1], "sender_id": r[2], "text": r[3],
|
||||
"attachment_ids": r[4] or [],
|
||||
"created_at": r[5]
|
||||
})
|
||||
|
||||
next_cursor = encode_cursor(scope, items[-1]["created_at"]) if len(rows) > limit else None
|
||||
return {"items": items, "next_cursor": next_cursor}
|
||||
@@ -0,0 +1,34 @@
|
||||
import boto3
|
||||
import os
|
||||
from botocore.client import Config
|
||||
|
||||
S3_ENDPOINT = os.getenv("S3_ENDPOINT", "http://minio:9000")
|
||||
S3_ACCESS_KEY = os.getenv("S3_ACCESS_KEY")
|
||||
S3_SECRET_KEY = os.getenv("S3_SECRET_KEY")
|
||||
S3_BUCKET = os.getenv("S3_BUCKET", "attachments")
|
||||
|
||||
s3 = boto3.client(
|
||||
"s3",
|
||||
endpoint_url=S3_ENDPOINT,
|
||||
aws_access_key_id=S3_ACCESS_KEY,
|
||||
aws_secret_access_key=S3_SECRET_KEY,
|
||||
config=Config(signature_version="s3v4"),
|
||||
region_name="us-east-1"
|
||||
)
|
||||
|
||||
def ensure_bucket():
|
||||
"""Идемпотентно создаёт приватный bucket."""
|
||||
try:
|
||||
s3.head_bucket(Bucket=S3_BUCKET)
|
||||
except s3.exceptions.ClientError:
|
||||
s3.create_bucket(Bucket=S3_BUCKET)
|
||||
|
||||
def upload_file(key: str, data: bytes, content_type: str):
|
||||
s3.put_object(Bucket=S3_BUCKET, Key=key, Body=data, ContentType=content_type)
|
||||
|
||||
def download_file(key: str) -> bytes:
|
||||
response = s3.get_object(Bucket=S3_BUCKET, Key=key)
|
||||
return response["Body"].read()
|
||||
|
||||
def delete_file(key: str):
|
||||
s3.delete_object(Bucket=S3_BUCKET, Key=key)
|
||||
@@ -0,0 +1,16 @@
|
||||
import hashlib, os, secrets
|
||||
|
||||
def hash_password(password: str) -> str:
|
||||
salt = secrets.token_bytes(16)
|
||||
key = hashlib.scrypt(password.encode(), salt=salt, n=16384, r=8, p=1, dklen=64)
|
||||
return salt.hex() + "$" + key.hex()
|
||||
|
||||
def verify_password(password: str, stored: str) -> bool:
|
||||
salt_hex, key_hex = stored.split("$")
|
||||
salt = bytes.fromhex(salt_hex)
|
||||
expected = bytes.fromhex(key_hex)
|
||||
actual = hashlib.scrypt(password.encode(), salt=salt, n=16384, r=8, p=1, dklen=64)
|
||||
return secrets.compare_digest(actual, expected)
|
||||
|
||||
def generate_token() -> str:
|
||||
return secrets.token_urlsafe(48) # ~384 бита энтропии
|
||||
Reference in New Issue
Block a user