Files
mtusi2026lab2/src/messenger/api.py
T
lxst_atmose 130c485a6d
Skeleton contracts / contracts (pull_request) Canceled after 0s
lab2: PostgreSQL, Bearer-сессии и Redis-кэш
2026-10-29 22:15:43 +03:00

252 lines
12 KiB
Python

"""Domain logic and routing for the lab2 API: PostgreSQL state, Bearer sessions."""
from __future__ import annotations
import base64
import datetime as dt
import json
import re
import uuid
from . import cursor as cursor_codec
from . import security
from . import validation
from .db import Database
from .errors import ApiError, Conflict, InvalidRequest, NotFound, Unauthorized, Unavailable, UnsupportedMediaType
from .store import Store, utc_now, rfc3339
SCOPE_CHATS = 'chats'
SCOPE_MESSAGES = 'chat/{chat_id}/messages'
class Request:
"""One parsed HTTP request; the API layer never touches sockets."""
__slots__ = ('method', 'path', 'query', 'headers', 'body', 'request_id', 'client')
def __init__(self, method, path, query, headers, body, request_id, client):
self.method = method
self.path = path
self.query = query
self.headers = headers
self.body = body
self.request_id = request_id
self.client = client
class Api:
ROUTES = (
('GET', re.compile(r'^/health/live$'), 'health_live'),
('GET', re.compile(r'^/health/ready$'), 'health_ready'),
('POST', re.compile(r'^/api/v1/users$'), 'create_user'),
('GET', re.compile(r'^/api/v1/users/me$'), 'current_user'),
('GET', re.compile(r'^/api/v1/chats$'), 'list_chats'),
('POST', re.compile(r'^/api/v1/chats$'), 'create_chat'),
('GET', re.compile(r'^/api/v1/chats/(?P<chat_id>[^/]+)$'), 'get_chat'),
('GET', re.compile(r'^/api/v1/chats/(?P<chat_id>[^/]+)/messages$'), 'list_messages'),
('POST', re.compile(r'^/api/v1/chats/(?P<chat_id>[^/]+)/messages$'), 'post_message'),
('POST', re.compile(r'^/api/v1/auth/sessions$'), 'create_session'),
('DELETE', re.compile(r'^/api/v1/auth/sessions/current$'), 'revoke_session'),
)
def __init__(self, config, store: Store, database: Database):
self.config = config
self.store = store
self.database = database
def dispatch(self, request):
"""Return (status, payload). Only ApiError and payloads leave this method."""
path_matched = False
for method, pattern, handler in self.ROUTES:
match = pattern.match(request.path)
if match:
path_matched = True
if method == request.method:
return getattr(self, handler)(request, match.groupdict())
raise NotFound('Маршрут не найден' if not path_matched else 'Метод не поддерживается')
# ------------------------------------------------------------- health
def health_live(self, request, path_params):
return 200, {'status': 'ok'}
def health_ready(self, request, path_params):
try:
self.store.stats()
except Exception:
raise Unavailable('База данных недоступна')
return 200, {'status': 'ok'}
# -------------------------------------------------------------- users
def create_user(self, request, path_params):
payload = self._json_object(request)
validation.require_fields(payload, ('username', 'display_name', 'password'),
('username', 'display_name', 'password'))
username = validation.require_username(payload)
display_name = validation.require_text_field(
payload, 'display_name', 1, self.config.max_display_name_code_points)
password = validation.require_text_field(
payload, 'password', 12, 128, strip_check=False)
password_hash = security.hash_password(password)
return 201, self.store.create_user(username, display_name, password_hash)
def current_user(self, request, path_params):
return 200, self._authenticate(request)
# -------------------------------------------------------------- chats
def create_chat(self, request, path_params):
actor = self._authenticate(request)
payload = self._json_object(request)
validation.require_fields(payload, ('title', 'member_ids'), ('title', 'member_ids'))
title = validation.require_text_field(payload, 'title', 1,
self.config.max_title_code_points)
members = validation.require_member_ids(payload, 100)
if actor['id'] not in members:
raise InvalidRequest('Создатель чата должен быть указан в member_ids')
if not self.store.users_exist(members):
raise InvalidRequest('member_ids содержит неизвестных пользователей')
return 201, self.store.create_chat(title, members)
def list_chats(self, request, path_params):
actor = self._authenticate(request)
limit, after_key = self._pagination(request, SCOPE_CHATS)
items, has_more = self.store.page_chats(actor['id'], after_key, limit)
for item in items:
item['member_ids'] = self._chat_member_ids(item['id'])
return 200, {'items': items, 'next_cursor': self._next_cursor(SCOPE_CHATS, items, has_more)}
def get_chat(self, request, path_params):
actor = self._authenticate(request)
chat = self._member_chat(actor, path_params['chat_id'])
chat['member_ids'] = self._chat_member_ids(chat['id'])
return 200, chat
# ----------------------------------------------------------- messages
def post_message(self, request, path_params):
actor = self._authenticate(request)
chat = self._member_chat(actor, path_params['chat_id'])
payload = self._json_object(request)
validation.require_fields(payload, ('text',), ('text',))
text = validation.require_text_field(payload, 'text', 1,
self.config.max_text_code_points)
return 201, self.store.add_message(chat['id'], actor['id'], text)
def list_messages(self, request, path_params):
actor = self._authenticate(request)
chat = self._member_chat(actor, path_params['chat_id'])
scope = SCOPE_MESSAGES.format(chat_id=chat['id'])
limit, after_key = self._pagination(request, scope)
items, has_more = self.store.page_messages(chat['id'], after_key, limit)
return 200, {'items': items, 'next_cursor': self._next_cursor(scope, items, has_more)}
# ----------------------------------------------------------- sessions
def create_session(self, request, path_params):
"""Login: only Authorization: Basic username:password, no JSON body."""
authorization = request.headers.get('Authorization') or ''
if not authorization.lower().startswith('basic '):
raise Unauthorized('Требуется авторизация Basic')
try:
raw = base64.b64decode(authorization[len('basic '):].strip()).decode('utf-8')
except Exception:
raise Unauthorized('Некорректные учётные данные') from None
if ':' not in raw:
raise Unauthorized('Некорректные учётные данные')
username, password = raw.split(':', 1)
row = self.store.user_by_username(username)
if row is None or not security.verify_password(password, row['password_hash']):
raise Unauthorized('Неверное имя пользователя или пароль', www_authenticate='Basic realm="messenger", charset="UTF-8"')
token = security.generate_token()
token_hash = security.hash_token(token)
expires_at = utc_now() + dt.timedelta(seconds=self.config.session_ttl_seconds)
self.store.create_session(token_hash, row['id'], expires_at)
user = self.store._public_user({
'id': row['id'],
'username': row['username'],
'display_name': row['display_name'],
'created_at': row['created_at'],
})
return 201, {
'token': token,
'token_type': 'Bearer',
'expires_at': rfc3339(expires_at),
'user': user,
}
def revoke_session(self, request, path_params):
actor = self._authenticate(request)
token = self._bearer_token(request)
self.store.delete_session(security.hash_token(token))
return 204, None
# ------------------------------------------------------------- helpers
def _authenticate(self, request):
"""Lab2 identity: only Authorization: Bearer <token> identifies the actor.
X-User-Id is ignored: it does not change the session owner and alone
grants no access. Basic on business endpoints is 401.
"""
token = self._bearer_token(request)
if token is None:
raise Unauthorized('Требуется идентификация пользователя',
www_authenticate='Bearer realm="messenger"')
user_id = self.store.get_session(security.hash_token(token))
if user_id is None:
raise Unauthorized('Сессия недействительна или истекла',
www_authenticate='Bearer realm="messenger"')
user = self.store.user(user_id)
if user is None:
raise Unauthorized('Пользователь не найден',
www_authenticate='Bearer realm="messenger"')
return user
def _bearer_token(self, request):
authorization = request.headers.get('Authorization') or ''
if not authorization.lower().startswith('bearer '):
return None
return authorization[len('bearer '):].strip()
def _chat_member_ids(self, chat_id):
with self.database.connection() as conn:
with conn.cursor() as cur:
cur.execute(
'SELECT user_id FROM chat_members WHERE chat_id = %s', (str(chat_id),))
return [str(row['user_id']) for row in cur.fetchall()]
def _member_chat(self, actor, raw_chat_id):
"""Foreign and missing chats are indistinguishable: both are 404."""
chat_id = validation.require_uuid_string(raw_chat_id, 'chat_id')
chat = self.store.chat(chat_id)
if chat is None or not self.store.is_member(chat, actor['id']):
raise NotFound('Чат не найден')
return chat
def _json_object(self, request):
content_type = request.headers.get('Content-Type') or ''
if content_type.split(';')[0].strip().lower() != 'application/json':
raise UnsupportedMediaType('Ожидается Content-Type: application/json')
if not request.body:
raise InvalidRequest('Требуется JSON-тело запроса')
try:
payload = json.loads(request.body.decode('utf-8'))
except (UnicodeError, ValueError):
raise InvalidRequest('Тело запроса не является корректным JSON') from None
return validation.require_object(payload)
def _pagination(self, request, scope):
raw_limit = (request.query.get('limit') or [None])[0]
limit = validation.parse_limit(raw_limit, self.config.default_page_limit,
self.config.max_page_limit)
raw_cursor = validation.parse_cursor((request.query.get('cursor') or [None])[0])
if raw_cursor is None:
return limit, None
try:
stamp, identifier = cursor_codec.decode(raw_cursor, scope, self.config.cursor_secret)
except cursor_codec.InvalidCursor:
raise InvalidRequest('cursor некорректен или относится к другому ресурсу') from None
return limit, (stamp, identifier)
def _next_cursor(self, scope, items, has_more):
if not has_more or not items:
return None
last = items[-1]
return cursor_codec.encode(scope, last['created_at'], last['id'],
self.config.cursor_secret)