lab2 complete

This commit is contained in:
kuruoni
2026-11-14 04:50:02 +03:00
parent 65003b6119
commit 684d00c899
20 changed files with 796 additions and 16 deletions
+53
View File
@@ -0,0 +1,53 @@
import re
import uuid as _uuid_lib
from fastapi import Request
from datetime import timezone, datetime
from .exceptions import ApiException
from .db import get_pool
users_db = {}
usernames_set = set()
chats_db = {}
messages_db = {}
USERNAME_REGEX = re.compile(r"^[a-z0-9_]{3,32}$")
def get_utc_now() -> str:
return datetime.now(timezone.utc)
def format_iso(dt: datetime) -> str:
return dt.strftime("%Y-%m-%dT%H:%M:%S.%fZ")
async def authenticate_user(request: Request) -> str:
auth = request.headers.get("Authorization")
auth_err_headers = {"WWW-Authenticate": 'Bearer realm="messenger"'}
if not auth or not auth.startswith("Bearer "):
raise ApiException(401, "unauthorized", "Missing or invalid Bearer token", headers=auth_err_headers)
token = auth.split(" ", 1)[1].strip()
pool = get_pool()
row = await pool.fetchrow(
"SELECT user_id, expires_at, revoked FROM sessions WHERE token = $1",
token
)
if not row:
raise ApiException(401, "unauthorized", "Session not found", headers=auth_err_headers)
if row["revoked"] or row["expires_at"] <= get_utc_now():
raise ApiException(401, "unauthorized", "Session expired or revoked", headers=auth_err_headers)
request.state.current_token = token
return str(row["user_id"])
def validate_uuid(val: str):
try:
_uuid_lib.UUID(str(val))
except Exception as e:
print(f" РЕАЛЬНАЯ ОШИБКА В validate_uuid: {type(e).__name__} -> {e}")
raise ApiException(400, "invalid_request", f"Invalid UUID: {val}")