+ добавила БД постгрес

This commit is contained in:
vasyukova
2026-09-30 22:38:32 +03:00
parent 8e3a0e22f4
commit 19d3767ef3
10 changed files with 327 additions and 6 deletions
+249
View File
@@ -0,0 +1,249 @@
import hashlib
import hmac
import secrets
import threading
from datetime import datetime, timedelta, timezone
from typing import List, Optional
from uuid import UUID, uuid4
from ..models.schemas import Chat, Message, User
from .db import connection
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:
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(),
)
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),
)
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])
# ---------- Сессии ----------
def create_session(self, user_id: UUID, ttl_seconds: int) -> tuple:
token = secrets.token_urlsafe(32)
expires_at = now_utc() + timedelta(seconds=ttl_seconds)
with self._lock, connection() as conn:
with conn.cursor() as cur:
cur.execute(
"INSERT INTO sessions (token, user_id, expires_at) VALUES (%s, %s, %s)",
(token, user_id, expires_at),
)
conn.commit()
return token, expires_at
def get_session_user(self, token: str) -> Optional[User]:
with connection() as conn, conn.cursor() as cur:
cur.execute(
"SELECT u.id, u.username, u.display_name, u.created_at, s.expires_at"
" FROM sessions s JOIN users u ON u.id = s.user_id"
" WHERE s.token = %s",
(token,),
)
row = cur.fetchone()
if row is None:
return None
if row[4] <= now_utc():
with conn.cursor() as cur2:
cur2.execute("DELETE FROM sessions WHERE token = %s", (token,))
conn.commit()
return None
return _row_to_user(row[:4])
def revoke_session(self, token: str) -> None:
with self._lock, connection() as conn:
with conn.cursor() as cur:
cur.execute("DELETE FROM sessions WHERE token = %s", (token,))
conn.commit()
# ---------- Чаты ----------
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()]
storage = PostgresStorage() # единственный экземпляр на процесс