Files
mtusi2026lab2/app/storage.py
T
2026-10-29 17:16:55 +03:00

173 lines
8.0 KiB
Python

"""Persistent users, chats, messages and sessions in PostgreSQL."""
import datetime as dt
import hashlib
import secrets
import uuid
import psycopg
from psycopg.rows import dict_row
from psycopg_pool import ConnectionPool
from argon2 import PasswordHasher
from argon2.exceptions import VerifyMismatchError, VerificationError, InvalidHashError
from app.config import secret, POOL_SIZE, SESSION_TTL_SECONDS
from app.errors import BadRequestError, ConflictError, NotFoundError, UnauthorizedError
from app.models import decode_cursor, encode_cursor
def public(row):
return {key: (str(value) if isinstance(value, uuid.UUID) else
value.isoformat(timespec='microseconds').replace('+00:00', 'Z')
if isinstance(value, dt.datetime) else value)
for key, value in row.items() if key != 'password_hash'}
def token_hash(token):
return hashlib.sha256(token.encode()).hexdigest()
class PostgresStorage:
def __init__(self):
self.pool = ConnectionPool(
secret('DATABASE_URL'), min_size=1, max_size=POOL_SIZE, timeout=2,
max_waiting=32, reconnect_timeout=3,
kwargs={'connect_timeout': 2, 'row_factory': dict_row,
'options': '-c statement_timeout=2500 -c lock_timeout=1500 -c timezone=UTC'},
check=ConnectionPool.check_connection,
)
self.pool.wait(timeout=15)
self.hasher = PasswordHasher(time_cost=3, memory_cost=65536, parallelism=2)
self.dummy_hash = self.hasher.hash(secrets.token_urlsafe(32))
def close(self):
self.pool.close()
def ready(self):
with self.pool.connection() as conn:
conn.execute('SELECT 1')
def create_user(self, username, display_name, password):
password_hash = self.hasher.hash(password)
try:
with self.pool.connection() as conn:
row = conn.execute('''INSERT INTO users(id, username, display_name, password_hash)
VALUES (%s,%s,%s,%s) RETURNING id, username, display_name, created_at''',
(uuid.uuid4(), username, display_name, password_hash)).fetchone()
return public(row)
except psycopg.errors.UniqueViolation:
raise ConflictError('Username is already taken') from None
def get_user(self, user_id):
with self.pool.connection() as conn:
row = conn.execute('SELECT id,username,display_name,created_at FROM users WHERE id=%s', (user_id,)).fetchone()
return public(row) if row else None
def login(self, username, password):
with self.pool.connection() as conn:
row = conn.execute('SELECT * FROM users WHERE username=%s', (username,)).fetchone()
try:
self.hasher.verify(row['password_hash'] if row else self.dummy_hash, password)
except (VerifyMismatchError, VerificationError, InvalidHashError):
raise UnauthorizedError('Invalid credentials') from None
if not row:
raise UnauthorizedError('Invalid credentials')
token = secrets.token_urlsafe(32) # 256 random bits; never persist/log the raw token.
with self.pool.connection() as conn:
session = conn.execute('''INSERT INTO sessions(token_hash,user_id,expires_at)
VALUES (%s,%s,clock_timestamp() + %s * interval '1 second') RETURNING expires_at''',
(token_hash(token), row['id'], SESSION_TTL_SECONDS)).fetchone()
return {'token': token, 'token_type': 'Bearer',
'expires_at': public(session)['expires_at'], 'user': public(row)}
def authenticate(self, token):
# Check expiry against the database clock on every protected request.
with self.pool.connection() as conn:
row = conn.execute('''SELECT user_id FROM sessions
WHERE token_hash=%s AND expires_at > clock_timestamp()''', (token_hash(token),)).fetchone()
if not row:
raise UnauthorizedError()
user = self.get_user(row['user_id'])
if not user:
raise UnauthorizedError()
return user
def logout(self, token):
with self.pool.connection() as conn:
row = conn.execute('''DELETE FROM sessions WHERE token_hash=%s
AND expires_at > clock_timestamp() RETURNING user_id''', (token_hash(token),)).fetchone()
if not row:
raise UnauthorizedError()
@staticmethod
def _chat(conn, chat_id):
row = conn.execute('SELECT * FROM chats WHERE id=%s', (chat_id,)).fetchone()
result = public(row)
result['member_ids'] = [str(r['user_id']) for r in conn.execute(
'SELECT user_id FROM memberships WHERE chat_id=%s ORDER BY user_id', (chat_id,))]
return result
@staticmethod
def _access(conn, user_id, chat_id):
if not conn.execute('SELECT 1 FROM memberships WHERE chat_id=%s AND user_id=%s',
(chat_id, user_id)).fetchone():
raise NotFoundError('Chat not found')
def create_chat(self, creator_id, title, member_ids):
if creator_id not in member_ids:
raise BadRequestError('Creator must be included in member_ids')
try:
with self.pool.connection() as conn:
chat_id = uuid.uuid4()
conn.execute('INSERT INTO chats(id,title) VALUES (%s,%s)', (chat_id, title))
with conn.cursor() as cur:
cur.executemany('INSERT INTO memberships(chat_id,user_id) VALUES (%s,%s)',
[(chat_id, user_id) for user_id in member_ids])
chat = self._chat(conn, chat_id)
return chat
except psycopg.errors.ForeignKeyViolation:
# Exiting connection() rolls back chat and every already inserted member.
raise BadRequestError('Unknown participant') from None
def get_chat(self, user_id, chat_id):
with self.pool.connection() as conn:
self._access(conn, user_id, chat_id)
return self._chat(conn, chat_id)
def list_chats(self, user_id, limit=50, cursor=None):
params = [user_id]
condition = ''
if cursor is not None:
stamp, item_id = decode_cursor(cursor, 'chat', user_id)
condition = ' AND (c.created_at,c.id) > (%s,%s)'
params.extend([stamp, uuid.UUID(int=item_id)])
params.append(limit + 1)
with self.pool.connection() as conn:
rows = conn.execute('''SELECT c.* FROM chats c JOIN memberships m ON m.chat_id=c.id
WHERE m.user_id=%s''' + condition + ' ORDER BY c.created_at,c.id LIMIT %s', params).fetchall()
items = [self._chat(conn, row['id']) for row in rows[:limit]]
next_cursor = encode_cursor(items[-1]['created_at'], items[-1]['id'], 'chat', user_id) if len(rows) > limit else None
return {'items': items, 'next_cursor': next_cursor}
def create_message(self, chat_id, sender_id, text):
with self.pool.connection() as conn:
self._access(conn, sender_id, chat_id)
row = conn.execute('''INSERT INTO messages(id,chat_id,sender_id,text)
VALUES (%s,%s,%s,%s) RETURNING *''', (uuid.uuid4(), chat_id, sender_id, text)).fetchone()
return public(row)
def list_messages(self, user_id, chat_id, limit=50, cursor=None):
params = [chat_id]
condition = ''
if cursor is not None:
stamp, item_id = decode_cursor(cursor, 'message', chat_id)
condition = ' AND (created_at,id) > (%s,%s)'
params.extend([stamp, uuid.UUID(int=item_id)])
params.append(limit + 1)
with self.pool.connection() as conn:
self._access(conn, user_id, chat_id)
rows = conn.execute('SELECT * FROM messages WHERE chat_id=%s' + condition +
' ORDER BY created_at,id LIMIT %s', params).fetchall()
items = [public(row) for row in rows[:limit]]
next_cursor = encode_cursor(items[-1]['created_at'], items[-1]['id'], 'message', chat_id) if len(rows) > limit else None
return {'items': items, 'next_cursor': next_cursor}