feat: добавить API, compose, nginx и отчёт для лабораторной 3
Co-authored-by: aider (deepseek/deepseek-chat) <aider@aider.chat>
This commit is contained in:
@@ -0,0 +1,49 @@
|
||||
import base64
|
||||
import binascii
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from fastapi import APIRouter, Depends, Request
|
||||
from sqlalchemy import delete, select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..config import settings
|
||||
from ..deps import current_user, get_db
|
||||
from ..errors import ApiError
|
||||
from ..models import SessionRow, User
|
||||
from ..schemas import SessionOut, UserOut
|
||||
from ..security import new_token, session_expiry, token_hash, verify_password
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
def _parse_basic(header: str):
|
||||
if not header.lower().startswith("basic "):
|
||||
raise ApiError(401, "unauthorized", "Требуется Basic")
|
||||
try:
|
||||
raw = base64.b64decode(header[6:].strip(), validate=True).decode("utf-8")
|
||||
except (binascii.Error, UnicodeDecodeError):
|
||||
raise ApiError(401, "unauthorized", "Некорректный Basic")
|
||||
if ":" not in raw:
|
||||
raise ApiError(401, "unauthorized", "Некорректный Basic")
|
||||
username, password = raw.split(":", 1)
|
||||
return username, password
|
||||
|
||||
|
||||
@router.post("/api/v1/auth/sessions", response_model=SessionOut, status_code=201)
|
||||
def login(request: Request, db: Session = Depends(get_db)):
|
||||
username, password = _parse_basic(request.headers.get("authorization", ""))
|
||||
user = db.scalar(select(User).where(User.username == username))
|
||||
if user is None or not verify_password(password, user.password_hash):
|
||||
raise ApiError(401, "unauthorized", "Неверные учётные данные")
|
||||
token = new_token()
|
||||
expires = session_expiry(settings.session_ttl_seconds)
|
||||
db.add(SessionRow(token_hash=token_hash(token), user_id=user.id, expires_at=expires))
|
||||
db.commit()
|
||||
return SessionOut(token=token, token_type="Bearer", expires_at=expires, user=UserOut.model_validate(user, from_attributes=True))
|
||||
|
||||
|
||||
@router.delete("/api/v1/auth/sessions/current", status_code=204)
|
||||
def logout(request: Request, user: User = Depends(current_user), db: Session = Depends(get_db)):
|
||||
db.execute(delete(SessionRow).where(SessionRow.token_hash == request.state.token_hash))
|
||||
db.commit()
|
||||
return None
|
||||
@@ -0,0 +1,100 @@
|
||||
import base64
|
||||
import json
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
|
||||
from fastapi import APIRouter, Depends, Query
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..deps import current_user, get_db, parse_uuid
|
||||
from ..errors import ApiError
|
||||
from ..models import Chat, ChatMember, User
|
||||
from ..schemas import ChatOut, ChatPage, CreateChat
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
def _chat_out(chat: Chat, member_ids) -> ChatOut:
|
||||
return ChatOut(id=chat.id, title=chat.title, member_ids=list(member_ids), created_at=chat.created_at)
|
||||
|
||||
|
||||
def _member_ids(db: Session, chat_id) -> list:
|
||||
return list(db.scalars(select(ChatMember.user_id).where(ChatMember.chat_id == chat_id)))
|
||||
|
||||
|
||||
def _require_member(db: Session, chat_id, user_id) -> Chat:
|
||||
chat = db.get(Chat, chat_id)
|
||||
if chat is None:
|
||||
raise ApiError(404, "not_found", "Чат не найден")
|
||||
if db.get(ChatMember, (chat_id, user_id)) is None:
|
||||
raise ApiError(404, "not_found", "Чат не найден")
|
||||
return chat
|
||||
|
||||
|
||||
def _encode_cursor(created_at: datetime, id_: uuid.UUID) -> str:
|
||||
payload = json.dumps({"t": created_at.isoformat(), "i": str(id_)}).encode()
|
||||
return base64.urlsafe_b64encode(payload).decode().rstrip("=")
|
||||
|
||||
|
||||
def _decode_cursor(cursor: str):
|
||||
try:
|
||||
pad = "=" * (-len(cursor) % 4)
|
||||
data = json.loads(base64.urlsafe_b64decode(cursor + pad))
|
||||
return datetime.fromisoformat(data["t"]), uuid.UUID(data["i"])
|
||||
except Exception:
|
||||
raise ApiError(400, "invalid_request", "Некорректный cursor")
|
||||
|
||||
|
||||
@router.post("/api/v1/chats", response_model=ChatOut, status_code=201)
|
||||
def create_chat(body: CreateChat, user: User = Depends(current_user), db: Session = Depends(get_db)):
|
||||
if not body.title.strip():
|
||||
raise ApiError(400, "invalid_request", "title не может быть пустым")
|
||||
ids = list(dict.fromkeys(body.member_ids))
|
||||
if user.id not in ids:
|
||||
raise ApiError(400, "invalid_request", "Вызывающий должен быть участником")
|
||||
found = set(db.scalars(select(User.id).where(User.id.in_(ids))))
|
||||
if found != set(ids):
|
||||
raise ApiError(400, "invalid_request", "Неизвестный участник")
|
||||
chat = Chat(title=body.title)
|
||||
db.add(chat)
|
||||
db.flush()
|
||||
for uid in ids:
|
||||
db.add(ChatMember(chat_id=chat.id, user_id=uid))
|
||||
db.commit()
|
||||
db.refresh(chat)
|
||||
return _chat_out(chat, ids)
|
||||
|
||||
|
||||
@router.get("/api/v1/chats", response_model=ChatPage)
|
||||
def list_chats(
|
||||
limit: int = Query(50, ge=1, le=100),
|
||||
cursor: str | None = Query(None),
|
||||
user: User = Depends(current_user),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
stmt = (
|
||||
select(Chat)
|
||||
.join(ChatMember, ChatMember.chat_id == Chat.id)
|
||||
.where(ChatMember.user_id == user.id)
|
||||
.order_by(Chat.created_at.asc(), Chat.id.asc())
|
||||
.limit(limit + 1)
|
||||
)
|
||||
if cursor:
|
||||
t, i = _decode_cursor(cursor)
|
||||
stmt = stmt.where((Chat.created_at > t) | ((Chat.created_at == t) & (Chat.id > i)))
|
||||
rows = list(db.scalars(stmt))
|
||||
next_cursor = None
|
||||
if len(rows) > limit:
|
||||
rows = rows[:limit]
|
||||
last = rows[-1]
|
||||
next_cursor = _encode_cursor(last.created_at, last.id)
|
||||
items = [_chat_out(c, _member_ids(db, c.id)) for c in rows]
|
||||
return ChatPage(items=items, next_cursor=next_cursor)
|
||||
|
||||
|
||||
@router.get("/api/v1/chats/{chat_id}", response_model=ChatOut)
|
||||
def get_chat(chat_id: str, user: User = Depends(current_user), db: Session = Depends(get_db)):
|
||||
cid = parse_uuid(chat_id)
|
||||
chat = _require_member(db, cid, user.id)
|
||||
return _chat_out(chat, _member_ids(db, cid))
|
||||
@@ -0,0 +1,24 @@
|
||||
from fastapi import APIRouter, Depends
|
||||
from sqlalchemy import text
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..db import get_db if False else None # placeholder to avoid circular import
|
||||
from ..deps import get_db
|
||||
from ..errors import ApiError
|
||||
from ..schemas import Health
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.get("/health/live", response_model=Health)
|
||||
def live():
|
||||
return Health()
|
||||
|
||||
|
||||
@router.get("/health/ready", response_model=Health)
|
||||
def ready(db: Session = Depends(get_db)):
|
||||
try:
|
||||
db.execute(text("SELECT 1"))
|
||||
except Exception:
|
||||
raise ApiError(503, "unavailable", "База данных недоступна")
|
||||
return Health()
|
||||
@@ -0,0 +1,98 @@
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
import uuid
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
from fastapi import APIRouter, Depends, Header, Query, Request
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..config import settings
|
||||
from ..deps import current_user, get_db, parse_uuid
|
||||
from ..errors import ApiError
|
||||
from ..models import Chat, ChatMember, IdempotencyKey, Message, User
|
||||
from ..schemas import CreateMessage, MessageOut, MessagePage
|
||||
from .chats import _decode_cursor, _encode_cursor, _require_member
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
_KEY_RE = re.compile(r"^[A-Za-z0-9._:-]{1,128}$")
|
||||
|
||||
|
||||
def _body_hash(body: CreateMessage) -> str:
|
||||
canonical = json.dumps({"text": body.text}, sort_keys=True, ensure_ascii=False)
|
||||
return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
@router.post("/api/v1/chats/{chat_id}/messages", response_model=MessageOut, status_code=201)
|
||||
def create_message(
|
||||
chat_id: str,
|
||||
body: CreateMessage,
|
||||
request: Request,
|
||||
idempotency_key: str | None = Header(default=None, alias="Idempotency-Key"),
|
||||
user: User = Depends(current_user),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
cid = parse_uuid(chat_id)
|
||||
_require_member(db, cid, user.id)
|
||||
if not body.text.strip():
|
||||
raise ApiError(400, "invalid_request", "text не может быть пустым")
|
||||
if not idempotency_key or not _KEY_RE.match(idempotency_key):
|
||||
raise ApiError(400, "invalid_request", "Некорректный Idempotency-Key")
|
||||
path = f"/api/v1/chats/{cid}/messages"
|
||||
bh = _body_hash(body)
|
||||
|
||||
existing = db.get(IdempotencyKey, (user.id, "POST", path, idempotency_key))
|
||||
if existing is not None:
|
||||
if existing.body_hash != bh:
|
||||
raise ApiError(409, "conflict", "Ключ уже использован с другим телом")
|
||||
msg = db.get(Message, existing.message_id)
|
||||
return MessageOut.model_validate(msg, from_attributes=True)
|
||||
|
||||
msg = Message(chat_id=cid, sender_id=user.id, text=body.text)
|
||||
db.add(msg)
|
||||
db.flush()
|
||||
db.add(IdempotencyKey(user_id=user.id, method="POST", path=path, key=idempotency_key, body_hash=bh, message_id=msg.id))
|
||||
try:
|
||||
db.commit()
|
||||
except IntegrityError:
|
||||
db.rollback()
|
||||
existing = db.get(IdempotencyKey, (user.id, "POST", path, idempotency_key))
|
||||
if existing is None:
|
||||
raise ApiError(500, "internal_error", "Не удалось сохранить сообщение")
|
||||
if existing.body_hash != bh:
|
||||
raise ApiError(409, "conflict", "Ключ уже использован с другим телом")
|
||||
msg = db.get(Message, existing.message_id)
|
||||
return MessageOut.model_validate(msg, from_attributes=True)
|
||||
db.refresh(msg)
|
||||
return MessageOut.model_validate(msg, from_attributes=True)
|
||||
|
||||
|
||||
@router.get("/api/v1/chats/{chat_id}/messages", response_model=MessagePage)
|
||||
def list_messages(
|
||||
chat_id: str,
|
||||
limit: int = Query(50, ge=1, le=100),
|
||||
cursor: str | None = Query(None),
|
||||
user: User = Depends(current_user),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
cid = parse_uuid(chat_id)
|
||||
_require_member(db, cid, user.id)
|
||||
stmt = (
|
||||
select(Message)
|
||||
.where(Message.chat_id == cid)
|
||||
.order_by(Message.created_at.asc(), Message.id.asc())
|
||||
.limit(limit + 1)
|
||||
)
|
||||
if cursor:
|
||||
t, i = _decode_cursor(cursor)
|
||||
stmt = stmt.where((Message.created_at > t) | ((Message.created_at == t) & (Message.id > i)))
|
||||
rows = list(db.scalars(stmt))
|
||||
next_cursor = None
|
||||
if len(rows) > limit:
|
||||
rows = rows[:limit]
|
||||
last = rows[-1]
|
||||
next_cursor = _encode_cursor(last.created_at, last.id)
|
||||
return MessagePage(items=[MessageOut.model_validate(m, from_attributes=True) for m in rows], next_cursor=next_cursor)
|
||||
@@ -0,0 +1,32 @@
|
||||
from fastapi import APIRouter, Depends
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..deps import current_user, get_db
|
||||
from ..errors import ApiError
|
||||
from ..models import User
|
||||
from ..schemas import CreateUser, UserOut
|
||||
from ..security import hash_password
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.post("/api/v1/users", response_model=UserOut, status_code=201)
|
||||
def register(body: CreateUser, db: Session = Depends(get_db)):
|
||||
if not body.display_name.strip():
|
||||
raise ApiError(400, "invalid_request", "display_name не может быть пустым")
|
||||
user = User(username=body.username, display_name=body.display_name, password_hash=hash_password(body.password))
|
||||
db.add(user)
|
||||
try:
|
||||
db.commit()
|
||||
except IntegrityError:
|
||||
db.rollback()
|
||||
raise ApiError(409, "conflict", "username занят")
|
||||
db.refresh(user)
|
||||
return user
|
||||
|
||||
|
||||
@router.get("/api/v1/users/me", response_model=UserOut)
|
||||
def me(user: User = Depends(current_user)):
|
||||
return user
|
||||
Reference in New Issue
Block a user