forked from mtusi2026/mtusi2026lab2
lab2: PostgreSQL persistence, Argon2id sessions, Compose stack (grade 3)
This commit is contained in:
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()
|
||||
Reference in New Issue
Block a user