forked from mtusi2026/mtusi2026lab4
Lab4: S3 attachments (grade 3)
This commit is contained in:
+47
@@ -0,0 +1,47 @@
|
||||
import hashlib
|
||||
import secrets
|
||||
from datetime import datetime, timezone, timedelta
|
||||
from fastapi import Depends, Request
|
||||
from sqlalchemy.orm import Session
|
||||
from argon2 import PasswordHasher
|
||||
from argon2.exceptions import VerifyMismatchError
|
||||
from . import config
|
||||
from .db import get_db
|
||||
from .models import User, Session as DbSession
|
||||
from .errors import ApiError
|
||||
|
||||
_ph = PasswordHasher()
|
||||
_BEARER = 'Bearer realm="messenger"'
|
||||
|
||||
def hash_password(p: str) -> str:
|
||||
return _ph.hash(p)
|
||||
|
||||
def verify_password(h: str, p: str) -> bool:
|
||||
try:
|
||||
return _ph.verify(h, p)
|
||||
except VerifyMismatchError:
|
||||
return False
|
||||
|
||||
def new_session(db: Session, user: User) -> tuple[str, datetime]:
|
||||
token = secrets.token_urlsafe(48)
|
||||
token_hash = hashlib.sha256(token.encode()).hexdigest()
|
||||
expires = datetime.now(timezone.utc) + timedelta(seconds=config.SESSION_TTL_SECONDS)
|
||||
db.add(DbSession(token_hash=token_hash, user_id=user.id, expires_at=expires))
|
||||
db.commit()
|
||||
return token, expires
|
||||
|
||||
def current_user(request: Request, db: Session = Depends(get_db)) -> User:
|
||||
auth = request.headers.get("authorization", "")
|
||||
if not auth.lower().startswith("bearer "):
|
||||
raise ApiError(401, "unauthorized", "missing bearer token", challenge=_BEARER)
|
||||
token = auth[7:].strip()
|
||||
token_hash = hashlib.sha256(token.encode()).hexdigest()
|
||||
s = db.get(DbSession, token_hash)
|
||||
if not s:
|
||||
raise ApiError(401, "unauthorized", "invalid session", challenge=_BEARER)
|
||||
if s.expires_at <= datetime.now(timezone.utc):
|
||||
raise ApiError(401, "unauthorized", "expired session", challenge=_BEARER)
|
||||
u = db.get(User, s.user_id)
|
||||
if not u:
|
||||
raise ApiError(401, "unauthorized", "user gone", challenge=_BEARER)
|
||||
return u
|
||||
@@ -0,0 +1,26 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
def _read_secret(env_name: str, file_env: str, default=None):
|
||||
path = os.environ.get(file_env)
|
||||
if path:
|
||||
return Path(path).read_text().strip()
|
||||
return os.environ.get(env_name, default)
|
||||
|
||||
APP_HOST = os.environ.get("APP_HOST", "0.0.0.0")
|
||||
APP_PORT = int(os.environ.get("APP_PORT", "8080"))
|
||||
APP_ENV = os.environ.get("APP_ENV", "lab")
|
||||
SESSION_TTL_SECONDS = int(os.environ.get("SESSION_TTL_SECONDS", "3600"))
|
||||
|
||||
DATABASE_URL = _read_secret("DATABASE_URL", "DATABASE_URL_FILE")
|
||||
|
||||
S3_ENDPOINT = os.environ.get("S3_ENDPOINT", "http://s3:9000")
|
||||
S3_REGION = os.environ.get("S3_REGION", "us-east-1")
|
||||
S3_BUCKET = os.environ.get("S3_BUCKET", "messenger-attachments")
|
||||
S3_ACCESS_KEY = _read_secret("S3_ACCESS_KEY_ID", "S3_ACCESS_KEY_ID_FILE")
|
||||
S3_SECRET_KEY = _read_secret("S3_SECRET_ACCESS_KEY", "S3_SECRET_ACCESS_KEY_FILE")
|
||||
|
||||
MAX_UPLOAD_BYTES = int(os.environ.get("MAX_UPLOAD_BYTES", str(10 * 1024 * 1024)))
|
||||
MAX_IMAGE_PIXELS = int(os.environ.get("MAX_IMAGE_PIXELS", "40000000"))
|
||||
|
||||
INSTANCE_ID = os.environ.get("INSTANCE_ID", "api-unknown")
|
||||
@@ -0,0 +1,16 @@
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import sessionmaker, DeclarativeBase
|
||||
from . import config
|
||||
|
||||
engine = create_engine(config.DATABASE_URL, pool_pre_ping=True, pool_size=5, max_overflow=10)
|
||||
SessionLocal = sessionmaker(bind=engine, autoflush=False, expire_on_commit=False)
|
||||
|
||||
class Base(DeclarativeBase):
|
||||
pass
|
||||
|
||||
def get_db():
|
||||
db = SessionLocal()
|
||||
try:
|
||||
yield db
|
||||
finally:
|
||||
db.close()
|
||||
@@ -0,0 +1,29 @@
|
||||
from fastapi import Request
|
||||
from fastapi.responses import JSONResponse
|
||||
|
||||
class ApiError(Exception):
|
||||
def __init__(self, status: int, code: str, message: str, challenge: str | None = None):
|
||||
self.status = status
|
||||
self.code = code
|
||||
self.message = message
|
||||
self.challenge = challenge
|
||||
|
||||
def _rid(request: Request) -> str:
|
||||
return getattr(request.state, "request_id", None) or "unknown"
|
||||
|
||||
async def api_error_handler(request: Request, exc: ApiError):
|
||||
headers = {"X-Request-Id": _rid(request)}
|
||||
if exc.challenge:
|
||||
headers["WWW-Authenticate"] = exc.challenge
|
||||
return JSONResponse(
|
||||
status_code=exc.status,
|
||||
content={"error": {"code": exc.code, "message": exc.message, "request_id": _rid(request)}},
|
||||
headers=headers,
|
||||
)
|
||||
|
||||
async def unhandled_handler(request: Request, exc: Exception):
|
||||
return JSONResponse(
|
||||
status_code=500,
|
||||
content={"error": {"code": "internal_error", "message": "internal error", "request_id": _rid(request)}},
|
||||
headers={"X-Request-Id": _rid(request)},
|
||||
)
|
||||
@@ -0,0 +1,26 @@
|
||||
import io
|
||||
from PIL import Image, UnidentifiedImageError
|
||||
from . import config
|
||||
from .errors import ApiError
|
||||
|
||||
def validate_image(data: bytes) -> tuple[str, int, int, int]:
|
||||
"""Возвращает (content_type, width, height, size)."""
|
||||
if not data:
|
||||
raise ApiError(400, "invalid_request", "empty body")
|
||||
if len(data) > config.MAX_UPLOAD_BYTES:
|
||||
raise ApiError(413, "payload_too_large", "file too large")
|
||||
head = data[:8]
|
||||
if head.startswith(b"\x89PNG\r\n\x1a\n"):
|
||||
ctype = "image/png"
|
||||
elif head.startswith(b"\xff\xd8\xff"):
|
||||
ctype = "image/jpeg"
|
||||
else:
|
||||
raise ApiError(415, "unsupported_media_type", "only PNG/JPEG")
|
||||
try:
|
||||
img = Image.open(io.BytesIO(data))
|
||||
w, h = img.size
|
||||
except UnidentifiedImageError:
|
||||
raise ApiError(415, "unsupported_media_type", "invalid image")
|
||||
if w * h > config.MAX_IMAGE_PIXELS:
|
||||
raise ApiError(413, "payload_too_large", "too many pixels")
|
||||
return ctype, w, h, len(data)
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
import uuid
|
||||
from contextlib import asynccontextmanager
|
||||
from fastapi import FastAPI, Request
|
||||
from . import config
|
||||
from .db import engine, Base
|
||||
from .errors import ApiError, api_error_handler, unhandled_handler
|
||||
from .s3 import ensure_bucket
|
||||
from .routers import health, users, sessions, chats, messages, attachments
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
# create_all is not idempotent under parallel startup: two replicas
|
||||
# may race and one hits UniqueViolation on pg_type. Catch and re-run
|
||||
# once after a short delay; by then the other replica has finished.
|
||||
import asyncio
|
||||
from sqlalchemy.exc import IntegrityError, OperationalError
|
||||
|
||||
for attempt in range(5):
|
||||
try:
|
||||
Base.metadata.create_all(engine)
|
||||
break
|
||||
except (IntegrityError, OperationalError) as exc:
|
||||
print(f"WARN: create_all attempt {attempt+1} failed: {exc}")
|
||||
await asyncio.sleep(1.0)
|
||||
else:
|
||||
print("WARN: create_all failed after 5 attempts; continuing")
|
||||
|
||||
try:
|
||||
ensure_bucket()
|
||||
except Exception as exc:
|
||||
print(f"WARN: ensure_bucket failed: {exc}")
|
||||
yield
|
||||
|
||||
app = FastAPI(lifespan=lifespan)
|
||||
app.add_exception_handler(ApiError, api_error_handler)
|
||||
app.add_exception_handler(Exception, unhandled_handler)
|
||||
|
||||
@app.middleware("http")
|
||||
async def add_request_id(request: Request, call_next):
|
||||
rid = request.headers.get("X-Request-Id") or uuid.uuid4().hex
|
||||
request.state.request_id = rid
|
||||
response = await call_next(request)
|
||||
response.headers["X-Request-Id"] = rid
|
||||
response.headers["X-Instance-Id"] = config.INSTANCE_ID
|
||||
return response
|
||||
|
||||
for r in (health, users, sessions, chats, messages, attachments):
|
||||
app.include_router(r.router)
|
||||
+110
@@ -0,0 +1,110 @@
|
||||
import uuid
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from sqlalchemy import String, DateTime, ForeignKey, Integer, UniqueConstraint, Index
|
||||
from sqlalchemy.dialects.postgresql import UUID as PGUUID
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from .db import Base
|
||||
|
||||
|
||||
def _uuid() -> uuid.UUID:
|
||||
return uuid.uuid4()
|
||||
|
||||
|
||||
def _now() -> datetime:
|
||||
return datetime.now(timezone.utc)
|
||||
|
||||
|
||||
class User(Base):
|
||||
__tablename__ = "users"
|
||||
id: Mapped[uuid.UUID] = mapped_column(PGUUID(as_uuid=True), primary_key=True, default=_uuid)
|
||||
username: Mapped[str] = mapped_column(String(32), unique=True, index=True)
|
||||
display_name: Mapped[str] = mapped_column(String(100))
|
||||
password_hash: Mapped[str] = mapped_column(String(255))
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=_now)
|
||||
|
||||
|
||||
class Session(Base):
|
||||
__tablename__ = "sessions"
|
||||
token_hash: Mapped[str] = mapped_column(String(64), primary_key=True) # sha256(token) hex
|
||||
user_id: Mapped[uuid.UUID] = mapped_column(
|
||||
PGUUID(as_uuid=True), ForeignKey("users.id", ondelete="CASCADE"), index=True
|
||||
)
|
||||
expires_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), index=True)
|
||||
|
||||
|
||||
class Chat(Base):
|
||||
__tablename__ = "chats"
|
||||
id: Mapped[uuid.UUID] = mapped_column(PGUUID(as_uuid=True), primary_key=True, default=_uuid)
|
||||
title: Mapped[str] = mapped_column(String(100))
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=_now, index=True)
|
||||
|
||||
|
||||
class ChatMember(Base):
|
||||
__tablename__ = "chat_members"
|
||||
chat_id: Mapped[uuid.UUID] = mapped_column(
|
||||
PGUUID(as_uuid=True), ForeignKey("chats.id", ondelete="CASCADE"), primary_key=True
|
||||
)
|
||||
user_id: Mapped[uuid.UUID] = mapped_column(
|
||||
PGUUID(as_uuid=True), ForeignKey("users.id", ondelete="CASCADE"), primary_key=True
|
||||
)
|
||||
|
||||
|
||||
class Message(Base):
|
||||
__tablename__ = "messages"
|
||||
id: Mapped[uuid.UUID] = mapped_column(PGUUID(as_uuid=True), primary_key=True, default=_uuid)
|
||||
chat_id: Mapped[uuid.UUID] = mapped_column(
|
||||
PGUUID(as_uuid=True), ForeignKey("chats.id", ondelete="CASCADE"), index=True
|
||||
)
|
||||
sender_id: Mapped[uuid.UUID] = mapped_column(
|
||||
PGUUID(as_uuid=True), ForeignKey("users.id")
|
||||
)
|
||||
text: Mapped[str] = mapped_column(String(4000), default="")
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=_now, index=True)
|
||||
|
||||
|
||||
class MessageAttachment(Base):
|
||||
__tablename__ = "message_attachments"
|
||||
message_id: Mapped[uuid.UUID] = mapped_column(
|
||||
PGUUID(as_uuid=True), ForeignKey("messages.id", ondelete="CASCADE"), primary_key=True
|
||||
)
|
||||
attachment_id: Mapped[uuid.UUID] = mapped_column(
|
||||
PGUUID(as_uuid=True), ForeignKey("attachments.id"), primary_key=True
|
||||
)
|
||||
position: Mapped[int] = mapped_column(Integer, default=0)
|
||||
|
||||
|
||||
class IdempotencyKey(Base):
|
||||
__tablename__ = "idempotency_keys"
|
||||
user_id: Mapped[uuid.UUID] = mapped_column(
|
||||
PGUUID(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)
|
||||
request_hash: Mapped[str] = mapped_column(String(64))
|
||||
response_json: Mapped[str] = mapped_column(String)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=_now)
|
||||
|
||||
__table_args__ = (Index("ix_idem_created", "created_at"),)
|
||||
|
||||
|
||||
class Attachment(Base):
|
||||
__tablename__ = "attachments"
|
||||
id: Mapped[uuid.UUID] = mapped_column(PGUUID(as_uuid=True), primary_key=True, default=_uuid)
|
||||
chat_id: Mapped[uuid.UUID] = mapped_column(
|
||||
PGUUID(as_uuid=True), ForeignKey("chats.id", ondelete="CASCADE"), index=True
|
||||
)
|
||||
owner_id: Mapped[uuid.UUID] = mapped_column(
|
||||
PGUUID(as_uuid=True), ForeignKey("users.id")
|
||||
)
|
||||
filename: Mapped[str] = mapped_column(String(255))
|
||||
content_type: Mapped[str] = mapped_column(String(32))
|
||||
size_bytes: Mapped[int] = mapped_column(Integer)
|
||||
sha256: Mapped[str] = mapped_column(String(64))
|
||||
s3_key: Mapped[str] = mapped_column(String(255))
|
||||
status: Mapped[str] = mapped_column(String(16), default="ready")
|
||||
error_code: Mapped[str | None] = mapped_column(String(64), nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=_now)
|
||||
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=_now, onupdate=_now)
|
||||
@@ -0,0 +1,72 @@
|
||||
import hashlib
|
||||
import uuid
|
||||
from fastapi import APIRouter, Depends, Request, Query
|
||||
from fastapi.responses import Response
|
||||
from sqlalchemy.orm import Session
|
||||
from ..db import get_db
|
||||
from ..models import Attachment, ChatMember
|
||||
from ..auth import current_user
|
||||
from ..errors import ApiError
|
||||
from .. import s3, config
|
||||
from ..images import validate_image
|
||||
from ..schemas import AttachmentOut
|
||||
|
||||
router = APIRouter(prefix="/api/v1", tags=["attachments"])
|
||||
|
||||
def _bad_filename(name: str) -> bool:
|
||||
return (not name) or len(name) > 255 or any(c in name for c in ("/", "\\", "\x00")) or any(ord(c) < 32 for c in name)
|
||||
|
||||
def _member_chat_or_404(db, chat_id, user_id):
|
||||
if not db.get(ChatMember, (chat_id, user_id)):
|
||||
raise ApiError(404, "not_found", "chat not found")
|
||||
|
||||
def _attachment_for_member(db, att_id, user_id) -> Attachment:
|
||||
att = db.get(Attachment, att_id)
|
||||
if not att:
|
||||
raise ApiError(404, "not_found", "attachment not found")
|
||||
_member_chat_or_404(db, att.chat_id, user_id)
|
||||
return att
|
||||
|
||||
@router.post("/chats/{chat_id}/attachments", status_code=201, response_model=AttachmentOut)
|
||||
async def upload(chat_id: uuid.UUID,
|
||||
filename: str = Query(..., min_length=1, max_length=255),
|
||||
request: Request = None,
|
||||
db: Session = Depends(get_db),
|
||||
user=Depends(current_user)):
|
||||
_member_chat_or_404(db, chat_id, user.id)
|
||||
if _bad_filename(filename):
|
||||
raise ApiError(400, "invalid_request", "invalid filename")
|
||||
ctype_header = request.headers.get("content-type", "").split(";")[0].strip()
|
||||
if ctype_header not in ("image/png", "image/jpeg"):
|
||||
raise ApiError(415, "unsupported_media_type", "expected image/png or image/jpeg")
|
||||
data = await request.body()
|
||||
ctype, w, h, size = validate_image(data)
|
||||
if ctype != ctype_header:
|
||||
raise ApiError(415, "unsupported_media_type", "content-type mismatch with file")
|
||||
digest = hashlib.sha256(data).hexdigest()
|
||||
key = f"chats/{chat_id}/attachments/{uuid.uuid4()}"
|
||||
s3.client().put_object(Bucket=config.S3_BUCKET, Key=key, Body=data, ContentType=ctype)
|
||||
att = Attachment(chat_id=chat_id, owner_id=user.id, filename=filename,
|
||||
content_type=ctype, size_bytes=size, sha256=digest, s3_key=key,
|
||||
status="ready")
|
||||
try:
|
||||
db.add(att); db.commit(); db.refresh(att)
|
||||
except Exception:
|
||||
db.rollback()
|
||||
try:
|
||||
s3.client().delete_object(Bucket=config.S3_BUCKET, Key=key)
|
||||
except Exception:
|
||||
pass
|
||||
raise
|
||||
return att
|
||||
|
||||
@router.get("/attachments/{att_id}", response_model=AttachmentOut)
|
||||
def meta(att_id: uuid.UUID, db=Depends(get_db), user=Depends(current_user)):
|
||||
return _attachment_for_member(db, att_id, user.id)
|
||||
|
||||
@router.get("/attachments/{att_id}/content")
|
||||
def content(att_id: uuid.UUID, db=Depends(get_db), user=Depends(current_user)):
|
||||
att = _attachment_for_member(db, att_id, user.id)
|
||||
obj = s3.client().get_object(Bucket=config.S3_BUCKET, Key=att.s3_key)
|
||||
body = obj["Body"].read()
|
||||
return Response(content=body, media_type=att.content_type)
|
||||
@@ -0,0 +1,44 @@
|
||||
import uuid
|
||||
from fastapi import APIRouter, Depends
|
||||
from sqlalchemy.orm import Session
|
||||
from ..db import get_db
|
||||
from ..models import User, Chat, ChatMember
|
||||
from ..schemas import CreateChatIn, ChatOut, ChatPage
|
||||
from ..errors import ApiError
|
||||
from ..auth import current_user
|
||||
|
||||
router = APIRouter(prefix="/api/v1/chats", tags=["chats"])
|
||||
|
||||
def _chat_out(db, chat) -> ChatOut:
|
||||
members = [m.user_id for m in db.query(ChatMember).filter(ChatMember.chat_id == chat.id).all()]
|
||||
return ChatOut(id=chat.id, title=chat.title, member_ids=members, created_at=chat.created_at)
|
||||
|
||||
@router.post("", status_code=201, response_model=ChatOut)
|
||||
def create_chat(body: CreateChatIn, db: Session = Depends(get_db), user: User = Depends(current_user)):
|
||||
if user.id not in body.member_ids:
|
||||
raise ApiError(400, "invalid_request", "caller must be a member")
|
||||
found = db.query(User.id).filter(User.id.in_(body.member_ids)).all()
|
||||
if len(found) != len(set(body.member_ids)):
|
||||
raise ApiError(400, "invalid_request", "unknown member")
|
||||
chat = Chat(title=body.title)
|
||||
db.add(chat); db.flush()
|
||||
for uid in body.member_ids:
|
||||
db.add(ChatMember(chat_id=chat.id, user_id=uid))
|
||||
db.commit(); db.refresh(chat)
|
||||
return _chat_out(db, chat)
|
||||
|
||||
@router.get("", response_model=ChatPage)
|
||||
def list_chats(db: Session = Depends(get_db), user: User = Depends(current_user)):
|
||||
rows = db.query(Chat).join(ChatMember, ChatMember.chat_id == Chat.id)\
|
||||
.filter(ChatMember.user_id == user.id)\
|
||||
.order_by(Chat.created_at, Chat.id).limit(100).all()
|
||||
return ChatPage(items=[_chat_out(db, c) for c in rows], next_cursor=None)
|
||||
|
||||
@router.get("/{chat_id}", response_model=ChatOut)
|
||||
def get_chat(chat_id: uuid.UUID, db: Session = Depends(get_db), user: User = Depends(current_user)):
|
||||
if not db.get(ChatMember, (chat_id, user.id)):
|
||||
raise ApiError(404, "not_found", "chat not found")
|
||||
chat = db.get(Chat, chat_id)
|
||||
if not chat:
|
||||
raise ApiError(404, "not_found", "chat not found")
|
||||
return _chat_out(db, chat)
|
||||
@@ -0,0 +1,19 @@
|
||||
from fastapi import APIRouter, Depends
|
||||
from sqlalchemy import text
|
||||
from sqlalchemy.orm import Session
|
||||
from ..db import get_db
|
||||
from ..errors import ApiError
|
||||
|
||||
router = APIRouter(prefix="/health", tags=["health"])
|
||||
|
||||
@router.get("/live")
|
||||
def live():
|
||||
return {"status": "ok"}
|
||||
|
||||
@router.get("/ready")
|
||||
def ready(db: Session = Depends(get_db)):
|
||||
try:
|
||||
db.execute(text("SELECT 1"))
|
||||
except Exception:
|
||||
raise ApiError(503, "unavailable", "database unavailable")
|
||||
return {"status": "ok"}
|
||||
@@ -0,0 +1,147 @@
|
||||
import uuid
|
||||
import json
|
||||
import hashlib
|
||||
import base64
|
||||
from datetime import datetime
|
||||
|
||||
from fastapi import APIRouter, Depends, Request
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..db import get_db
|
||||
from ..models import (
|
||||
User,
|
||||
ChatMember,
|
||||
Message,
|
||||
MessageAttachment,
|
||||
IdempotencyKey,
|
||||
Attachment,
|
||||
)
|
||||
from ..schemas import CreateMessageIn, MessageOut, MessagePage
|
||||
from ..errors import ApiError
|
||||
from ..auth import current_user
|
||||
|
||||
router = APIRouter(prefix="/api/v1/chats/{chat_id}/messages", tags=["messages"])
|
||||
|
||||
|
||||
def _msg_out(db: Session, m: Message) -> MessageOut:
|
||||
atts = [
|
||||
a.attachment_id
|
||||
for a in db.query(MessageAttachment)
|
||||
.filter(MessageAttachment.message_id == m.id)
|
||||
.order_by(MessageAttachment.position)
|
||||
.all()
|
||||
]
|
||||
return MessageOut(
|
||||
id=m.id,
|
||||
chat_id=m.chat_id,
|
||||
sender_id=m.sender_id,
|
||||
text=m.text,
|
||||
created_at=m.created_at,
|
||||
attachment_ids=atts,
|
||||
)
|
||||
|
||||
|
||||
def _require_member(db: Session, chat_id: uuid.UUID, user_id: uuid.UUID) -> None:
|
||||
if not db.get(ChatMember, (chat_id, user_id)):
|
||||
raise ApiError(404, "not_found", "chat not found")
|
||||
|
||||
|
||||
@router.post("", status_code=201, response_model=MessageOut)
|
||||
def send(
|
||||
chat_id: uuid.UUID,
|
||||
body: CreateMessageIn,
|
||||
request: Request,
|
||||
db: Session = Depends(get_db),
|
||||
user: User = Depends(current_user),
|
||||
):
|
||||
_require_member(db, chat_id, user.id)
|
||||
|
||||
key = request.headers.get("idempotency-key", "")
|
||||
if not key or len(key) > 128:
|
||||
raise ApiError(400, "invalid_request", "Idempotency-Key required")
|
||||
|
||||
if not body.text.strip() and not body.attachment_ids:
|
||||
raise ApiError(400, "invalid_request", "empty message")
|
||||
|
||||
for aid in body.attachment_ids:
|
||||
a = db.get(Attachment, aid)
|
||||
if not a or a.chat_id != chat_id:
|
||||
raise ApiError(404, "not_found", "attachment not found")
|
||||
|
||||
path = f"/api/v1/chats/{chat_id}/messages"
|
||||
body_hash = hashlib.sha256(
|
||||
json.dumps(body.model_dump(), sort_keys=True, default=str).encode()
|
||||
).hexdigest()
|
||||
|
||||
existing = db.get(IdempotencyKey, (user.id, "POST", path, key))
|
||||
if existing:
|
||||
if existing.request_hash != body_hash:
|
||||
raise ApiError(409, "conflict", "idempotency key reused with different body")
|
||||
return json.loads(existing.response_json)
|
||||
|
||||
m = Message(chat_id=chat_id, sender_id=user.id, text=body.text)
|
||||
db.add(m)
|
||||
db.flush() # чтобы появился m.id
|
||||
|
||||
for i, aid in enumerate(body.attachment_ids):
|
||||
db.add(MessageAttachment(message_id=m.id, attachment_id=aid, position=i))
|
||||
db.flush() # чтобы _msg_out увидел MessageAttachment
|
||||
|
||||
out = _msg_out(db, m)
|
||||
|
||||
db.add(
|
||||
IdempotencyKey(
|
||||
user_id=user.id,
|
||||
method="POST",
|
||||
path=path,
|
||||
key=key,
|
||||
request_hash=body_hash,
|
||||
response_json=json.dumps(out.model_dump(), default=str),
|
||||
)
|
||||
)
|
||||
db.commit()
|
||||
return out
|
||||
|
||||
|
||||
@router.get("", response_model=MessagePage)
|
||||
def list_messages(
|
||||
chat_id: uuid.UUID,
|
||||
limit: int = 50,
|
||||
cursor: str | None = None,
|
||||
db: Session = Depends(get_db),
|
||||
user: User = Depends(current_user),
|
||||
):
|
||||
_require_member(db, chat_id, user.id)
|
||||
|
||||
if limit < 1 or limit > 100:
|
||||
raise ApiError(400, "invalid_request", "bad limit")
|
||||
|
||||
q = (
|
||||
db.query(Message)
|
||||
.filter(Message.chat_id == chat_id)
|
||||
.order_by(Message.created_at, Message.id)
|
||||
)
|
||||
|
||||
if cursor:
|
||||
try:
|
||||
c = json.loads(base64.urlsafe_b64decode(cursor.encode()).decode())
|
||||
ts = datetime.fromisoformat(c["t"])
|
||||
mid = uuid.UUID(c["i"])
|
||||
q = q.filter(
|
||||
(Message.created_at > ts)
|
||||
| ((Message.created_at == ts) & (Message.id > mid))
|
||||
)
|
||||
except Exception:
|
||||
raise ApiError(400, "invalid_request", "bad cursor")
|
||||
|
||||
rows = q.limit(limit + 1).all()
|
||||
has_more = len(rows) > limit
|
||||
rows = rows[:limit]
|
||||
|
||||
next_cursor = None
|
||||
if has_more:
|
||||
last = rows[-1]
|
||||
payload = json.dumps({"t": last.created_at.isoformat(), "i": str(last.id)}).encode()
|
||||
next_cursor = base64.urlsafe_b64encode(payload).decode()
|
||||
|
||||
return MessagePage(items=[_msg_out(db, m) for m in rows], next_cursor=next_cursor)
|
||||
@@ -0,0 +1,41 @@
|
||||
import base64
|
||||
import hashlib
|
||||
from fastapi import APIRouter, Depends, Request
|
||||
from sqlalchemy.orm import Session
|
||||
from ..db import get_db
|
||||
from ..models import User, Session as DbSession
|
||||
from ..schemas import SessionOut
|
||||
from ..errors import ApiError
|
||||
from ..auth import verify_password, new_session, current_user
|
||||
|
||||
router = APIRouter(prefix="/api/v1/auth/sessions", tags=["sessions"])
|
||||
|
||||
_BASIC = 'Basic realm="messenger", charset="UTF-8"'
|
||||
_BEARER = 'Bearer realm="messenger"'
|
||||
|
||||
@router.post("", status_code=201, response_model=SessionOut)
|
||||
def login(request: Request, db: Session = Depends(get_db)):
|
||||
auth = request.headers.get("authorization", "")
|
||||
if not auth.lower().startswith("basic "):
|
||||
raise ApiError(401, "unauthorized", "basic required", challenge=_BASIC)
|
||||
try:
|
||||
raw = base64.b64decode(auth[6:].strip()).decode("utf-8")
|
||||
username, password = raw.split(":", 1)
|
||||
except Exception:
|
||||
raise ApiError(401, "unauthorized", "bad credentials", challenge=_BASIC)
|
||||
user = db.query(User).filter(User.username == username).first()
|
||||
if not user or not verify_password(user.password_hash, password):
|
||||
raise ApiError(401, "unauthorized", "bad credentials", challenge=_BASIC)
|
||||
token, expires = new_session(db, user)
|
||||
return {"token": token, "token_type": "Bearer", "expires_at": expires, "user": user}
|
||||
|
||||
@router.delete("/current", status_code=204)
|
||||
def logout(request: Request, db: Session = Depends(get_db), user: User = Depends(current_user)):
|
||||
auth = request.headers.get("authorization", "")
|
||||
token = auth[7:].strip()
|
||||
h = hashlib.sha256(token.encode()).hexdigest()
|
||||
s = db.get(DbSession, h)
|
||||
if s:
|
||||
db.delete(s)
|
||||
db.commit()
|
||||
return None
|
||||
@@ -0,0 +1,27 @@
|
||||
from fastapi import APIRouter, Depends
|
||||
from sqlalchemy.orm import Session
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
from ..db import get_db
|
||||
from ..models import User
|
||||
from ..schemas import CreateUserIn, UserOut
|
||||
from ..errors import ApiError
|
||||
from ..auth import hash_password, current_user
|
||||
|
||||
router = APIRouter(prefix="/api/v1/users", tags=["users"])
|
||||
|
||||
@router.post("", status_code=201, response_model=UserOut)
|
||||
def register(body: CreateUserIn, db: Session = Depends(get_db)):
|
||||
u = User(username=body.username, display_name=body.display_name,
|
||||
password_hash=hash_password(body.password))
|
||||
db.add(u)
|
||||
try:
|
||||
db.commit()
|
||||
except IntegrityError:
|
||||
db.rollback()
|
||||
raise ApiError(409, "conflict", "username taken")
|
||||
db.refresh(u)
|
||||
return u
|
||||
|
||||
@router.get("/me", response_model=UserOut)
|
||||
def me(user: User = Depends(current_user)):
|
||||
return user
|
||||
@@ -0,0 +1,30 @@
|
||||
import boto3
|
||||
from botocore.client import Config
|
||||
from botocore.exceptions import ClientError
|
||||
from . import config
|
||||
|
||||
_client = None
|
||||
|
||||
def client():
|
||||
global _client
|
||||
if _client is None:
|
||||
_client = boto3.client(
|
||||
"s3",
|
||||
endpoint_url=config.S3_ENDPOINT,
|
||||
region_name=config.S3_REGION,
|
||||
aws_access_key_id=config.S3_ACCESS_KEY,
|
||||
aws_secret_access_key=config.S3_SECRET_KEY,
|
||||
config=Config(signature_version="s3v4", s3={"addressing_style": "path"}),
|
||||
)
|
||||
return _client
|
||||
|
||||
def ensure_bucket():
|
||||
c = client()
|
||||
try:
|
||||
c.head_bucket(Bucket=config.S3_BUCKET)
|
||||
except ClientError as e:
|
||||
code = e.response.get("Error", {}).get("Code", "")
|
||||
if code in ("404", "NoSuchBucket", "NotFound"):
|
||||
c.create_bucket(Bucket=config.S3_BUCKET)
|
||||
else:
|
||||
raise
|
||||
@@ -0,0 +1,67 @@
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
from pydantic import BaseModel, Field, ConfigDict
|
||||
|
||||
class UserOut(BaseModel):
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
id: uuid.UUID
|
||||
username: str
|
||||
display_name: str
|
||||
created_at: datetime
|
||||
|
||||
class CreateUserIn(BaseModel):
|
||||
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):
|
||||
token: str
|
||||
token_type: str = "Bearer"
|
||||
expires_at: datetime
|
||||
user: UserOut
|
||||
|
||||
class ChatOut(BaseModel):
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
id: uuid.UUID
|
||||
title: str
|
||||
member_ids: list[uuid.UUID]
|
||||
created_at: datetime
|
||||
|
||||
class CreateChatIn(BaseModel):
|
||||
title: str = Field(min_length=1, max_length=100)
|
||||
member_ids: list[uuid.UUID] = Field(min_length=1, max_length=100)
|
||||
|
||||
class MessageOut(BaseModel):
|
||||
id: uuid.UUID
|
||||
chat_id: uuid.UUID
|
||||
sender_id: uuid.UUID
|
||||
text: str
|
||||
created_at: datetime
|
||||
attachment_ids: list[uuid.UUID]
|
||||
|
||||
class CreateMessageIn(BaseModel):
|
||||
text: str = Field(default="", max_length=4000)
|
||||
attachment_ids: list[uuid.UUID] = Field(default_factory=list, max_length=10)
|
||||
|
||||
class MessagePage(BaseModel):
|
||||
items: list[MessageOut]
|
||||
next_cursor: Optional[str] = None
|
||||
|
||||
class ChatPage(BaseModel):
|
||||
items: list[ChatOut]
|
||||
next_cursor: Optional[str] = None
|
||||
|
||||
class AttachmentOut(BaseModel):
|
||||
id: uuid.UUID
|
||||
chat_id: uuid.UUID
|
||||
owner_id: uuid.UUID
|
||||
filename: str
|
||||
content_type: str
|
||||
size_bytes: int
|
||||
sha256: str
|
||||
status: str = "ready"
|
||||
variants: list = []
|
||||
error_code: Optional[str] = None
|
||||
created_at: datetime
|
||||
updated_at: datetime
|
||||
Reference in New Issue
Block a user