main.py на PostgreSQL и Bearer-аутентификацию

This commit is contained in:
2026-10-01 00:34:58 +03:00
parent c4fc878861
commit c2672b4cac
2 changed files with 193 additions and 219 deletions
+193 -85
View File
@@ -1,23 +1,52 @@
import os import os
import uuid import uuid
from contextvars import ContextVar from contextvars import ContextVar
from datetime import datetime, timedelta, timezone
from typing import Optional from typing import Optional
from uuid import UUID
from fastapi import Depends, FastAPI, Header, HTTPException, Query, Request from fastapi import Depends, FastAPI, Header, HTTPException, Query, Request
from fastapi.exceptions import RequestValidationError from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse from fastapi.responses import JSONResponse
from fastapi.security import HTTPBasic, HTTPBasicCredentials
from sqlalchemy import text
from sqlalchemy.ext.asyncio import AsyncSession
from starlette.middleware.base import BaseHTTPMiddleware from starlette.middleware.base import BaseHTTPMiddleware
from .auth import (
SESSION_TTL,
generate_token,
get_current_user,
hash_password,
hash_token,
revoke_current_session,
verify_password,
)
from .db.models import SessionRow, User
from .db.session import get_db
from .models import CreateChat, CreateMessage, CreateUser from .models import CreateChat, CreateMessage, CreateUser
from .storage import storage from .repositories import chats as chats_repo
from .repositories import messages as messages_repo
from .repositories import users as users_repo
request_id_var: ContextVar[str] = ContextVar("request_id", default="") request_id_var: ContextVar[str] = ContextVar("request_id", default="")
_HTTP_CODES = {
400: "invalid_request",
401: "unauthorized",
404: "not_found",
409: "conflict",
413: "payload_too_large",
415: "unsupported_media_type",
429: "rate_limited",
503: "unavailable",
500: "internal_error",
}
def err(status_code: int, code: str, message: str) -> JSONResponse:
def err_json(status: int, code: str, message: str) -> JSONResponse:
return JSONResponse( return JSONResponse(
status_code=status_code, status_code=status,
content={ content={
"error": { "error": {
"code": code, "code": code,
@@ -37,146 +66,225 @@ class RequestIdMiddleware(BaseHTTPMiddleware):
return response return response
app = FastAPI(title="MTUSI Messenger — lab1") app = FastAPI(title="MTUSI Messenger — lab2")
app.add_middleware(RequestIdMiddleware) app.add_middleware(RequestIdMiddleware)
security = HTTPBasic(auto_error=False)
# ---------- exception handlers ----------
_HTTP_CODES = {
400: "invalid_request",
401: "unauthorized",
404: "not_found",
409: "conflict",
413: "payload_too_large",
415: "unsupported_media_type",
429: "rate_limited",
503: "unavailable",
500: "internal_error",
}
@app.exception_handler(RequestValidationError) @app.exception_handler(RequestValidationError)
async def _validation_handler(request: Request, exc: RequestValidationError): async def _validation(request: Request, exc: RequestValidationError):
# пустое сообщение, limit=0, чужой json и т.п. return err_json(400, "invalid_request", "Validation error")
return err(400, "invalid_request", "Validation error")
@app.exception_handler(HTTPException) @app.exception_handler(HTTPException)
async def _http_handler(request: Request, exc: HTTPException): async def _http(request: Request, exc: HTTPException):
code = _HTTP_CODES.get(exc.status_code, "internal_error") code = _HTTP_CODES.get(exc.status_code, "internal_error")
message = exc.detail if isinstance(exc.detail, str) and exc.detail else "Error" detail = exc.detail if isinstance(exc.detail, str) else "Error"
return err(exc.status_code, code, message) resp = err_json(exc.status_code, code, detail)
if exc.headers:
for k, v in exc.headers.items():
resp.headers[k] = v
return resp
@app.exception_handler(Exception) @app.exception_handler(Exception)
async def _generic_handler(request: Request, exc: Exception): async def _generic(request: Request, exc: Exception):
# ноль деталей -> ошибка return err_json(500, "internal_error", "Internal server error")
return err(500, "internal_error", "Internal server error")
# dependency def _iso_z(dt: datetime) -> str:
return dt.isoformat().replace("+00:00", "Z")
def get_actor(x_user_id: Optional[str] = Header(None, alias="X-User-Id")) -> dict:
if not x_user_id:
raise HTTPException(401, "Unauthorized")
user = storage.get_user(x_user_id)
if user is None:
raise HTTPException(401, "Unauthorized")
return user
# health def _user_json(u: User) -> dict:
return {
"id": str(u.id),
"username": u.username,
"display_name": u.display_name,
"created_at": _iso_z(u.created_at),
}
def _chat_json(chat, member_ids: list[str]) -> dict:
return {
"id": str(chat.id),
"title": chat.title,
"member_ids": member_ids,
"created_at": _iso_z(chat.created_at),
}
def _msg_json(m) -> dict:
return {
"id": str(m.id),
"chat_id": str(m.chat_id),
"sender_id": str(m.sender_id),
"text": m.text,
"created_at": _iso_z(m.created_at),
}
# ---------- health ----------
@app.get("/health/live") @app.get("/health/live")
def health_live(): def live():
return {"status": "ok"} return {"status": "ok"}
@app.get("/health/ready") @app.get("/health/ready")
def health_ready(): async def ready(db: AsyncSession = Depends(get_db)):
try:
await db.execute(text("SELECT 1"))
except Exception:
return err_json(503, "unavailable", "Database unavailable")
return {"status": "ok"} return {"status": "ok"}
# users # ---------- users ----------
@app.post("/api/v1/users", status_code=201) @app.post("/api/v1/users", status_code=201)
def create_user(body: CreateUser): async def register(body: CreateUser, db: AsyncSession = Depends(get_db)):
user = storage.create_user(body.username, body.display_name) existing = await users_repo.get_by_username(db, body.username)
if user is None: if existing is not None:
raise HTTPException(409, "Username already exists") raise HTTPException(409, "Username already exists")
return user try:
user = await users_repo.create(
db, body.username, body.display_name, hash_password(body.password)
)
except Exception:
raise HTTPException(409, "Username already exists")
return _user_json(user)
# ---------- sessions ----------
@app.post("/api/v1/auth/sessions", status_code=201)
async def login(
creds: Optional[HTTPBasicCredentials] = Depends(security),
db: AsyncSession = Depends(get_db),
):
basic_challenge = 'Basic realm="messenger", charset="UTF-8"'
if creds is None:
raise HTTPException(
status_code=401, detail="Unauthorized", headers={"WWW-Authenticate": basic_challenge}
)
user = await users_repo.get_by_username(db, creds.username)
if user is None or not verify_password(creds.password, user.password_hash):
raise HTTPException(
status_code=401, detail="Unauthorized", headers={"WWW-Authenticate": basic_challenge}
)
token = generate_token()
expires = datetime.now(timezone.utc) + timedelta(seconds=SESSION_TTL)
db.add(
SessionRow(user_id=user.id, token_hash=hash_token(token), expires_at=expires)
)
await db.commit()
return {
"token": token,
"token_type": "Bearer",
"expires_at": _iso_z(expires),
"user": _user_json(user),
}
@app.delete("/api/v1/auth/sessions/current", status_code=204)
async def logout(authorization: str = Header(...), db: AsyncSession = Depends(get_db)):
await revoke_current_session(authorization, db)
@app.get("/api/v1/users/me") @app.get("/api/v1/users/me")
def current_user(actor: dict = Depends(get_actor)): async def me(user: User = Depends(get_current_user)):
return actor return _user_json(user)
# chats # ---------- chats ----------
@app.post("/api/v1/chats", status_code=201) @app.post("/api/v1/chats", status_code=201)
def create_chat(body: CreateChat, actor: dict = Depends(get_actor)): async def create_chat(
if actor["id"] not in body.member_ids: body: CreateChat,
user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db),
):
if user.id not in body.member_ids:
raise HTTPException(400, "Caller must be in member_ids") raise HTTPException(400, "Caller must be in member_ids")
chat, error = storage.create_chat(body.title, body.member_ids, actor["id"]) try:
if error == "member_not_found": chat = await chats_repo.create_atomic(db, body.title, body.member_ids)
except ValueError:
raise HTTPException(404, "Member not found") raise HTTPException(404, "Member not found")
if error: return _chat_json(chat, [str(x) for x in body.member_ids])
raise HTTPException(400, error)
return chat
@app.get("/api/v1/chats") @app.get("/api/v1/chats")
def list_chats( async def list_chats(
actor: dict = Depends(get_actor), user: User = Depends(get_current_user),
limit: int = Query(50, ge=1, le=100), limit: int = Query(50, ge=1, le=100),
cursor: Optional[str] = Query(None, min_length=1), cursor: Optional[str] = Query(None, min_length=1),
db: AsyncSession = Depends(get_db),
): ):
items, next_cursor = storage.list_chats(actor["id"], limit, cursor) parsed = None
return {"items": items, "next_cursor": next_cursor} if cursor is not None:
try:
c_created, c_id = cursor.split("|", 1)
parsed = (datetime.fromisoformat(c_created), UUID(c_id))
except Exception:
raise HTTPException(400, "Invalid cursor")
rows, next_cursor = await chats_repo.list_for_user(db, user.id, limit, parsed)
items = []
for chat in rows:
members = await chats_repo.list_member_ids(db, chat.id)
items.append(_chat_json(chat, [str(m) for m in members]))
nxt = f"{next_cursor[0].isoformat()}|{next_cursor[1]}" if next_cursor else None
return {"items": items, "next_cursor": nxt}
@app.get("/api/v1/chats/{chat_id}") @app.get("/api/v1/chats/{chat_id}")
def get_chat(chat_id: str, actor: dict = Depends(get_actor)): async def get_chat(
chat = storage.get_chat(chat_id, actor["id"]) chat_id: UUID,
user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db),
):
chat = await chats_repo.get_if_member(db, chat_id, user.id)
if chat is None: if chat is None:
raise HTTPException(404, "Chat not found") raise HTTPException(404, "Chat not found")
return chat members = await chats_repo.list_member_ids(db, chat.id)
return _chat_json(chat, [str(m) for m in members])
# messages # ---------- messages ----------
@app.post("/api/v1/chats/{chat_id}/messages", status_code=201) @app.post("/api/v1/chats/{chat_id}/messages", status_code=201)
def post_message( async def post_message(
chat_id: str, chat_id: UUID,
body: CreateMessage, body: CreateMessage,
actor: dict = Depends(get_actor), user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db),
): ):
msg, error = storage.post_message(chat_id, actor["id"], body.text) chat = await chats_repo.get_if_member(db, chat_id, user.id)
if error == "chat_not_found": if chat is None:
raise HTTPException(404, "Chat not found") raise HTTPException(404, "Chat not found")
if error: msg = await messages_repo.create(db, chat_id, user.id, body.text)
raise HTTPException(400, error) return _msg_json(msg)
return msg
@app.get("/api/v1/chats/{chat_id}/messages") @app.get("/api/v1/chats/{chat_id}/messages")
def list_messages( async def list_messages(
chat_id: str, chat_id: UUID,
actor: dict = Depends(get_actor), user: User = Depends(get_current_user),
limit: int = Query(50, ge=1, le=100), limit: int = Query(50, ge=1, le=100),
cursor: Optional[str] = Query(None, min_length=1), cursor: Optional[str] = Query(None, min_length=1),
db: AsyncSession = Depends(get_db),
): ):
items, next_cursor, error = storage.list_messages( chat = await chats_repo.get_if_member(db, chat_id, user.id)
chat_id, actor["id"], limit, cursor if chat is None:
)
if error == "chat_not_found":
raise HTTPException(404, "Chat not found") raise HTTPException(404, "Chat not found")
return {"items": items, "next_cursor": next_cursor} parsed = None
if cursor is not None:
try:
c_created, c_id = cursor.split("|", 1)
parsed = (datetime.fromisoformat(c_created), UUID(c_id))
except Exception:
raise HTTPException(400, "Invalid cursor")
rows, next_cursor = await messages_repo.list_page(db, chat_id, limit, parsed)
nxt = f"{next_cursor[0].isoformat()}|{next_cursor[1]}" if next_cursor else None
return {"items": [_msg_json(m) for m in rows], "next_cursor": nxt}
if __name__ == "__main__": if __name__ == "__main__":
import uvicorn import uvicorn
port = int(os.getenv("PORT", "8080")) uvicorn.run(app, host="0.0.0.0", port=int(os.getenv("APP_PORT", "8080")))
uvicorn.run(app, host="0.0.0.0", port=port, log_level="info")
-134
View File
@@ -1,134 +0,0 @@
import threading
import uuid
from datetime import datetime, timezone
def new_id() -> str:
return str(uuid.uuid4())
def now_iso() -> str:
return datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
def _key_message(m: dict):
return (m["created_at"], uuid.UUID(m["id"]).int)
class Storage:
def __init__(self) -> None:
self._lock = threading.RLock()
self.users: dict[str, dict] = {}
self.chats: dict[str, dict] = {}
self.messages: dict[str, list[dict]] = {}
# users
def create_user(self, username: str, display_name: str) -> dict | None:
with self._lock:
for u in self.users.values():
if u["username"] == username:
return None
uid = new_id()
user = {
"id": uid,
"username": username,
"display_name": display_name,
"created_at": now_iso(),
}
self.users[uid] = user
return dict(user)
def get_user(self, uid: str) -> dict | None:
with self._lock:
u = self.users.get(uid)
return dict(u) if u else None
# chats
def create_chat(self, title: str, member_ids: list[str], creator_id: str):
with self._lock:
for mid in member_ids:
if mid not in self.users:
return None, "member_not_found"
if creator_id not in member_ids:
return None, "creator_not_member"
cid = new_id()
chat = {
"id": cid,
"title": title,
"member_ids": list(member_ids),
"created_at": now_iso(),
}
self.chats[cid] = chat
self.messages[cid] = []
return self._chat_public(chat), None
def get_chat(self, chat_id: str, requester_id: str) -> dict | None:
with self._lock:
chat = self.chats.get(chat_id)
if chat is None or requester_id not in chat["member_ids"]:
return None
return self._chat_public(chat)
def list_chats(self, requester_id: str, limit: int, cursor: str | None):
with self._lock:
items = [c for c in self.chats.values() if requester_id in c["member_ids"]]
items.sort(key=lambda c: (c["created_at"], uuid.UUID(c["id"]).int))
start = 0
if cursor:
for i, c in enumerate(items):
if c["id"] == cursor:
start = i + 1
break
page = items[start:start + limit]
next_cursor = None
if len(page) == limit and start + limit < len(items):
next_cursor = page[-1]["id"]
return [self._chat_public(c) for c in page], next_cursor
# messages
def post_message(self, chat_id: str, sender_id: str, text: str):
with self._lock:
chat = self.chats.get(chat_id)
if chat is None or sender_id not in chat["member_ids"]:
return None, "chat_not_found"
msg = {
"id": new_id(),
"chat_id": chat_id,
"sender_id": sender_id,
"text": text,
"created_at": now_iso(),
}
self.messages[chat_id].append(msg)
return dict(msg), None
def list_messages(self, chat_id: str, requester_id: str,
limit: int, cursor: str | None):
with self._lock:
chat = self.chats.get(chat_id)
if chat is None or requester_id not in chat["member_ids"]:
return None, None, "chat_not_found"
items = self.messages[chat_id] # здесь было узкое место items = sorted(self.messages[chat_id], key=_key_message)
start = 0
if cursor:
for i, m in enumerate(items):
if m["id"] == cursor:
start = i + 1
break
page = items[start:start + limit]
next_cursor = None
if len(page) == limit and start + limit < len(items):
next_cursor = page[-1]["id"]
return [dict(m) for m in page], next_cursor, None
@staticmethod
def _chat_public(chat: dict) -> dict:
return {
"id": chat["id"],
"title": chat["title"],
"member_ids": list(chat["member_ids"]),
"created_at": chat["created_at"],
}
storage = Storage()