lab2: PostgreSQL persistence, Argon2id sessions, Compose stack (grade 3)
This commit is contained in:
Executable
+87
@@ -0,0 +1,87 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import os
|
||||
import secrets
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Optional
|
||||
|
||||
import psycopg
|
||||
from argon2 import PasswordHasher
|
||||
from argon2.exceptions import VerifyMismatchError, VerificationError, InvalidHashError
|
||||
|
||||
from .db import transaction
|
||||
|
||||
_hasher = PasswordHasher()
|
||||
|
||||
|
||||
def hash_password(password: str) -> str:
|
||||
return _hasher.hash(password)
|
||||
|
||||
|
||||
def verify_password(password: str, password_hash: str) -> bool:
|
||||
try:
|
||||
_hasher.verify(password_hash, password)
|
||||
return True
|
||||
except (VerifyMismatchError, VerificationError, InvalidHashError):
|
||||
return False
|
||||
|
||||
|
||||
def _now() -> datetime:
|
||||
return datetime.now(timezone.utc)
|
||||
|
||||
|
||||
def _ttl_seconds() -> int:
|
||||
return int(os.environ.get("SESSION_TTL_SECONDS", "3600"))
|
||||
|
||||
|
||||
def _generate_token() -> str:
|
||||
return secrets.token_urlsafe(32)
|
||||
|
||||
|
||||
def _token_hash(token: str) -> str:
|
||||
return hashlib.sha256(token.encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
def create_session(user_id: str) -> dict:
|
||||
token = _generate_token()
|
||||
expires_at = _now() + timedelta(seconds=_ttl_seconds())
|
||||
with transaction() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO sessions (token_hash, user_id, expires_at, created_at)
|
||||
VALUES (%s, %s, %s, %s)
|
||||
""",
|
||||
(_token_hash(token), user_id, expires_at, _now()),
|
||||
)
|
||||
return {"token": token, "expires_at": expires_at}
|
||||
|
||||
|
||||
def get_user_id_by_token(token: str) -> Optional[str]:
|
||||
with transaction() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT user_id, expires_at
|
||||
FROM sessions
|
||||
WHERE token_hash = %s
|
||||
""",
|
||||
(_token_hash(token),),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if row is None:
|
||||
return None
|
||||
if row["expires_at"] <= _now():
|
||||
return None
|
||||
return str(row["user_id"])
|
||||
|
||||
|
||||
def revoke_session(token: str) -> bool:
|
||||
with transaction() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"DELETE FROM sessions WHERE token_hash = %s",
|
||||
(_token_hash(token),),
|
||||
)
|
||||
return cur.rowcount > 0
|
||||
@@ -0,0 +1,55 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from contextlib import contextmanager
|
||||
from typing import Iterator
|
||||
|
||||
import psycopg
|
||||
from psycopg.rows import dict_row
|
||||
from psycopg_pool import ConnectionPool
|
||||
|
||||
|
||||
_pool: ConnectionPool | None = None
|
||||
|
||||
|
||||
def _database_url() -> str:
|
||||
url = os.environ.get("DATABASE_URL")
|
||||
if not url:
|
||||
raise RuntimeError("DATABASE_URL environment variable is required")
|
||||
return url
|
||||
|
||||
|
||||
def init_pool(min_size: int = 1, max_size: int = 10) -> None:
|
||||
global _pool
|
||||
if _pool is not None:
|
||||
return
|
||||
_pool = ConnectionPool(
|
||||
conninfo=_database_url(),
|
||||
min_size=min_size,
|
||||
max_size=max_size,
|
||||
kwargs={"row_factory": dict_row},
|
||||
open=True,
|
||||
timeout=5.0,
|
||||
)
|
||||
|
||||
|
||||
def close_pool() -> None:
|
||||
global _pool
|
||||
if _pool is not None:
|
||||
_pool.close()
|
||||
_pool = None
|
||||
|
||||
|
||||
@contextmanager
|
||||
def connection() -> Iterator[psycopg.Connection]:
|
||||
if _pool is None:
|
||||
raise RuntimeError("Connection pool is not initialized")
|
||||
with _pool.connection() as conn:
|
||||
yield conn
|
||||
|
||||
|
||||
@contextmanager
|
||||
def transaction() -> Iterator[psycopg.Connection]:
|
||||
with connection() as conn:
|
||||
with conn.transaction():
|
||||
yield conn
|
||||
Executable
+65
@@ -0,0 +1,65 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from typing import Callable
|
||||
|
||||
from fastapi import Request
|
||||
from fastapi.responses import JSONResponse
|
||||
from starlette.middleware.base import BaseHTTPMiddleware
|
||||
|
||||
from .store import ApiError
|
||||
|
||||
|
||||
REQUEST_ID_HEADER = "X-Request-Id"
|
||||
|
||||
|
||||
class RequestIdMiddleware(BaseHTTPMiddleware):
|
||||
async def dispatch(self, request: Request, call_next: Callable):
|
||||
rid = request.headers.get(REQUEST_ID_HEADER) or uuid.uuid4().hex
|
||||
request.state.request_id = rid
|
||||
response = await call_next(request)
|
||||
response.headers[REQUEST_ID_HEADER] = rid
|
||||
return response
|
||||
|
||||
|
||||
def _envelope(code: str, message: str, request_id: str) -> dict:
|
||||
return {"error": {"code": code, "message": message, "request_id": request_id}}
|
||||
|
||||
|
||||
def _rid(request: Request) -> str:
|
||||
return getattr(request.state, "request_id", None) or uuid.uuid4().hex
|
||||
|
||||
|
||||
async def api_error_handler(request: Request, exc: Exception) -> JSONResponse:
|
||||
assert isinstance(exc, ApiError)
|
||||
response = JSONResponse(
|
||||
status_code=exc.status,
|
||||
content=_envelope(exc.code, exc.message, _rid(request)),
|
||||
)
|
||||
if exc.status == 401:
|
||||
scheme = "Bearer"
|
||||
if request.url.path == "/api/v1/auth/sessions":
|
||||
scheme = "Basic"
|
||||
response.headers["WWW-Authenticate"] = f'{scheme} realm="messenger"'
|
||||
return response
|
||||
|
||||
|
||||
async def validation_handler(request: Request, exc: Exception) -> JSONResponse:
|
||||
return JSONResponse(
|
||||
status_code=400,
|
||||
content=_envelope("invalid_request", "Request validation failed", _rid(request)),
|
||||
)
|
||||
|
||||
|
||||
async def json_decode_handler(request: Request, exc: Exception) -> JSONResponse:
|
||||
return JSONResponse(
|
||||
status_code=400,
|
||||
content=_envelope("invalid_request", "Malformed JSON", _rid(request)),
|
||||
)
|
||||
|
||||
|
||||
async def unhandled_handler(request: Request, exc: Exception) -> JSONResponse:
|
||||
return JSONResponse(
|
||||
status_code=500,
|
||||
content=_envelope("internal_error", "Internal error", _rid(request)),
|
||||
)
|
||||
Executable
+236
@@ -0,0 +1,236 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
from contextlib import asynccontextmanager
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import Depends, FastAPI, Header, Query, Request, Response
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from fastapi.responses import JSONResponse
|
||||
from starlette.exceptions import HTTPException as StarletteHTTPException
|
||||
|
||||
from . import auth
|
||||
from .db import close_pool, init_pool
|
||||
from .errors import (
|
||||
RequestIdMiddleware,
|
||||
_envelope,
|
||||
_rid,
|
||||
api_error_handler,
|
||||
json_decode_handler,
|
||||
unhandled_handler,
|
||||
validation_handler,
|
||||
)
|
||||
from .schemas import (
|
||||
Chat,
|
||||
ChatPage,
|
||||
CreateChat,
|
||||
CreateMessage,
|
||||
CreateUser,
|
||||
Health,
|
||||
Message,
|
||||
MessagePage,
|
||||
Session,
|
||||
User,
|
||||
)
|
||||
from .store import ApiError, BadRequest, Conflict, NotFound, Unauthorized, store, iso
|
||||
|
||||
logging.basicConfig(
|
||||
level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s"
|
||||
)
|
||||
log = logging.getLogger("messenger")
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
init_pool()
|
||||
log.info("db pool initialized")
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
close_pool()
|
||||
log.info("db pool closed")
|
||||
|
||||
|
||||
app = FastAPI(title="MTUSI Messenger lab2", version="1.2.0", lifespan=lifespan)
|
||||
app.add_middleware(RequestIdMiddleware)
|
||||
|
||||
app.add_exception_handler(ApiError, api_error_handler)
|
||||
app.add_exception_handler(RequestValidationError, validation_handler)
|
||||
app.add_exception_handler(Exception, unhandled_handler)
|
||||
|
||||
|
||||
@app.exception_handler(StarletteHTTPException)
|
||||
async def _http_exc(request: Request, exc: StarletteHTTPException):
|
||||
code = "not_found" if exc.status_code == 404 else "invalid_request"
|
||||
return JSONResponse(
|
||||
status_code=exc.status_code,
|
||||
content=_envelope(code, str(exc.detail), _rid(request)),
|
||||
)
|
||||
|
||||
|
||||
# ---------- зависимости ----------
|
||||
|
||||
def _parse_basic(header_value: str) -> tuple[str, str]:
|
||||
"""Разбирает `Basic base64(username:password)`. Бросает Unauthorized."""
|
||||
import base64
|
||||
if not header_value.lower().startswith("basic "):
|
||||
raise Unauthorized("Basic authentication required")
|
||||
try:
|
||||
raw = base64.b64decode(header_value.split(" ", 1)[1], validate=True)
|
||||
decoded = raw.decode("utf-8")
|
||||
username, _, password = decoded.partition(":")
|
||||
if not username:
|
||||
raise ValueError("empty username")
|
||||
return username, password
|
||||
except Exception:
|
||||
raise Unauthorized("Invalid Basic credentials") from None
|
||||
|
||||
|
||||
def _bearer_token(authorization: Optional[str]) -> str:
|
||||
if not authorization:
|
||||
raise Unauthorized("Missing Authorization header")
|
||||
parts = authorization.split(" ", 1)
|
||||
if len(parts) != 2 or parts[0].lower() != "bearer":
|
||||
raise Unauthorized("Bearer token required")
|
||||
token = parts[1].strip()
|
||||
if not token:
|
||||
raise Unauthorized("Empty bearer token")
|
||||
return token
|
||||
|
||||
|
||||
def current_user_id(
|
||||
authorization: Optional[str] = Header(default=None),
|
||||
) -> str:
|
||||
token = _bearer_token(authorization)
|
||||
user_id = auth.get_user_id_by_token(token)
|
||||
if user_id is None:
|
||||
raise Unauthorized("Invalid or expired token")
|
||||
return user_id
|
||||
|
||||
|
||||
# ---------- health ----------
|
||||
|
||||
@app.get("/health/live", response_model=Health)
|
||||
def liveness():
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
@app.get("/health/ready", response_model=Health)
|
||||
def readiness():
|
||||
try:
|
||||
from .db import transaction
|
||||
with transaction() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute("SELECT 1")
|
||||
except Exception:
|
||||
return JSONResponse(
|
||||
status_code=503,
|
||||
content=_envelope("unavailable", "Database unavailable", "readiness"),
|
||||
)
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
# ---------- users ----------
|
||||
|
||||
@app.post("/api/v1/users", status_code=201, response_model=User)
|
||||
def register_user(body: CreateUser):
|
||||
password_hash = auth.hash_password(body.password)
|
||||
return store.create_user(body.username, body.display_name, password_hash)
|
||||
|
||||
|
||||
@app.get("/api/v1/users/me", response_model=User)
|
||||
def me(user_id: str = Depends(current_user_id)):
|
||||
user = store.get_user(user_id)
|
||||
if user is None:
|
||||
raise Unauthorized("User not found")
|
||||
return user
|
||||
|
||||
|
||||
# ---------- auth ----------
|
||||
|
||||
@app.post("/api/v1/auth/sessions", status_code=201, response_model=Session)
|
||||
def create_session(authorization: Optional[str] = Header(default=None)):
|
||||
username, password = _parse_basic(authorization or "")
|
||||
row = store.get_user_by_username(username)
|
||||
if row is None or not auth.verify_password(password, row["password_hash"]):
|
||||
raise Unauthorized("Invalid credentials")
|
||||
session = auth.create_session(str(row["id"]))
|
||||
user = store.get_user(str(row["id"]))
|
||||
if user is None:
|
||||
raise Unauthorized("User not found")
|
||||
return {
|
||||
"token": session["token"],
|
||||
"token_type": "Bearer",
|
||||
"expires_at": iso(session["expires_at"]),
|
||||
"user": user,
|
||||
}
|
||||
|
||||
|
||||
@app.delete("/api/v1/auth/sessions/current", status_code=204)
|
||||
def logout(authorization: Optional[str] = Header(default=None)):
|
||||
token = _bearer_token(authorization)
|
||||
user_id = auth.get_user_id_by_token(token)
|
||||
if user_id is None:
|
||||
raise Unauthorized("Invalid or expired token")
|
||||
auth.revoke_session(token)
|
||||
return Response(status_code=204)
|
||||
|
||||
|
||||
# ---------- chats ----------
|
||||
|
||||
@app.post("/api/v1/chats", status_code=201, response_model=Chat)
|
||||
def create_chat(body: CreateChat, user_id: str = Depends(current_user_id)):
|
||||
return store.create_chat(body.title, body.member_ids, user_id)
|
||||
|
||||
|
||||
@app.get("/api/v1/chats", response_model=ChatPage)
|
||||
def list_chats(
|
||||
limit: int = Query(default=50, ge=1, le=100),
|
||||
cursor: Optional[str] = Query(default=None, min_length=1),
|
||||
user_id: str = Depends(current_user_id),
|
||||
):
|
||||
items, next_cursor = store.list_chats(user_id, limit, cursor)
|
||||
return {"items": items, "next_cursor": next_cursor}
|
||||
|
||||
|
||||
@app.get("/api/v1/chats/{chat_id}", response_model=Chat)
|
||||
def get_chat(chat_id: str, user_id: str = Depends(current_user_id)):
|
||||
chat = store.get_chat(chat_id, user_id)
|
||||
if chat is None:
|
||||
raise NotFound()
|
||||
return chat
|
||||
|
||||
|
||||
# ---------- messages ----------
|
||||
|
||||
@app.post(
|
||||
"/api/v1/chats/{chat_id}/messages", status_code=201, response_model=Message
|
||||
)
|
||||
def create_message(
|
||||
chat_id: str, body: CreateMessage, user_id: str = Depends(current_user_id)
|
||||
):
|
||||
return store.add_message(chat_id, user_id, body.text)
|
||||
|
||||
|
||||
@app.get("/api/v1/chats/{chat_id}/messages", response_model=MessagePage)
|
||||
def list_messages(
|
||||
chat_id: str,
|
||||
limit: int = Query(default=50, ge=1, le=100),
|
||||
cursor: Optional[str] = Query(default=None, min_length=1),
|
||||
user_id: str = Depends(current_user_id),
|
||||
):
|
||||
items, next_cursor = store.list_messages(chat_id, user_id, limit, cursor)
|
||||
return {"items": items, "next_cursor": next_cursor}
|
||||
|
||||
|
||||
def main() -> None:
|
||||
import uvicorn
|
||||
|
||||
host = os.environ.get("APP_HOST", "0.0.0.0")
|
||||
port = int(os.environ.get("APP_PORT", "8080"))
|
||||
uvicorn.run("src.main:app", host=host, port=port, log_level="info")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Executable
+135
@@ -0,0 +1,135 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import uuid
|
||||
from typing import List, Optional
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field, field_validator
|
||||
|
||||
USERNAME_RE = re.compile(r"^[a-z0-9_]{3,32}$")
|
||||
|
||||
|
||||
class StrictModel(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid", str_strip_whitespace=False)
|
||||
|
||||
|
||||
# ---------- Users ----------
|
||||
|
||||
class CreateUser(StrictModel):
|
||||
username: str = Field(min_length=3, max_length=32)
|
||||
display_name: str = Field(min_length=1, max_length=100)
|
||||
password: str = Field(min_length=12, max_length=128)
|
||||
|
||||
@field_validator("username")
|
||||
@classmethod
|
||||
def _username(cls, v: str) -> str:
|
||||
if not USERNAME_RE.match(v):
|
||||
raise ValueError("username must match [a-z0-9_]{3,32}")
|
||||
return v
|
||||
|
||||
@field_validator("display_name")
|
||||
@classmethod
|
||||
def _display_name(cls, v: str) -> str:
|
||||
if not v.strip():
|
||||
raise ValueError("display_name must not be blank")
|
||||
if len(v) > 100:
|
||||
raise ValueError("display_name too long")
|
||||
return v
|
||||
|
||||
|
||||
class User(StrictModel):
|
||||
id: str
|
||||
username: str
|
||||
display_name: str
|
||||
created_at: str
|
||||
|
||||
|
||||
# ---------- Chats ----------
|
||||
|
||||
class CreateChat(StrictModel):
|
||||
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(cls, v: str) -> str:
|
||||
if not v.strip():
|
||||
raise ValueError("title must not be blank")
|
||||
return v
|
||||
|
||||
@field_validator("member_ids")
|
||||
@classmethod
|
||||
def _members(cls, v: List[str]) -> List[str]:
|
||||
if len(set(v)) != len(v):
|
||||
raise ValueError("member_ids must be unique")
|
||||
for item in v:
|
||||
try:
|
||||
uuid.UUID(item)
|
||||
except ValueError as exc:
|
||||
raise ValueError("member_ids must be UUIDs") from exc
|
||||
return v
|
||||
|
||||
|
||||
class Chat(StrictModel):
|
||||
id: str
|
||||
title: str
|
||||
member_ids: List[str]
|
||||
created_at: str
|
||||
|
||||
|
||||
class ChatPage(StrictModel):
|
||||
items: List[Chat]
|
||||
next_cursor: Optional[str] = None
|
||||
|
||||
|
||||
# ---------- Messages ----------
|
||||
|
||||
class CreateMessage(StrictModel):
|
||||
text: str = Field(min_length=1, max_length=4000)
|
||||
|
||||
@field_validator("text")
|
||||
@classmethod
|
||||
def _text(cls, v: str) -> str:
|
||||
if not v.strip():
|
||||
raise ValueError("text must not be blank")
|
||||
if len(v) > 4000:
|
||||
raise ValueError("text too long")
|
||||
return v
|
||||
|
||||
|
||||
class Message(StrictModel):
|
||||
id: str
|
||||
chat_id: str
|
||||
sender_id: str
|
||||
text: str
|
||||
created_at: str
|
||||
|
||||
|
||||
class MessagePage(StrictModel):
|
||||
items: List[Message]
|
||||
next_cursor: Optional[str] = None
|
||||
|
||||
|
||||
# ---------- Sessions ----------
|
||||
|
||||
class Session(StrictModel):
|
||||
token: str = Field(min_length=32)
|
||||
token_type: str = Field(default="Bearer")
|
||||
expires_at: str
|
||||
user: User
|
||||
|
||||
|
||||
# ---------- Misc ----------
|
||||
|
||||
class Health(StrictModel):
|
||||
status: str = "ok"
|
||||
|
||||
|
||||
class ErrorBody(StrictModel):
|
||||
code: str
|
||||
message: str
|
||||
request_id: str
|
||||
|
||||
|
||||
class ErrorEnvelope(StrictModel):
|
||||
error: ErrorBody
|
||||
Executable
+332
@@ -0,0 +1,332 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import json
|
||||
import uuid
|
||||
from datetime import datetime, timezone
|
||||
from typing import List, Optional, Tuple
|
||||
|
||||
import psycopg
|
||||
from psycopg.errors import UniqueViolation
|
||||
|
||||
from .db import transaction
|
||||
|
||||
|
||||
# ---------- ошибки ----------
|
||||
|
||||
class ApiError(Exception):
|
||||
status = 500
|
||||
code = "internal_error"
|
||||
|
||||
def __init__(self, message: str = "Internal error") -> None:
|
||||
super().__init__(message)
|
||||
self.message = message
|
||||
|
||||
|
||||
class BadRequest(ApiError):
|
||||
status = 400
|
||||
code = "invalid_request"
|
||||
|
||||
|
||||
class Unauthorized(ApiError):
|
||||
status = 401
|
||||
code = "unauthorized"
|
||||
|
||||
|
||||
class NotFound(ApiError):
|
||||
status = 404
|
||||
code = "not_found"
|
||||
|
||||
|
||||
class Conflict(ApiError):
|
||||
status = 409
|
||||
code = "conflict"
|
||||
|
||||
|
||||
# ---------- утилиты ----------
|
||||
|
||||
def _now() -> datetime:
|
||||
return datetime.now(timezone.utc)
|
||||
|
||||
|
||||
def iso(dt: datetime) -> str:
|
||||
return dt.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%fZ")
|
||||
|
||||
|
||||
def _user_dict(row: dict) -> dict:
|
||||
return {
|
||||
"id": str(row["id"]),
|
||||
"username": row["username"],
|
||||
"display_name": row["display_name"],
|
||||
"created_at": iso(row["created_at"]),
|
||||
}
|
||||
|
||||
|
||||
def _chat_dict(row: dict, member_ids: List[str]) -> dict:
|
||||
return {
|
||||
"id": str(row["id"]),
|
||||
"title": row["title"],
|
||||
"member_ids": member_ids,
|
||||
"created_at": iso(row["created_at"]),
|
||||
}
|
||||
|
||||
|
||||
def _message_dict(row: dict) -> dict:
|
||||
return {
|
||||
"id": str(row["id"]),
|
||||
"chat_id": str(row["chat_id"]),
|
||||
"sender_id": str(row["sender_id"]),
|
||||
"text": row["text"],
|
||||
"created_at": iso(row["created_at"]),
|
||||
}
|
||||
|
||||
|
||||
# ---------- курсор ----------
|
||||
|
||||
def _encode_cursor(scope: str, created_at: str, item_id: str) -> str:
|
||||
payload = json.dumps(
|
||||
{"s": scope, "t": created_at, "i": item_id}, separators=(",", ":")
|
||||
).encode()
|
||||
return base64.urlsafe_b64encode(payload).decode().rstrip("=")
|
||||
|
||||
|
||||
def _decode_cursor(scope: str, cursor: str) -> Tuple[str, str]:
|
||||
pad = "=" * (-len(cursor) % 4)
|
||||
try:
|
||||
raw = base64.urlsafe_b64decode(cursor + pad)
|
||||
data = json.loads(raw)
|
||||
if data.get("s") != scope:
|
||||
raise ValueError("scope mismatch")
|
||||
return data["t"], data["i"]
|
||||
except Exception as exc:
|
||||
raise BadRequest("invalid cursor") from exc
|
||||
|
||||
|
||||
# ---------- Store ----------
|
||||
|
||||
class Store:
|
||||
|
||||
# ---- users ----
|
||||
|
||||
def create_user(
|
||||
self, username: str, display_name: str, password_hash: str
|
||||
) -> dict:
|
||||
uid = str(uuid.uuid4())
|
||||
now = _now()
|
||||
try:
|
||||
with transaction() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO users (id, username, display_name, password_hash, created_at)
|
||||
VALUES (%s, %s, %s, %s, %s)
|
||||
""",
|
||||
(uid, username, display_name, password_hash, now),
|
||||
)
|
||||
except UniqueViolation:
|
||||
raise Conflict("username already taken") from None
|
||||
return {
|
||||
"id": uid,
|
||||
"username": username,
|
||||
"display_name": display_name,
|
||||
"created_at": iso(now),
|
||||
}
|
||||
|
||||
def get_user(self, user_id: str) -> Optional[dict]:
|
||||
with transaction() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute("SELECT * FROM users WHERE id = %s", (user_id,))
|
||||
row = cur.fetchone()
|
||||
return _user_dict(row) if row else None
|
||||
|
||||
def get_user_by_username(self, username: str) -> Optional[dict]:
|
||||
"""Возвращает полную строку, включая password_hash (для входа)."""
|
||||
with transaction() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute("SELECT * FROM users WHERE username = %s", (username,))
|
||||
row = cur.fetchone()
|
||||
return row
|
||||
|
||||
# ---- chats ----
|
||||
|
||||
def create_chat(
|
||||
self, title: str, member_ids: List[str], creator_id: str
|
||||
) -> dict:
|
||||
if creator_id not in member_ids:
|
||||
raise BadRequest("creator must be in member_ids")
|
||||
|
||||
with transaction() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"SELECT id FROM users WHERE id = ANY(%s)",
|
||||
(member_ids,),
|
||||
)
|
||||
found = {str(r["id"]) for r in cur.fetchall()}
|
||||
missing = set(member_ids) - found
|
||||
if missing:
|
||||
raise BadRequest("unknown member_id")
|
||||
|
||||
cid = str(uuid.uuid4())
|
||||
now = _now()
|
||||
with transaction() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"INSERT INTO chats (id, title, created_at) VALUES (%s, %s, %s)",
|
||||
(cid, title, now),
|
||||
)
|
||||
cur.executemany(
|
||||
"INSERT INTO chat_members (chat_id, user_id) VALUES (%s, %s)",
|
||||
[(cid, uid) for uid in member_ids],
|
||||
)
|
||||
return {
|
||||
"id": cid,
|
||||
"title": title,
|
||||
"member_ids": list(member_ids),
|
||||
"created_at": iso(now),
|
||||
}
|
||||
|
||||
def get_chat(self, chat_id: str, viewer_id: str) -> Optional[dict]:
|
||||
with transaction() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT c.* FROM chats c
|
||||
JOIN chat_members m ON m.chat_id = c.id
|
||||
WHERE c.id = %s AND m.user_id = %s
|
||||
""",
|
||||
(chat_id, viewer_id),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if row is None:
|
||||
return None
|
||||
cur.execute(
|
||||
"SELECT user_id FROM chat_members WHERE chat_id = %s ORDER BY user_id",
|
||||
(chat_id,),
|
||||
)
|
||||
members = [str(r["user_id"]) for r in cur.fetchall()]
|
||||
return _chat_dict(row, members)
|
||||
|
||||
def list_chats(
|
||||
self, viewer_id: str, limit: int, cursor: Optional[str]
|
||||
) -> Tuple[List[dict], Optional[str]]:
|
||||
scope = "chats:" + viewer_id
|
||||
params: list = [viewer_id]
|
||||
where_cursor = ""
|
||||
if cursor:
|
||||
t, i = _decode_cursor(scope, cursor)
|
||||
where_cursor = "AND (c.created_at, c.id) > (%s, %s)"
|
||||
params.extend([t, i])
|
||||
params.append(limit + 1) # +1, чтобы узнать, есть ли следующая страница
|
||||
|
||||
with transaction() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
f"""
|
||||
SELECT c.id, c.title, c.created_at
|
||||
FROM chats c
|
||||
JOIN chat_members m ON m.chat_id = c.id
|
||||
WHERE m.user_id = %s {where_cursor}
|
||||
ORDER BY c.created_at, c.id
|
||||
LIMIT %s
|
||||
""",
|
||||
params,
|
||||
)
|
||||
rows = cur.fetchall()
|
||||
|
||||
has_more = len(rows) > limit
|
||||
page = rows[:limit]
|
||||
|
||||
result = []
|
||||
for row in page:
|
||||
cur.execute(
|
||||
"SELECT user_id FROM chat_members WHERE chat_id = %s ORDER BY user_id",
|
||||
(row["id"],),
|
||||
)
|
||||
members = [str(r["user_id"]) for r in cur.fetchall()]
|
||||
result.append(_chat_dict(row, members))
|
||||
|
||||
next_cursor = None
|
||||
if has_more and page:
|
||||
last = page[-1]
|
||||
next_cursor = _encode_cursor(scope, iso(last["created_at"]), str(last["id"]))
|
||||
return result, next_cursor
|
||||
|
||||
# ---- messages ----
|
||||
|
||||
def add_message(self, chat_id: str, sender_id: str, text: str) -> dict:
|
||||
mid = str(uuid.uuid4())
|
||||
now = _now()
|
||||
with transaction() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"SELECT 1 FROM chat_members WHERE chat_id = %s AND user_id = %s",
|
||||
(chat_id, sender_id),
|
||||
)
|
||||
if cur.fetchone() is None:
|
||||
raise NotFound()
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
|
||||
VALUES (%s, %s, %s, %s, %s)
|
||||
""",
|
||||
(mid, chat_id, sender_id, text, now),
|
||||
)
|
||||
return {
|
||||
"id": mid,
|
||||
"chat_id": chat_id,
|
||||
"sender_id": sender_id,
|
||||
"text": text,
|
||||
"created_at": iso(now),
|
||||
}
|
||||
|
||||
def list_messages(
|
||||
self,
|
||||
chat_id: str,
|
||||
viewer_id: str,
|
||||
limit: int,
|
||||
cursor: Optional[str],
|
||||
) -> Tuple[List[dict], Optional[str]]:
|
||||
with transaction() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"SELECT 1 FROM chat_members WHERE chat_id = %s AND user_id = %s",
|
||||
(chat_id, viewer_id),
|
||||
)
|
||||
if cur.fetchone() is None:
|
||||
raise NotFound()
|
||||
|
||||
scope = "chat:" + chat_id
|
||||
params: list = [chat_id]
|
||||
where_cursor = ""
|
||||
if cursor:
|
||||
t, i = _decode_cursor(scope, cursor)
|
||||
where_cursor = "AND (created_at, id) > (%s, %s)"
|
||||
params.extend([t, i])
|
||||
params.append(limit + 1)
|
||||
|
||||
with transaction() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
f"""
|
||||
SELECT id, chat_id, sender_id, text, created_at
|
||||
FROM messages
|
||||
WHERE chat_id = %s {where_cursor}
|
||||
ORDER BY created_at, id
|
||||
LIMIT %s
|
||||
""",
|
||||
params,
|
||||
)
|
||||
rows = cur.fetchall()
|
||||
|
||||
has_more = len(rows) > limit
|
||||
page = rows[:limit]
|
||||
result = [_message_dict(r) for r in page]
|
||||
|
||||
next_cursor = None
|
||||
if has_more and page:
|
||||
last = page[-1]
|
||||
next_cursor = _encode_cursor(scope, iso(last["created_at"]), str(last["id"]))
|
||||
return result, next_cursor
|
||||
|
||||
|
||||
store = Store()
|
||||
Reference in New Issue
Block a user