Files
mtusi2026lab2/src/main.py
T
Your Name e67d13cf3d
Skeleton contracts / contracts (pull_request) Canceled after 0s
lab2: postgresql, redis sessions, grade 4 completed
2026-11-02 21:29:07 +03:00

405 lines
15 KiB
Python

from fastapi import FastAPI, HTTPException, Depends, Query, Request
from fastapi.responses import JSONResponse
from fastapi.exceptions import RequestValidationError
from starlette.exceptions import HTTPException as StarletteHTTPException
from starlette.middleware.base import BaseHTTPMiddleware
from pydantic import BaseModel, Field, field_validator
from typing import List, Optional
from contextlib import asynccontextmanager
from datetime import datetime, timezone, timedelta
from passlib.context import CryptContext
import asyncpg
import redis.asyncio as aioredis
import uuid, base64, os, secrets
DATABASE_URL = os.getenv("DATABASE_URL", "postgresql://user:password@db:5432/messenger")
REDIS_URL = os.getenv("REDIS_URL", "redis://redis:6379/0")
TTL = int(os.getenv("SESSION_TTL_SECONDS", "3600"))
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
db_pool = None
redis_client = None
@asynccontextmanager
async def lifespan(app: FastAPI):
global db_pool, redis_client
db_pool = await asyncpg.create_pool(DATABASE_URL, min_size=1, max_size=10)
redis_client = aioredis.from_url(REDIS_URL, decode_responses=True)
async with db_pool.acquire() as conn:
with open('migrations/001_init.sql', 'r') as f:
await conn.execute(f.read())
yield
await db_pool.close()
await redis_client.aclose()
app = FastAPI(lifespan=lifespan)
class RequestIdMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request: Request, call_next):
req_id = request.headers.get("X-Request-Id", str(uuid.uuid4()))
request.state.request_id = req_id
response = await call_next(request)
response.headers["X-Request-Id"] = req_id
return response
app.add_middleware(RequestIdMiddleware)
def fmt_dt(dt: datetime):
if dt.tzinfo is None:
dt = dt.replace(tzinfo=timezone.utc)
return dt.astimezone(timezone.utc).isoformat(timespec='microseconds').replace('+00:00', 'Z')
class UserCreate(BaseModel):
username: str = Field(..., min_length=3, max_length=32, pattern=r"^[a-z0-9_]+$")
display_name: str = Field(..., min_length=1, max_length=100)
password: str = Field(..., min_length=12, max_length=128)
@field_validator('display_name')
def check_spaces(cls, v):
if not v.strip(): raise ValueError("Cannot be only spaces")
return v
class ChatCreate(BaseModel):
title: str = Field(..., min_length=1, max_length=100)
member_ids: List[str]
@field_validator('title')
def check_spaces(cls, v):
if not v.strip(): raise ValueError("Cannot be only spaces")
return v
class MessageCreate(BaseModel):
text: str = Field(..., min_length=1, max_length=4000)
@field_validator('text')
def check_spaces(cls, v):
if not v.strip(): raise ValueError("Text cannot be empty or spaces")
return v
@app.exception_handler(StarletteHTTPException)
async def http_exc_handler(request: Request, exc: StarletteHTTPException):
req_id = getattr(request.state, "request_id", str(uuid.uuid4()))
headers = {"X-Request-Id": req_id}
if hasattr(exc, "headers") and exc.headers:
headers.update(exc.headers)
code = "invalid_request"
if exc.status_code == 401:
code = "unauthorized"
elif exc.status_code == 404:
code = "not_found"
elif exc.status_code == 409:
code = "conflict"
return JSONResponse(
status_code=exc.status_code,
content={"error": {"code": code, "message": str(exc.detail), "request_id": req_id}},
headers=headers
)
@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request: Request, exc: RequestValidationError):
req_id = getattr(request.state, "request_id", str(uuid.uuid4()))
return JSONResponse(
status_code=400,
content={"error": {"code": "invalid_request", "message": "Invalid request data", "request_id": req_id}},
headers={"X-Request-Id": req_id}
)
def get_bearer_token(request: Request):
auth = request.headers.get("Authorization")
if not auth or not auth.startswith("Bearer "):
raise HTTPException(
status_code=401,
detail="Unauthorized",
headers={"WWW-Authenticate": 'Bearer realm="messenger"'}
)
return auth.split(" ")[1]
def get_basic_credentials(request: Request):
auth = request.headers.get("Authorization")
if not auth or not auth.startswith("Basic "):
raise HTTPException(
status_code=401,
detail="Unauthorized",
headers={"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"'}
)
try:
decoded = base64.b64decode(auth.split(" ")[1]).decode('utf-8')
username, password = decoded.split(":", 1)
return username, password
except Exception:
raise HTTPException(
status_code=401,
detail="Unauthorized",
headers={"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"'}
)
async def get_current_user(request: Request):
token = get_bearer_token(request)
try:
user_id = await redis_client.get(f"session:{token}")
except Exception:
raise HTTPException(status_code=503, detail="Redis unavailable")
if not user_id:
raise HTTPException(
status_code=401,
detail="Session expired or invalid",
headers={"WWW-Authenticate": 'Bearer realm="messenger"'}
)
async with db_pool.acquire() as conn:
user = await conn.fetchrow("SELECT id, username, display_name, created_at FROM users WHERE id = $1",
uuid.UUID(user_id))
if not user:
raise HTTPException(
status_code=401,
detail="User not found",
headers={"WWW-Authenticate": 'Bearer realm="messenger"'}
)
return dict(user)
@app.get("/health/live")
async def live(): return {"status": "ok"}
@app.get("/health/ready")
async def ready():
try:
async with db_pool.acquire() as conn:
await conn.fetchval("SELECT 1")
await redis_client.ping()
return {"status": "ok"}
except Exception:
return JSONResponse(status_code=503, content={
"error": {"code": "unavailable", "message": "Dependency down", "request_id": str(uuid.uuid4())}})
@app.post("/api/v1/users", status_code=201)
async def create_user(user: UserCreate):
user_id = uuid.uuid4()
hashed_pw = pwd_context.hash(user.password)
now = datetime.now(timezone.utc)
try:
async with db_pool.acquire() as conn:
await conn.execute(
"INSERT INTO users (id, username, display_name, password_hash, created_at) VALUES ($1, $2, $3, $4, $5)",
user_id, user.username, user.display_name, hashed_pw, now
)
except asyncpg.UniqueViolationError:
raise HTTPException(409, "Username already exists")
return {"id": str(user_id), "username": user.username, "display_name": user.display_name, "created_at": fmt_dt(now)}
@app.get("/api/v1/users/me")
async def get_me(user: dict = Depends(get_current_user)):
return {
"id": str(user["id"]),
"username": user["username"],
"display_name": user["display_name"],
"created_at": fmt_dt(user["created_at"])
}
@app.post("/api/v1/auth/sessions", status_code=201)
async def login(request: Request):
username, password = get_basic_credentials(request)
async with db_pool.acquire() as conn:
user = await conn.fetchrow("SELECT * FROM users WHERE username = $1", username)
if not user or not pwd_context.verify(password, user["password_hash"]):
raise HTTPException(
status_code=401,
detail="Invalid credentials",
headers={"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"'}
)
token = secrets.token_hex(32)
await redis_client.setex(f"session:{token}", TTL, str(user["id"]))
expires_at = datetime.now(timezone.utc) + timedelta(seconds=TTL)
return {
"token": token, "token_type": "Bearer", "expires_at": fmt_dt(expires_at),
"user": {
"id": str(user["id"]), "username": user["username"],
"display_name": user["display_name"], "created_at": fmt_dt(user["created_at"])
}
}
@app.delete("/api/v1/auth/sessions/current", status_code=204)
async def logout(request: Request):
token = get_bearer_token(request)
deleted = await redis_client.delete(f"session:{token}")
if deleted == 0:
raise HTTPException(
status_code=401,
detail="Session expired or invalid",
headers={"WWW-Authenticate": 'Bearer realm="messenger"'}
)
return None
@app.post("/api/v1/chats", status_code=201)
async def create_chat(chat: ChatCreate, user: dict = Depends(get_current_user)):
chat_id = uuid.uuid4()
now = datetime.now(timezone.utc)
members = set(chat.member_ids)
members.add(str(user["id"]))
async with db_pool.acquire() as conn:
async with conn.transaction():
await conn.execute("INSERT INTO chats (id, title, created_at) VALUES ($1, $2, $3)", chat_id, chat.title,
now)
for m_id in members:
try:
await conn.execute("INSERT INTO chat_members (chat_id, user_id) VALUES ($1, $2)", chat_id,
uuid.UUID(m_id))
except asyncpg.ForeignKeyViolationError:
raise HTTPException(400, "User not found")
return {"id": str(chat_id), "title": chat.title, "member_ids": list(members), "created_at": fmt_dt(now)}
@app.get("/api/v1/chats")
async def list_chats(user: dict = Depends(get_current_user), limit: int = Query(50, ge=1, le=100),
cursor: Optional[str] = None):
async with db_pool.acquire() as conn:
query = """
SELECT c.id, c.title, c.created_at FROM chats c
JOIN chat_members cm ON c.id = cm.chat_id
WHERE cm.user_id = $1
"""
params = [user["id"]]
if cursor:
try:
c_time, c_id = base64.b64decode(cursor).decode('utf-8').split('|', 1)
query += " AND (c.created_at, c.id) > ($2, $3)"
params.extend([datetime.fromisoformat(c_time.replace('Z', '+00:00')), uuid.UUID(c_id)])
except Exception:
raise HTTPException(400, "Invalid cursor")
query += f" ORDER BY c.created_at ASC, c.id ASC LIMIT {limit + 1}"
rows = await conn.fetch(query, *params)
items = []
for row in rows:
chat_dict = dict(row)
chat_dict['created_at'] = fmt_dt(chat_dict['created_at'])
chat_dict['id'] = str(chat_dict['id'])
m_rows = await conn.fetch("SELECT user_id FROM chat_members WHERE chat_id = $1", row['id'])
chat_dict['member_ids'] = [str(m['user_id']) for m in m_rows]
items.append(chat_dict)
next_cursor = None
if len(items) > limit:
last = items[limit - 1]
next_cursor = base64.b64encode(f"{last['created_at']}|{last['id']}".encode('utf-8')).decode('utf-8')
items = items[:limit]
return {"items": items, "next_cursor": next_cursor}
@app.get("/api/v1/chats/{chat_id}")
async def get_chat(chat_id: str, user: dict = Depends(get_current_user)):
try:
chat_uuid = uuid.UUID(chat_id)
except ValueError:
raise HTTPException(400, "Invalid chat UUID")
async with db_pool.acquire() as conn:
member = await conn.fetchval("SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2", chat_uuid,
user["id"])
if not member:
raise HTTPException(404, "Chat not found")
chat = await conn.fetchrow("SELECT id, title, created_at FROM chats WHERE id = $1", chat_uuid)
if not chat:
raise HTTPException(404, "Chat not found")
m_rows = await conn.fetch("SELECT user_id FROM chat_members WHERE chat_id = $1", chat_uuid)
member_ids = [str(m["user_id"]) for m in m_rows]
return {
"id": str(chat["id"]),
"title": chat["title"],
"member_ids": member_ids,
"created_at": fmt_dt(chat["created_at"])
}
@app.post("/api/v1/chats/{chat_id}/messages", status_code=201)
async def send_message(chat_id: str, msg: MessageCreate, user: dict = Depends(get_current_user)):
chat_uuid = uuid.UUID(chat_id)
async with db_pool.acquire() as conn:
member = await conn.fetchval("SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2", chat_uuid,
user["id"])
if not member: raise HTTPException(404, "Chat not found")
msg_id = uuid.uuid4()
now = datetime.now(timezone.utc)
await conn.execute(
"INSERT INTO messages (id, chat_id, sender_id, text, created_at) VALUES ($1, $2, $3, $4, $5)", msg_id,
chat_uuid, user["id"], msg.text, now)
return {"id": str(msg_id), "chat_id": chat_id, "sender_id": str(user["id"]), "text": msg.text,
"created_at": fmt_dt(now)}
@app.get("/api/v1/chats/{chat_id}/messages")
async def get_messages(chat_id: str, user: dict = Depends(get_current_user), limit: int = Query(50, ge=1, le=100),
cursor: Optional[str] = None):
chat_uuid = uuid.UUID(chat_id)
async with db_pool.acquire() as conn:
member = await conn.fetchval("SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2", chat_uuid,
user["id"])
if not member: raise HTTPException(404, "Chat not found")
query = "SELECT * FROM messages WHERE chat_id = $1"
params = [chat_uuid]
if cursor:
try:
c_time, c_id = base64.b64decode(cursor).decode('utf-8').split('|', 1)
query += " AND (created_at, id) > ($2, $3)"
params.extend([datetime.fromisoformat(c_time.replace('Z', '+00:00')), uuid.UUID(c_id)])
except Exception:
raise HTTPException(400, "Invalid cursor")
query += f" ORDER BY created_at ASC, id ASC LIMIT {limit + 1}"
rows = await conn.fetch(query, *params)
items = []
for row in rows:
msg_dict = dict(row)
msg_dict['created_at'] = fmt_dt(msg_dict['created_at'])
msg_dict['id'] = str(msg_dict['id'])
msg_dict['chat_id'] = str(msg_dict['chat_id'])
msg_dict['sender_id'] = str(msg_dict['sender_id'])
items.append(msg_dict)
next_cursor = None
if len(items) > limit:
last = items[limit - 1]
next_cursor = base64.b64encode(f"{last['created_at']}|{last['id']}".encode('utf-8')).decode('utf-8')
items = items[:limit]
return {"items": items, "next_cursor": next_cursor}