forked from mtusi2026/mtusi2026lab4
Lab4: S3 attachments (grade 3)
This commit is contained in:
@@ -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
|
||||
Reference in New Issue
Block a user