forked from mtusi2026/mtusi2026lab3
фикс из пр
This commit is contained in:
+27
-1
@@ -57,4 +57,30 @@ def decode_cursor(cursor: str) -> tuple[UUID, datetime, UUID]:
|
||||
binascii.Error,
|
||||
json.JSONDecodeError,
|
||||
) as exc:
|
||||
raise ValueError("Invalid cursor") from exc
|
||||
raise ValueError("Invalid cursor") from exc
|
||||
|
||||
|
||||
def encode_chat_cursor(user_id: UUID, created_at: datetime, chat_id: UUID) -> str:
|
||||
data = {
|
||||
"user_id": str(user_id),
|
||||
"created_at": created_at.isoformat(),
|
||||
"chat_id": str(chat_id),
|
||||
}
|
||||
raw = json.dumps(data, separators=(",", ":")).encode("utf-8")
|
||||
return base64.urlsafe_b64encode(raw).decode("ascii")
|
||||
|
||||
|
||||
def decode_chat_cursor(cursor: str) -> tuple[UUID, datetime, UUID]:
|
||||
try:
|
||||
raw = base64.b64decode(cursor.encode("ascii"), altchars=b"-_", validate=True)
|
||||
data = json.loads(raw.decode("utf-8"))
|
||||
if not isinstance(data, dict) or set(data) != {"user_id", "created_at", "chat_id"}:
|
||||
raise ValueError("Invalid cursor")
|
||||
user_id = UUID(data["user_id"])
|
||||
created_at = datetime.fromisoformat(data["created_at"])
|
||||
chat_id = UUID(data["chat_id"])
|
||||
if created_at.tzinfo is None or created_at.utcoffset() is None:
|
||||
raise ValueError("Invalid cursor")
|
||||
return user_id, created_at, chat_id
|
||||
except (ValueError, TypeError, KeyError, UnicodeError, binascii.Error, json.JSONDecodeError) as exc:
|
||||
raise ValueError("Invalid cursor") from exc
|
||||
|
||||
+21
-10
@@ -2,14 +2,14 @@ from datetime import datetime, timedelta, timezone
|
||||
from uuid import UUID, uuid4
|
||||
import os
|
||||
import re
|
||||
import base64
|
||||
import binascii
|
||||
|
||||
from fastapi import Depends, FastAPI, Request, Header
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from fastapi.responses import JSONResponse
|
||||
from fastapi.security import (
|
||||
HTTPAuthorizationCredentials,
|
||||
HTTPBasic,
|
||||
HTTPBasicCredentials,
|
||||
HTTPBearer,
|
||||
)
|
||||
from sqlalchemy.exc import IntegrityError, SQLAlchemyError
|
||||
@@ -50,7 +50,6 @@ async def lifespan(app: FastAPI):
|
||||
app = FastAPI(lifespan=lifespan)
|
||||
INSTANCE_ID = os.getenv("INSTANCE_ID") or str(uuid4())
|
||||
|
||||
basic_security = HTTPBasic(auto_error=False)
|
||||
bearer_security = HTTPBearer(auto_error=False)
|
||||
|
||||
|
||||
@@ -300,22 +299,32 @@ async def get_me(
|
||||
status_code=201,
|
||||
)
|
||||
async def create_auth_session(
|
||||
credentials: HTTPBasicCredentials | None = Depends(basic_security),
|
||||
authorization: str | None = Header(default=None),
|
||||
session: AsyncSession = Depends(get_db_session),
|
||||
):
|
||||
credentials = None
|
||||
if authorization is not None:
|
||||
scheme, separator, encoded = authorization.partition(" ")
|
||||
if separator and scheme.lower() == "basic":
|
||||
try:
|
||||
decoded = base64.b64decode(encoded.strip(), validate=True).decode("utf-8")
|
||||
if ":" in decoded:
|
||||
credentials = decoded.split(":", 1)
|
||||
except (ValueError, UnicodeError, binascii.Error):
|
||||
pass
|
||||
if credentials is None:
|
||||
raise APIError(
|
||||
status_code=401,
|
||||
code="unauthorized",
|
||||
message="Unauthorized",
|
||||
headers={
|
||||
"WWW-Authenticate": 'Basic realm="messenger"',
|
||||
"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"',
|
||||
},
|
||||
)
|
||||
|
||||
user_credentials = await get_user_credentials_by_username(
|
||||
session,
|
||||
credentials.username,
|
||||
credentials[0],
|
||||
)
|
||||
|
||||
if user_credentials is None:
|
||||
@@ -324,20 +333,20 @@ async def create_auth_session(
|
||||
code="unauthorized",
|
||||
message="Unauthorized",
|
||||
headers={
|
||||
"WWW-Authenticate": 'Basic realm="messenger"',
|
||||
"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"',
|
||||
},
|
||||
)
|
||||
|
||||
if not verify_password(
|
||||
user_credentials.password_hash,
|
||||
credentials.password,
|
||||
credentials[1],
|
||||
):
|
||||
raise APIError(
|
||||
status_code=401,
|
||||
code="unauthorized",
|
||||
message="Unauthorized",
|
||||
headers={
|
||||
"WWW-Authenticate": 'Basic realm="messenger"',
|
||||
"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"',
|
||||
},
|
||||
)
|
||||
|
||||
@@ -401,6 +410,7 @@ async def create_chat_endpoint(
|
||||
)
|
||||
async def get_chats(
|
||||
limit: int = 50,
|
||||
cursor: str | None = None,
|
||||
current_user: User = Depends(get_current_user),
|
||||
session: AsyncSession = Depends(get_db_session),
|
||||
) -> ChatPage:
|
||||
@@ -415,6 +425,7 @@ async def get_chats(
|
||||
session=session,
|
||||
current_user_id=current_user.id,
|
||||
limit=limit,
|
||||
cursor=cursor,
|
||||
)
|
||||
|
||||
|
||||
@@ -514,4 +525,4 @@ async def get_messages_endpoint(
|
||||
current_user_id=current_user.id,
|
||||
limit=limit,
|
||||
cursor=cursor,
|
||||
)
|
||||
)
|
||||
|
||||
+40
-31
@@ -8,7 +8,7 @@ from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from src.models import Chat, ChatPage, CreateChat, CreateUser, User, CreateMessage, Message, MessagePage
|
||||
from src.security import hash_password
|
||||
from src.errors import APIError
|
||||
from src.cursor import decode_cursor, encode_cursor
|
||||
from src.cursor import decode_cursor, encode_cursor, decode_chat_cursor, encode_chat_cursor
|
||||
|
||||
|
||||
async def create_user(
|
||||
@@ -269,33 +269,48 @@ async def list_chats(
|
||||
session: AsyncSession,
|
||||
current_user_id: UUID,
|
||||
limit: int,
|
||||
cursor: str | None = None,
|
||||
) -> ChatPage:
|
||||
chats_result = await session.execute(
|
||||
cursor_created_at = None
|
||||
cursor_chat_id = None
|
||||
if cursor is not None:
|
||||
try:
|
||||
cursor_user_id, cursor_created_at, cursor_chat_id = decode_chat_cursor(cursor)
|
||||
except ValueError as exc:
|
||||
raise APIError(status_code=400, code="invalid_request", message="Invalid cursor") from exc
|
||||
if cursor_user_id != current_user_id:
|
||||
raise APIError(status_code=400, code="invalid_request", message="Invalid cursor")
|
||||
|
||||
result = await session.execute(
|
||||
text(
|
||||
"""
|
||||
SELECT
|
||||
c.id,
|
||||
c.title,
|
||||
c.created_at
|
||||
SELECT c.id, c.title, c.created_at
|
||||
FROM chats AS c
|
||||
JOIN chat_members AS cm
|
||||
ON cm.chat_id = c.id
|
||||
JOIN chat_members AS cm ON cm.chat_id = c.id
|
||||
WHERE cm.user_id = :current_user_id
|
||||
AND (
|
||||
CAST(:cursor_created_at AS timestamptz) IS NULL
|
||||
OR (c.created_at, c.id) > (
|
||||
CAST(:cursor_created_at AS timestamptz),
|
||||
CAST(:cursor_chat_id AS uuid)
|
||||
)
|
||||
)
|
||||
ORDER BY c.created_at, c.id
|
||||
LIMIT :limit
|
||||
LIMIT :fetch_limit
|
||||
"""
|
||||
),
|
||||
{
|
||||
"current_user_id": current_user_id,
|
||||
"limit": limit,
|
||||
"cursor_created_at": cursor_created_at,
|
||||
"cursor_chat_id": cursor_chat_id,
|
||||
"fetch_limit": limit + 1,
|
||||
},
|
||||
)
|
||||
|
||||
chat_rows = chats_result.all()
|
||||
|
||||
rows = result.all()
|
||||
has_more = len(rows) > limit
|
||||
page_rows = rows[:limit]
|
||||
items = []
|
||||
|
||||
for chat_row in chat_rows:
|
||||
for chat_row in page_rows:
|
||||
members_result = await session.execute(
|
||||
text(
|
||||
"""
|
||||
@@ -305,29 +320,23 @@ async def list_chats(
|
||||
ORDER BY user_id
|
||||
"""
|
||||
),
|
||||
{
|
||||
"chat_id": chat_row.id,
|
||||
},
|
||||
{"chat_id": chat_row.id},
|
||||
)
|
||||
|
||||
member_ids = [
|
||||
UUID(str(row.user_id))
|
||||
for row in members_result
|
||||
]
|
||||
|
||||
items.append(
|
||||
Chat(
|
||||
id=UUID(str(chat_row.id)),
|
||||
title=chat_row.title,
|
||||
member_ids=member_ids,
|
||||
member_ids=[UUID(str(row.user_id)) for row in members_result],
|
||||
created_at=chat_row.created_at,
|
||||
)
|
||||
)
|
||||
|
||||
return ChatPage(
|
||||
items=items,
|
||||
next_cursor=None,
|
||||
)
|
||||
next_cursor = None
|
||||
if has_more:
|
||||
last = page_rows[-1]
|
||||
next_cursor = encode_chat_cursor(
|
||||
current_user_id, last.created_at, UUID(str(last.id))
|
||||
)
|
||||
return ChatPage(items=items, next_cursor=next_cursor)
|
||||
|
||||
|
||||
async def create_message(
|
||||
@@ -643,4 +652,4 @@ async def get_messages(
|
||||
return MessagePage(
|
||||
items=items,
|
||||
next_cursor=next_cursor,
|
||||
)
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user