Files
mtusi2026lab2-fork/api/utils.py
T
2026-11-14 04:50:02 +03:00

53 lines
1.6 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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}")