Lab2
This commit is contained in:
+372
@@ -0,0 +1,372 @@
|
||||
"""Business rules for MTUSI Messenger Lab2."""
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Any
|
||||
from uuid import UUID
|
||||
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app import repositories
|
||||
from app.cache import REVOKED_SESSION, session_cache
|
||||
from app.config import settings
|
||||
from app.errors import ApiError
|
||||
from app.security import (
|
||||
decode_chat_cursor,
|
||||
decode_message_cursor,
|
||||
encode_chat_cursor,
|
||||
encode_message_cursor,
|
||||
generate_session_token,
|
||||
hash_password,
|
||||
hash_session_token,
|
||||
parse_basic_authorization,
|
||||
verify_password,
|
||||
)
|
||||
|
||||
|
||||
def _utc_now() -> datetime:
|
||||
return datetime.now(timezone.utc)
|
||||
|
||||
|
||||
def _to_user(row: dict[str, Any]) -> dict[str, Any]:
|
||||
return {
|
||||
"id": row["id"],
|
||||
"username": row["username"],
|
||||
"display_name": row["display_name"],
|
||||
"created_at": row["created_at"],
|
||||
}
|
||||
|
||||
|
||||
def _to_chat(row: dict[str, Any]) -> dict[str, Any]:
|
||||
return {
|
||||
"id": row["id"],
|
||||
"title": row["title"],
|
||||
"member_ids": row["member_ids"],
|
||||
"created_at": row["created_at"],
|
||||
}
|
||||
|
||||
|
||||
def _to_message(row: dict[str, Any]) -> dict[str, Any]:
|
||||
return {
|
||||
"id": row["id"],
|
||||
"chat_id": row["chat_id"],
|
||||
"sender_id": row["sender_id"],
|
||||
"text": row["text"],
|
||||
"created_at": row["created_at"],
|
||||
}
|
||||
|
||||
|
||||
def _bearer_unauthorized() -> ApiError:
|
||||
return ApiError(
|
||||
401,
|
||||
"unauthorized",
|
||||
"Authentication is required.",
|
||||
headers={
|
||||
"WWW-Authenticate": 'Bearer realm="messenger"',
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def _basic_unauthorized() -> ApiError:
|
||||
return ApiError(
|
||||
401,
|
||||
"unauthorized",
|
||||
"Invalid credentials.",
|
||||
headers={
|
||||
"WWW-Authenticate": (
|
||||
'Basic realm="messenger", charset="UTF-8"'
|
||||
),
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def _invalid_request(message: str) -> ApiError:
|
||||
return ApiError(400, "invalid_request", message)
|
||||
|
||||
|
||||
def _not_found() -> ApiError:
|
||||
return ApiError(404, "not_found", "Object not found.")
|
||||
|
||||
|
||||
async def register_user(
|
||||
db: AsyncSession,
|
||||
*,
|
||||
username: str,
|
||||
display_name: str,
|
||||
password: str,
|
||||
) -> dict[str, Any]:
|
||||
user = await repositories.create_user(
|
||||
db,
|
||||
username=username,
|
||||
display_name=display_name,
|
||||
password_hash=hash_password(password),
|
||||
)
|
||||
|
||||
if user is None:
|
||||
raise ApiError(
|
||||
409,
|
||||
"conflict",
|
||||
"Username is already taken.",
|
||||
)
|
||||
|
||||
return _to_user(user)
|
||||
|
||||
|
||||
async def create_user_session(
|
||||
db: AsyncSession,
|
||||
authorization: str | None,
|
||||
) -> dict[str, Any]:
|
||||
credentials = parse_basic_authorization(authorization)
|
||||
|
||||
if credentials is None:
|
||||
raise _basic_unauthorized()
|
||||
|
||||
username, password = credentials
|
||||
user = await repositories.get_user_by_username(db, username)
|
||||
|
||||
if user is None or not verify_password(
|
||||
user["password_hash"],
|
||||
password,
|
||||
):
|
||||
raise _basic_unauthorized()
|
||||
|
||||
token = generate_session_token()
|
||||
expires_at = _utc_now() + timedelta(
|
||||
seconds=settings.session_ttl_seconds
|
||||
)
|
||||
|
||||
await repositories.create_session(
|
||||
db,
|
||||
user_id=user["id"],
|
||||
token_hash=hash_session_token(token),
|
||||
expires_at=expires_at,
|
||||
)
|
||||
|
||||
return {
|
||||
"token": token,
|
||||
"token_type": "Bearer",
|
||||
"expires_at": expires_at,
|
||||
"user": _to_user(user),
|
||||
}
|
||||
|
||||
|
||||
async def current_user_from_bearer_token(
|
||||
db: AsyncSession,
|
||||
token: str,
|
||||
) -> dict[str, Any]:
|
||||
token_hash = hash_session_token(token)
|
||||
cached = await session_cache.get(token_hash)
|
||||
|
||||
if cached is REVOKED_SESSION:
|
||||
raise _bearer_unauthorized()
|
||||
|
||||
if cached is not None:
|
||||
return cached
|
||||
|
||||
# Cache miss or cache unavailable: PostgreSQL decides.
|
||||
session_user = await repositories.get_active_session_user(db, token_hash)
|
||||
|
||||
if session_user is None:
|
||||
raise _bearer_unauthorized()
|
||||
|
||||
user = _to_user(session_user)
|
||||
await session_cache.put(token_hash, user, session_user["expires_at"])
|
||||
return user
|
||||
|
||||
|
||||
async def logout_current_session(
|
||||
db: AsyncSession,
|
||||
token: str,
|
||||
) -> None:
|
||||
token_hash = hash_session_token(token)
|
||||
revoked = await repositories.revoke_active_session(db, token_hash)
|
||||
|
||||
if not revoked:
|
||||
raise _bearer_unauthorized()
|
||||
|
||||
# Invalidate after COMMIT in the source of truth.
|
||||
await session_cache.revoke(token_hash)
|
||||
|
||||
|
||||
async def create_chat(
|
||||
db: AsyncSession,
|
||||
*,
|
||||
title: str,
|
||||
member_ids: list[UUID],
|
||||
current_user: dict[str, Any],
|
||||
) -> dict[str, Any]:
|
||||
unique_member_ids = set(member_ids)
|
||||
|
||||
if len(unique_member_ids) != len(member_ids):
|
||||
raise _invalid_request(
|
||||
"member_ids must not contain duplicates."
|
||||
)
|
||||
|
||||
if current_user["id"] not in unique_member_ids:
|
||||
raise _invalid_request(
|
||||
"The current user must be included in member_ids."
|
||||
)
|
||||
|
||||
existing_ids = await repositories.user_ids_that_exist(
|
||||
db,
|
||||
unique_member_ids,
|
||||
)
|
||||
|
||||
if existing_ids != unique_member_ids:
|
||||
raise _invalid_request(
|
||||
"One or more member_ids do not exist."
|
||||
)
|
||||
|
||||
chat = await repositories.create_chat_with_members(
|
||||
db,
|
||||
title=title,
|
||||
member_ids=member_ids,
|
||||
)
|
||||
|
||||
return _to_chat(chat)
|
||||
|
||||
|
||||
async def get_chat(
|
||||
db: AsyncSession,
|
||||
*,
|
||||
chat_id: UUID,
|
||||
current_user: dict[str, Any],
|
||||
) -> dict[str, Any]:
|
||||
chat = await repositories.get_accessible_chat(
|
||||
db,
|
||||
chat_id=chat_id,
|
||||
user_id=current_user["id"],
|
||||
)
|
||||
|
||||
if chat is None:
|
||||
raise _not_found()
|
||||
|
||||
return _to_chat(chat)
|
||||
|
||||
|
||||
async def list_chats(
|
||||
db: AsyncSession,
|
||||
*,
|
||||
limit: int,
|
||||
cursor: str | None,
|
||||
current_user: dict[str, Any],
|
||||
) -> dict[str, Any]:
|
||||
cursor_created_at: datetime | None = None
|
||||
cursor_id: UUID | None = None
|
||||
|
||||
if cursor is not None:
|
||||
decoded = decode_chat_cursor(cursor)
|
||||
|
||||
if decoded is None:
|
||||
raise _invalid_request("Invalid cursor.")
|
||||
|
||||
cursor_created_at, cursor_id = decoded
|
||||
|
||||
rows = await repositories.list_chats_for_user(
|
||||
db,
|
||||
user_id=current_user["id"],
|
||||
limit=limit,
|
||||
cursor_created_at=cursor_created_at,
|
||||
cursor_id=cursor_id,
|
||||
)
|
||||
|
||||
has_more = len(rows) > limit
|
||||
page = rows[:limit]
|
||||
|
||||
next_cursor = None
|
||||
if has_more and page:
|
||||
last = page[-1]
|
||||
next_cursor = encode_chat_cursor(
|
||||
last["created_at"],
|
||||
last["id"],
|
||||
)
|
||||
|
||||
return {
|
||||
"items": [_to_chat(row) for row in page],
|
||||
"next_cursor": next_cursor,
|
||||
}
|
||||
|
||||
|
||||
async def create_message(
|
||||
db: AsyncSession,
|
||||
*,
|
||||
chat_id: UUID,
|
||||
text_value: str,
|
||||
current_user: dict[str, Any],
|
||||
) -> dict[str, Any]:
|
||||
chat = await repositories.get_accessible_chat(
|
||||
db,
|
||||
chat_id=chat_id,
|
||||
user_id=current_user["id"],
|
||||
)
|
||||
|
||||
if chat is None:
|
||||
raise _not_found()
|
||||
|
||||
message = await repositories.create_message(
|
||||
db,
|
||||
chat_id=chat_id,
|
||||
sender_id=current_user["id"],
|
||||
text_value=text_value,
|
||||
)
|
||||
|
||||
return _to_message(message)
|
||||
|
||||
|
||||
async def list_messages(
|
||||
db: AsyncSession,
|
||||
*,
|
||||
chat_id: UUID,
|
||||
limit: int,
|
||||
cursor: str | None,
|
||||
current_user: dict[str, Any],
|
||||
) -> dict[str, Any]:
|
||||
chat = await repositories.get_accessible_chat(
|
||||
db,
|
||||
chat_id=chat_id,
|
||||
user_id=current_user["id"],
|
||||
)
|
||||
|
||||
if chat is None:
|
||||
raise _not_found()
|
||||
|
||||
cursor_created_at: datetime | None = None
|
||||
cursor_id: UUID | None = None
|
||||
|
||||
if cursor is not None:
|
||||
decoded = decode_message_cursor(cursor)
|
||||
|
||||
if decoded is None:
|
||||
raise _invalid_request("Invalid cursor.")
|
||||
|
||||
cursor_chat_id, cursor_created_at, cursor_id = decoded
|
||||
|
||||
if cursor_chat_id != chat_id:
|
||||
raise _invalid_request(
|
||||
"Cursor belongs to another chat."
|
||||
)
|
||||
|
||||
rows = await repositories.list_messages_keyset(
|
||||
db,
|
||||
chat_id=chat_id,
|
||||
limit=limit,
|
||||
cursor_created_at=cursor_created_at,
|
||||
cursor_id=cursor_id,
|
||||
)
|
||||
|
||||
has_more = len(rows) > limit
|
||||
page = rows[:limit]
|
||||
|
||||
next_cursor = None
|
||||
if has_more and page:
|
||||
last = page[-1]
|
||||
next_cursor = encode_message_cursor(
|
||||
chat_id,
|
||||
last["created_at"],
|
||||
last["id"],
|
||||
)
|
||||
|
||||
return {
|
||||
"items": [_to_message(row) for row in page],
|
||||
"next_cursor": next_cursor,
|
||||
}
|
||||
Reference in New Issue
Block a user