from __future__ import annotations import hashlib import os import secrets import uuid from dataclasses import dataclass from datetime import datetime, timedelta, timezone from typing import List, Optional, Tuple from uuid import UUID from argon2 import PasswordHasher from argon2.exceptions import VerifyMismatchError from sqlalchemy import func, select, tuple_ from sqlalchemy.exc import IntegrityError from .db import session_scope from .errors import AppError from .tables import ChatMemberRow, ChatRow, MessageRow, SessionRow, UserRow password_hasher = PasswordHasher() def utc_now() -> datetime: return datetime.now(timezone.utc) def format_ts(value: datetime) -> str: if value.tzinfo is None: value = value.replace(tzinfo=timezone.utc) return value.astimezone(timezone.utc).isoformat(timespec="microseconds").replace("+00:00", "Z") def parse_ts(value: str) -> datetime: return datetime.fromisoformat(value.replace("Z", "+00:00")) def session_ttl_seconds() -> int: raw = os.environ.get("SESSION_TTL_SECONDS", "3600") return max(1, int(raw)) def hash_token(token: str) -> str: return hashlib.sha256(token.encode("utf-8")).hexdigest() @dataclass class User: id: str username: str display_name: str created_at: str def to_dict(self) -> dict: return { "id": self.id, "username": self.username, "display_name": self.display_name, "created_at": self.created_at, } @dataclass class Chat: id: str title: str member_ids: List[str] created_at: str def to_dict(self) -> dict: return { "id": self.id, "title": self.title, "member_ids": list(self.member_ids), "created_at": self.created_at, } @dataclass class Message: id: str chat_id: str sender_id: str text: str created_at: str def to_dict(self) -> dict: return { "id": self.id, "chat_id": self.chat_id, "sender_id": self.sender_id, "text": self.text, "created_at": self.created_at, } @dataclass class Session: token: str token_type: str expires_at: str user: User def to_dict(self) -> dict: return { "token": self.token, "token_type": self.token_type, "expires_at": self.expires_at, "user": self.user.to_dict(), } def _user_from_row(row: UserRow) -> User: return User( id=str(row.id), username=row.username, display_name=row.display_name, created_at=format_ts(row.created_at), ) def _chat_from_row(row: ChatRow, member_ids: List[str]) -> Chat: return Chat( id=str(row.id), title=row.title, member_ids=member_ids, created_at=format_ts(row.created_at), ) def _message_from_row(row: MessageRow) -> Message: return Message( id=str(row.id), chat_id=str(row.chat_id), sender_id=str(row.sender_id), text=row.text, created_at=format_ts(row.created_at), ) def _member_ids(session, chat_id: UUID) -> List[str]: rows = session.scalars( select(ChatMemberRow.user_id) .where(ChatMemberRow.chat_id == chat_id) .order_by(ChatMemberRow.user_id) ).all() return [str(user_id) for user_id in rows] class Store: def create_user(self, username: str, display_name: str, password: str) -> User: row = UserRow( id=uuid.uuid4(), username=username, display_name=display_name, password_hash=password_hasher.hash(password), created_at=utc_now(), ) try: with session_scope() as session: session.add(row) session.flush() return _user_from_row(row) except IntegrityError as exc: raise AppError(409, "conflict", "Username is already taken") from exc def get_user(self, user_id: str) -> Optional[User]: with session_scope() as session: row = session.get(UserRow, UUID(user_id)) return _user_from_row(row) if row else None def create_session(self, username: str, password: str) -> Session: with session_scope() as session: row = session.scalar(select(UserRow).where(UserRow.username == username)) if row is None: raise AppError( 401, "unauthorized", "Invalid credentials", headers={"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"'}, ) try: password_hasher.verify(row.password_hash, password) except VerifyMismatchError as exc: raise AppError( 401, "unauthorized", "Invalid credentials", headers={"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"'}, ) from exc token = secrets.token_urlsafe(32) expires_at = utc_now() + timedelta(seconds=session_ttl_seconds()) session.add( SessionRow( token_hash=hash_token(token), user_id=row.id, expires_at=expires_at, created_at=utc_now(), ) ) user = _user_from_row(row) return Session( token=token, token_type="Bearer", expires_at=format_ts(expires_at), user=user, ) def resolve_bearer(self, token: str) -> str: with session_scope() as session: row = session.get(SessionRow, hash_token(token)) challenge = {"WWW-Authenticate": 'Bearer realm="messenger"'} if row is None: raise AppError(401, "unauthorized", "Invalid session", headers=challenge) if row.revoked_at is not None: raise AppError(401, "unauthorized", "Session revoked", headers=challenge) expires_at = row.expires_at if expires_at.tzinfo is None: expires_at = expires_at.replace(tzinfo=timezone.utc) if expires_at <= utc_now(): raise AppError(401, "unauthorized", "Session expired", headers=challenge) return str(row.user_id) def revoke_session(self, token: str) -> None: with session_scope() as session: row = session.get(SessionRow, hash_token(token), with_for_update=True) challenge = {"WWW-Authenticate": 'Bearer realm="messenger"'} if row is None: raise AppError(401, "unauthorized", "Invalid session", headers=challenge) if row.revoked_at is not None: raise AppError(401, "unauthorized", "Session revoked", headers=challenge) expires_at = row.expires_at if expires_at.tzinfo is None: expires_at = expires_at.replace(tzinfo=timezone.utc) if expires_at <= utc_now(): raise AppError(401, "unauthorized", "Session expired", headers=challenge) row.revoked_at = utc_now() def create_chat(self, title: str, member_ids: List[str]) -> Chat: chat_id = uuid.uuid4() member_uuids = [UUID(m) for m in member_ids] with session_scope() as session: existing = session.scalar( select(func.count()).select_from(UserRow).where(UserRow.id.in_(member_uuids)) ) if existing != len(member_uuids): raise AppError(400, "invalid_request", "Unknown member in member_ids") chat = ChatRow(id=chat_id, title=title, created_at=utc_now()) session.add(chat) for member_id in member_uuids: session.add(ChatMemberRow(chat_id=chat_id, user_id=member_id)) session.flush() return _chat_from_row(chat, list(member_ids)) def get_chat(self, chat_id: str) -> Optional[Chat]: with session_scope() as session: row = session.get(ChatRow, UUID(chat_id)) if row is None: return None return _chat_from_row(row, _member_ids(session, row.id)) def list_chats_for_user( self, user_id: str, limit: int, after: Optional[Tuple[str, str]] = None, ) -> Tuple[List[Chat], Optional[Chat]]: with session_scope() as session: stmt = ( select(ChatRow) .join(ChatMemberRow, ChatMemberRow.chat_id == ChatRow.id) .where(ChatMemberRow.user_id == UUID(user_id)) ) if after is not None: stmt = stmt.where( tuple_(ChatRow.created_at, ChatRow.id) > (parse_ts(after[0]), UUID(after[1])) ) stmt = stmt.order_by(ChatRow.created_at.asc(), ChatRow.id.asc()).limit(limit + 1) rows = list(session.scalars(stmt).all()) chats = [_chat_from_row(row, _member_ids(session, row.id)) for row in rows] page = chats[:limit] has_more = len(chats) > limit last = page[-1] if page and has_more else None return page, last def create_message(self, chat_id: str, sender_id: str, text: str) -> Message: row = MessageRow( id=uuid.uuid4(), chat_id=UUID(chat_id), sender_id=UUID(sender_id), text=text, created_at=utc_now(), ) with session_scope() as session: session.add(row) session.flush() return _message_from_row(row) def list_messages( self, chat_id: str, limit: int, after: Optional[Tuple[str, str]] = None, ) -> Tuple[List[Message], Optional[Message]]: with session_scope() as session: stmt = select(MessageRow).where(MessageRow.chat_id == UUID(chat_id)) if after is not None: stmt = stmt.where( tuple_(MessageRow.created_at, MessageRow.id) > (parse_ts(after[0]), UUID(after[1])) ) stmt = stmt.order_by(MessageRow.created_at.asc(), MessageRow.id.asc()).limit( limit + 1 ) rows = list(session.scalars(stmt).all()) messages = [_message_from_row(row) for row in rows] page = messages[:limit] has_more = len(messages) > limit last = page[-1] if page and has_more else None return page, last store = Store()