forked from mtusi2026/mtusi2026lab4
feat(lab4): implement S3 attachments and image validation
This commit is contained in:
@@ -0,0 +1,47 @@
|
||||
import base64
|
||||
import binascii
|
||||
import json
|
||||
import re
|
||||
from datetime import datetime
|
||||
from uuid import UUID
|
||||
|
||||
from src.errors import invalid
|
||||
|
||||
|
||||
def encode_cursor(scope, item):
|
||||
data = {"scope": scope, "created_at": item["created_at"], "id": item["id"]}
|
||||
raw = json.dumps(data, separators=(",", ":")).encode("utf-8")
|
||||
return base64.urlsafe_b64encode(raw).decode("ascii").rstrip("=")
|
||||
|
||||
|
||||
def parse_page(limit, cursor, scope):
|
||||
if len(limit) > 10 or re.fullmatch(r"[0-9]+", limit) is None:
|
||||
invalid("limit должен быть целым числом от 1 до 100")
|
||||
size = int(limit)
|
||||
if not 1 <= size <= 100:
|
||||
invalid("limit должен быть от 1 до 100")
|
||||
if cursor is None:
|
||||
return size, None
|
||||
if not cursor or len(cursor) > 2048:
|
||||
invalid("Некорректный cursor")
|
||||
try:
|
||||
raw = base64.b64decode(
|
||||
cursor + "=" * (-len(cursor) % 4), altchars=b"-_", validate=True
|
||||
)
|
||||
data = json.loads(raw)
|
||||
if not isinstance(data, dict) or set(data) != {"scope", "created_at", "id"}:
|
||||
raise ValueError
|
||||
if data["scope"] != scope or not isinstance(data["created_at"], str):
|
||||
raise ValueError
|
||||
if re.fullmatch(
|
||||
r"[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(?:\.[0-9]{1,6})?Z",
|
||||
data["created_at"],
|
||||
) is None:
|
||||
raise ValueError
|
||||
created_at = datetime.fromisoformat(data["created_at"][:-1] + "+00:00")
|
||||
if created_at.tzinfo is None:
|
||||
raise ValueError
|
||||
item_id = UUID(data["id"])
|
||||
except (ValueError, TypeError, AttributeError, binascii.Error):
|
||||
invalid("Некорректный cursor или cursor от другого ресурса")
|
||||
return size, (created_at, item_id)
|
||||
Reference in New Issue
Block a user