forked from mtusi2026/mtusi2026lab2
Проверять формат cursor: неверный cursor даёт 400
This commit is contained in:
+15
-8
@@ -22,7 +22,7 @@ import security
|
||||
from errors import ApiError, bad_credentials, error_response, invalid, not_found, unauthorized
|
||||
from schemas import CreateChat, CreateMessage, CreateUser
|
||||
from sessions import Sessions
|
||||
from store import Store, UnknownMember, UsernameTaken, timestamp
|
||||
from store import TIME_FORMAT, Store, UnknownMember, UsernameTaken, timestamp
|
||||
|
||||
logging.basicConfig(
|
||||
level=config.LOG_LEVEL.upper(),
|
||||
@@ -129,8 +129,8 @@ def current_session(request: Request) -> Session:
|
||||
return Session(user_id, token)
|
||||
|
||||
|
||||
def encode_cursor(scope: str, item: dict) -> str:
|
||||
raw = json.dumps([scope, item["created_at"], item["id"]])
|
||||
def encode_cursor(scope: str, created_at: str, item_id: str) -> str:
|
||||
raw = json.dumps([scope, created_at, item_id])
|
||||
return base64.urlsafe_b64encode(raw.encode()).decode()
|
||||
|
||||
|
||||
@@ -139,18 +139,25 @@ def decode_cursor(scope: str, cursor):
|
||||
if cursor is None:
|
||||
return None
|
||||
try:
|
||||
cursor_scope, created_at, item_id = json.loads(base64.urlsafe_b64decode(cursor.encode()))
|
||||
key = [datetime.strptime(created_at, "%Y-%m-%dT%H:%M:%S.%fZ").replace(tzinfo=timezone.utc), str(UUID(item_id))]
|
||||
# validate=True: символ вне алфавита base64 — ошибка, а не пропускается молча
|
||||
cursor_scope, created_at, item_id = json.loads(base64.b64decode(cursor, altchars=b"-_", validate=True))
|
||||
# время и id принимаются только в том виде, в котором их выдаёт сам сервер
|
||||
moment = datetime.strptime(created_at, TIME_FORMAT).replace(tzinfo=timezone.utc)
|
||||
time_ok = moment.strftime(TIME_FORMAT) == created_at
|
||||
id_ok = str(UUID(item_id)) == item_id
|
||||
except (TypeError, ValueError, AttributeError):
|
||||
raise invalid("Некорректный cursor")
|
||||
# cursor действует только для того списка, в котором был выдан
|
||||
if cursor_scope != scope:
|
||||
if cursor_scope != scope or not time_ok or not id_ok:
|
||||
raise invalid("Некорректный cursor")
|
||||
return key
|
||||
# у одной позиции есть ровно одна запись cursor: другое оформление JSON или base64 не принимается
|
||||
if encode_cursor(scope, created_at, item_id) != cursor:
|
||||
raise invalid("Некорректный cursor")
|
||||
return [moment, item_id]
|
||||
|
||||
|
||||
def page(scope: str, items: list, has_more: bool) -> dict:
|
||||
next_cursor = encode_cursor(scope, items[-1]) if has_more else None
|
||||
next_cursor = encode_cursor(scope, items[-1]["created_at"], items[-1]["id"]) if has_more else None
|
||||
return {"items": items, "next_cursor": next_cursor}
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user