forked from mtusi2026/mtusi2026lab2
267 lines
10 KiB
Python
267 lines
10 KiB
Python
import hashlib
|
|
import hmac
|
|
import secrets
|
|
import threading
|
|
from datetime import datetime, timezone
|
|
from typing import List, Optional
|
|
from uuid import UUID, uuid4
|
|
|
|
from ..models.schemas import Chat, Message, User
|
|
from .db import connection
|
|
from .sessions import (
|
|
create_session as _sess_create,
|
|
get_session_user as _sess_get,
|
|
revoke_session as _sess_revoke,
|
|
)
|
|
|
|
|
|
def now_utc() -> datetime:
|
|
return datetime.now(timezone.utc)
|
|
|
|
|
|
# --- Password KDF (stdlib scrypt) ---
|
|
_SCRYPT_N = 2 ** 14
|
|
_SCRYPT_R = 8
|
|
_SCRYPT_P = 1
|
|
_SCRYPT_DKLEN = 32
|
|
|
|
|
|
def _hash_password(password: str) -> str:
|
|
salt = secrets.token_bytes(16)
|
|
dk = hashlib.scrypt(
|
|
password.encode("utf-8"),
|
|
salt=salt,
|
|
n=_SCRYPT_N, r=_SCRYPT_R, p=_SCRYPT_P, dklen=_SCRYPT_DKLEN,
|
|
)
|
|
return "scrypt$%d$%d$%d$%s$%s" % (
|
|
_SCRYPT_N, _SCRYPT_R, _SCRYPT_P, salt.hex(), dk.hex(),
|
|
)
|
|
|
|
|
|
def _verify_password(password: str, stored: str) -> bool:
|
|
try:
|
|
scheme, n, r, p, salt_hex, dk_hex = stored.split("$")
|
|
if scheme != "scrypt":
|
|
return False
|
|
dk = hashlib.scrypt(
|
|
password.encode("utf-8"),
|
|
salt=bytes.fromhex(salt_hex),
|
|
n=int(n), r=int(r), p=int(p),
|
|
dklen=len(bytes.fromhex(dk_hex)),
|
|
)
|
|
return hmac.compare_digest(dk.hex(), dk_hex)
|
|
except Exception:
|
|
return False
|
|
|
|
|
|
def _row_to_user(row) -> User:
|
|
return User(id=row[0], username=row[1], display_name=row[2], created_at=row[3])
|
|
|
|
|
|
def _row_to_chat(row, member_ids: List[UUID]) -> Chat:
|
|
return Chat(id=row[0], title=row[1], member_ids=member_ids, created_at=row[2])
|
|
|
|
|
|
def _row_to_message(row) -> Message:
|
|
return Message(
|
|
id=row[0], chat_id=row[1], sender_id=row[2],
|
|
text=row[3], created_at=row[4],
|
|
)
|
|
|
|
|
|
class PostgresStorage:
|
|
"""Потокобезопасная обёртка; параллелизм обеспечивает PostgreSQL."""
|
|
|
|
def __init__(self) -> None:
|
|
self._lock = threading.RLock()
|
|
|
|
# ---------- Пользователи ----------
|
|
def create_user(self, username: str, display_name: str, password: str) -> User:
|
|
with self._lock, connection() as conn:
|
|
with conn.cursor() as cur:
|
|
# SELECT-проверка + INSERT в одной транзакции; уникальный индекс
|
|
# users.username отсекает гонку на уровне БД (UniqueViolation).
|
|
cur.execute("SELECT 1 FROM users WHERE username = %s", (username,))
|
|
if cur.fetchone() is not None:
|
|
raise ValueError("username_taken")
|
|
user = User(
|
|
id=uuid4(), username=username,
|
|
display_name=display_name, created_at=now_utc(),
|
|
)
|
|
try:
|
|
cur.execute(
|
|
"INSERT INTO users (id, username, display_name, password_hash, created_at)"
|
|
" VALUES (%s, %s, %s, %s, %s)",
|
|
(user.id, user.username, user.display_name,
|
|
_hash_password(password), user.created_at),
|
|
)
|
|
except Exception as exc:
|
|
# Параллельная регистрация того же username: уникальный индекс
|
|
# выбросил UniqueViolation — превращаем в доменную ошибку.
|
|
if exc.__class__.__name__ == "UniqueViolation":
|
|
raise ValueError("username_taken")
|
|
raise
|
|
conn.commit()
|
|
return user
|
|
|
|
def get_user(self, user_id: UUID) -> Optional[User]:
|
|
with connection() as conn, conn.cursor() as cur:
|
|
cur.execute(
|
|
"SELECT id, username, display_name, created_at FROM users WHERE id = %s",
|
|
(user_id,),
|
|
)
|
|
row = cur.fetchone()
|
|
return _row_to_user(row) if row else None
|
|
|
|
def get_user_by_username(self, username: str) -> Optional[User]:
|
|
with connection() as conn, conn.cursor() as cur:
|
|
cur.execute(
|
|
"SELECT id, username, display_name, created_at FROM users WHERE username = %s",
|
|
(username,),
|
|
)
|
|
row = cur.fetchone()
|
|
return _row_to_user(row) if row else None
|
|
|
|
def verify_credentials(self, username: str, password: str) -> Optional[User]:
|
|
with connection() as conn, conn.cursor() as cur:
|
|
cur.execute(
|
|
"SELECT id, username, display_name, created_at, password_hash"
|
|
" FROM users WHERE username = %s",
|
|
(username,),
|
|
)
|
|
row = cur.fetchone()
|
|
if row is None:
|
|
return None
|
|
if not _verify_password(password, row[4]):
|
|
return None
|
|
return _row_to_user(row[:4])
|
|
|
|
# ---------- Сессии (Redis или PostgreSQL — см. storage/sessions.py) ----------
|
|
# Тонкие делегаты: роутеры продолжают вызывать storage.create_session(...),
|
|
# storage.get_session_user(...), storage.revoke_session(...) без изменений.
|
|
def create_session(self, user_id: UUID, ttl_seconds: int) -> tuple:
|
|
return _sess_create(user_id, ttl_seconds)
|
|
|
|
def get_session_user(self, token: str) -> Optional[User]:
|
|
return _sess_get(token)
|
|
|
|
def revoke_session(self, token: str) -> None:
|
|
_sess_revoke(token)
|
|
|
|
# ---------- Чаты ----------
|
|
def create_chat(self, title: str, member_ids: List[UUID]) -> Chat:
|
|
with self._lock, connection() as conn:
|
|
with conn.cursor() as cur:
|
|
# проверяем всех участников
|
|
cur.execute(
|
|
"SELECT id FROM users WHERE id = ANY(%s)",
|
|
(list(member_ids),),
|
|
)
|
|
found = {r[0] for r in cur.fetchall()}
|
|
if len(found) != len(set(member_ids)):
|
|
raise ValueError("unknown_member")
|
|
chat = Chat(
|
|
id=uuid4(), title=title,
|
|
member_ids=list(member_ids), created_at=now_utc(),
|
|
)
|
|
cur.execute(
|
|
"INSERT INTO chats (id, title, created_at) VALUES (%s, %s, %s)",
|
|
(chat.id, chat.title, chat.created_at),
|
|
)
|
|
cur.executemany(
|
|
"INSERT INTO chat_members (chat_id, user_id) VALUES (%s, %s)",
|
|
[(chat.id, uid) for uid in member_ids],
|
|
)
|
|
conn.commit()
|
|
return chat
|
|
|
|
def get_chat(self, chat_id: UUID) -> Optional[Chat]:
|
|
with connection() as conn, conn.cursor() as cur:
|
|
cur.execute(
|
|
"SELECT id, title, created_at FROM chats WHERE id = %s",
|
|
(chat_id,),
|
|
)
|
|
row = cur.fetchone()
|
|
if row is None:
|
|
return None
|
|
cur.execute(
|
|
"SELECT user_id FROM chat_members WHERE chat_id = %s", (chat_id,),
|
|
)
|
|
members = [r[0] for r in cur.fetchall()]
|
|
return _row_to_chat(row, members)
|
|
|
|
def list_chats_for_user(self, user_id: UUID) -> List[Chat]:
|
|
with connection() as conn, conn.cursor() as cur:
|
|
cur.execute(
|
|
"SELECT c.id, c.title, c.created_at FROM chats c"
|
|
" JOIN chat_members m ON m.chat_id = c.id"
|
|
" WHERE m.user_id = %s ORDER BY c.created_at, c.id",
|
|
(user_id,),
|
|
)
|
|
rows = cur.fetchall()
|
|
chats = []
|
|
for row in rows:
|
|
cur.execute(
|
|
"SELECT user_id FROM chat_members WHERE chat_id = %s", (row[0],),
|
|
)
|
|
members = [r[0] for r in cur.fetchall()]
|
|
chats.append(_row_to_chat(row, members))
|
|
return chats
|
|
|
|
# ---------- Сообщения ----------
|
|
def add_message(self, chat_id: UUID, sender_id: UUID, text: str) -> Message:
|
|
with self._lock, connection() as conn:
|
|
message = Message(
|
|
id=uuid4(), chat_id=chat_id, sender_id=sender_id,
|
|
text=text, created_at=now_utc(),
|
|
)
|
|
with conn.cursor() as cur:
|
|
cur.execute(
|
|
"INSERT INTO messages (id, chat_id, sender_id, text, created_at)"
|
|
" VALUES (%s, %s, %s, %s, %s)",
|
|
(message.id, message.chat_id, message.sender_id,
|
|
message.text, message.created_at),
|
|
)
|
|
conn.commit()
|
|
return message
|
|
|
|
def list_messages(self, chat_id: UUID) -> List[Message]:
|
|
with connection() as conn, conn.cursor() as cur:
|
|
cur.execute(
|
|
"SELECT id, chat_id, sender_id, text, created_at FROM messages"
|
|
" WHERE chat_id = %s ORDER BY created_at, id",
|
|
(chat_id,),
|
|
)
|
|
return [_row_to_message(r) for r in cur.fetchall()]
|
|
|
|
def list_messages_page(
|
|
self,
|
|
chat_id: UUID,
|
|
limit: int,
|
|
after: Optional[tuple] = None,
|
|
) -> List[Message]:
|
|
"""Keyset-пагинация в SQL
|
|
|
|
after = (created_at, id) последней записи предыдущей страницы или None.
|
|
Запрос использует индекс idx_messages_chat_created (chat_id, created_at, id)
|
|
и не делает полный scan всей истории на каждую страницу.
|
|
"""
|
|
with connection() as conn, conn.cursor() as cur:
|
|
if after is None:
|
|
cur.execute(
|
|
"SELECT id, chat_id, sender_id, text, created_at FROM messages"
|
|
" WHERE chat_id = %s ORDER BY created_at, id LIMIT %s",
|
|
(chat_id, limit),
|
|
)
|
|
else:
|
|
after_ts, after_id = after
|
|
cur.execute(
|
|
"SELECT id, chat_id, sender_id, text, created_at FROM messages"
|
|
" WHERE chat_id = %s AND (created_at, id) > (%s, %s)"
|
|
" ORDER BY created_at, id LIMIT %s",
|
|
(chat_id, after_ts, after_id, limit),
|
|
)
|
|
return [_row_to_message(r) for r in cur.fetchall()]
|
|
|
|
|
|
storage = PostgresStorage() # единственный экземпляр на процесс |