Files
mtusi2026lab4/app/validation.py
T
dawuduk d208a87ae8 Перенести рабочий стенд lab3 в репозиторий lab4.
API, Postgres, Redis и HAProxy остаются базой для вложений: сессии и история уже общие для нескольких реплик.
2026-11-09 00:04:59 +03:00

103 lines
2.8 KiB
Python

import json
import re
from typing import Any, Dict, Optional, Tuple
from uuid import UUID
USERNAME_RE = re.compile(r"^[a-z0-9_]{3,32}$")
IDEMPOTENCY_RE = re.compile(r"^[A-Za-z0-9._:-]{1,128}$")
def parse_json_body(raw: bytes) -> Tuple[Optional[Dict[str, Any]], Optional[str]]:
if not raw:
return None, "empty body"
try:
data = json.loads(raw.decode("utf-8"))
except (UnicodeDecodeError, json.JSONDecodeError):
return None, "malformed JSON"
if not isinstance(data, dict):
return None, "JSON body must be an object"
return data, None
def require_exact_keys(data: Dict[str, Any], allowed: set, required: set) -> Optional[str]:
keys = set(data.keys())
if keys - allowed:
return "unexpected fields"
if required - keys:
return "missing required fields"
return None
def validate_username(value: Any) -> Optional[str]:
if not isinstance(value, str) or not USERNAME_RE.fullmatch(value):
return "invalid username"
return None
def validate_display_name(value: Any) -> Optional[str]:
if not isinstance(value, str):
return "invalid display_name"
if not value.strip():
return "display_name must not be blank"
if len(value) > 100:
return "display_name too long"
return None
def validate_password(value: Any) -> Optional[str]:
if not isinstance(value, str):
return "invalid password"
if not value.strip():
return "password must not be blank"
if len(value) < 12 or len(value) > 128:
return "password length"
return None
def validate_title(value: Any) -> Optional[str]:
if not isinstance(value, str):
return "invalid title"
if not value.strip():
return "title must not be blank"
if len(value) > 100:
return "title too long"
return None
def validate_uuid(value: Any) -> Optional[str]:
if not isinstance(value, str):
return "invalid uuid"
try:
UUID(value)
except ValueError:
return "invalid uuid"
return None
def validate_idempotency_key(value: Optional[str]) -> Optional[str]:
if value is None or IDEMPOTENCY_RE.fullmatch(value) is None:
return "invalid idempotency key"
return None
def validate_message_text(value: Any) -> Optional[str]:
if not isinstance(value, str):
return "invalid text"
if not value.strip():
return "text must not be blank"
if len(value) > 4000:
return "text too long"
return None
def validate_limit(value: Optional[str], default: int = 50) -> Tuple[Optional[int], Optional[str]]:
if value is None:
return default, None
try:
limit = int(value)
except ValueError:
return None, "invalid limit"
if limit < 1 or limit > 100:
return None, "limit out of range"
return limit, None