forked from mtusi2026/mtusi2026lab2
172 lines
6.5 KiB
Python
172 lines
6.5 KiB
Python
import base64
|
||
import datetime as dt
|
||
import json
|
||
import re
|
||
import uuid
|
||
from typing import Any, Dict, List, Optional, Tuple
|
||
from app.errors import APIError, BadRequestError
|
||
|
||
USERNAME_REGEX = re.compile(r'^[a-z0-9_]{3,32}$')
|
||
|
||
|
||
def now_utc_z() -> str:
|
||
"""Return current server time in RFC 3339 UTC format ending with Z."""
|
||
return dt.datetime.now(dt.timezone.utc).strftime('%Y-%m-%dT%H:%M:%S.%fZ')
|
||
|
||
|
||
def parse_rfc3339(value: str) -> dt.datetime:
|
||
"""Parse RFC 3339 UTC timestamp ending with Z."""
|
||
if not isinstance(value, str) or not value.endswith('Z'):
|
||
raise ValueError("Timestamp must be UTC ending with Z")
|
||
return dt.datetime.fromisoformat(value[:-1] + '+00:00')
|
||
|
||
|
||
def validate_uuid(value: Any, field_name: str = "id") -> str:
|
||
if not isinstance(value, str):
|
||
raise BadRequestError(f"{field_name} must be a string")
|
||
try:
|
||
parsed = uuid.UUID(value)
|
||
except (ValueError, TypeError, AttributeError):
|
||
raise BadRequestError(f"{field_name} must be a valid UUID")
|
||
return str(parsed)
|
||
|
||
|
||
def validate_create_user(body: Any) -> Dict[str, Any]:
|
||
if not isinstance(body, dict):
|
||
raise BadRequestError("Request body must be a JSON object")
|
||
allowed_fields = {'username', 'display_name', 'password'}
|
||
if set(body.keys()) != allowed_fields:
|
||
extra = set(body.keys()) - allowed_fields
|
||
missing = allowed_fields - set(body.keys())
|
||
if missing:
|
||
raise BadRequestError(f"Missing required fields: {', '.join(missing)}")
|
||
if extra:
|
||
raise BadRequestError(f"Unexpected fields: {', '.join(extra)}")
|
||
|
||
username = body.get('username')
|
||
display_name = body.get('display_name')
|
||
|
||
if not isinstance(username, str) or not USERNAME_REGEX.fullmatch(username):
|
||
raise BadRequestError("username must match ^[a-z0-9_]{3,32}$")
|
||
|
||
if not isinstance(display_name, str):
|
||
raise BadRequestError("display_name must be a string")
|
||
if len(display_name) < 1 or len(display_name) > 100:
|
||
raise BadRequestError("display_name length must be between 1 and 100 characters")
|
||
if not display_name.strip():
|
||
raise BadRequestError("display_name cannot consist only of whitespace")
|
||
|
||
password = body['password']
|
||
if not isinstance(password, str) or not 12 <= len(password) <= 128 or not password.strip():
|
||
raise BadRequestError('password must contain 12–128 nonblank characters')
|
||
return {'username': username, 'display_name': display_name, 'password': password}
|
||
|
||
|
||
def validate_create_chat(body: Any) -> Dict[str, Any]:
|
||
if not isinstance(body, dict):
|
||
raise BadRequestError("Request body must be a JSON object")
|
||
allowed_fields = {'title', 'member_ids'}
|
||
if set(body.keys()) != allowed_fields:
|
||
extra = set(body.keys()) - allowed_fields
|
||
missing = allowed_fields - set(body.keys())
|
||
if missing:
|
||
raise BadRequestError(f"Missing required fields: {', '.join(missing)}")
|
||
if extra:
|
||
raise BadRequestError(f"Unexpected fields: {', '.join(extra)}")
|
||
|
||
title = body.get('title')
|
||
member_ids = body.get('member_ids')
|
||
|
||
if not isinstance(title, str):
|
||
raise BadRequestError("title must be a string")
|
||
if len(title) < 1 or len(title) > 100:
|
||
raise BadRequestError("title length must be between 1 and 100 characters")
|
||
if not title.strip():
|
||
raise BadRequestError("title cannot consist only of whitespace")
|
||
|
||
if not isinstance(member_ids, list):
|
||
raise BadRequestError("member_ids must be an array")
|
||
if len(member_ids) < 1 or len(member_ids) > 100:
|
||
raise BadRequestError("member_ids length must be between 1 and 100")
|
||
|
||
seen = set()
|
||
cleaned_members = []
|
||
for mid in member_ids:
|
||
mid_str = validate_uuid(mid, "member_ids element")
|
||
if mid_str in seen:
|
||
raise BadRequestError(f"Duplicate member_id: {mid_str}")
|
||
seen.add(mid_str)
|
||
cleaned_members.append(mid_str)
|
||
|
||
return {'title': title, 'member_ids': cleaned_members}
|
||
|
||
|
||
def validate_create_message(body: Any) -> Dict[str, Any]:
|
||
if not isinstance(body, dict):
|
||
raise BadRequestError("Request body must be a JSON object")
|
||
allowed_fields = {'text'}
|
||
if set(body.keys()) != allowed_fields:
|
||
extra = set(body.keys()) - allowed_fields
|
||
missing = allowed_fields - set(body.keys())
|
||
if missing:
|
||
raise BadRequestError(f"Missing required fields: {', '.join(missing)}")
|
||
if extra:
|
||
raise BadRequestError(f"Unexpected fields: {', '.join(extra)}")
|
||
|
||
text = body.get('text')
|
||
if not isinstance(text, str):
|
||
raise BadRequestError("text must be a string")
|
||
if len(text) < 1 or len(text) > 4000:
|
||
raise BadRequestError("text length must be between 1 and 4000 characters")
|
||
if not text.strip():
|
||
raise BadRequestError("text cannot consist only of whitespace")
|
||
|
||
return {'text': text}
|
||
|
||
|
||
def parse_limit(limit_param: Optional[str]) -> int:
|
||
if limit_param is None:
|
||
return 50
|
||
try:
|
||
limit = int(limit_param)
|
||
except (ValueError, TypeError):
|
||
raise BadRequestError("limit must be an integer")
|
||
if limit < 1 or limit > 100:
|
||
raise BadRequestError("limit must be between 1 and 100")
|
||
return limit
|
||
|
||
|
||
def encode_cursor(created_at: str, item_id: str, resource_type: str, chat_id: Optional[str] = None) -> str:
|
||
data = {
|
||
't': created_at,
|
||
'id': item_id,
|
||
'type': resource_type,
|
||
}
|
||
if chat_id is not None:
|
||
data['cid'] = chat_id
|
||
raw = json.dumps(data, separators=(',', ':')).encode('utf-8')
|
||
return base64.urlsafe_b64encode(raw).decode('ascii')
|
||
|
||
|
||
def decode_cursor(cursor_str: str, expected_type: str, expected_chat_id: Optional[str] = None) -> Tuple[dt.datetime, int]:
|
||
try:
|
||
if len(cursor_str) > 2048:
|
||
raise ValueError
|
||
raw = base64.b64decode(cursor_str.encode('ascii'), altchars=b'-_', validate=True)
|
||
data = json.loads(raw.decode('utf-8'))
|
||
if not isinstance(data, dict):
|
||
raise ValueError
|
||
if data.get('type') != expected_type:
|
||
raise BadRequestError("Cursor does not match resource type")
|
||
if expected_chat_id is not None and data.get('cid') != expected_chat_id:
|
||
raise BadRequestError("Cursor belongs to another chat")
|
||
t = parse_rfc3339(data['t'])
|
||
if t.utcoffset() != dt.timedelta(0):
|
||
raise ValueError
|
||
u_int = uuid.UUID(data['id']).int
|
||
return t, u_int
|
||
except APIError:
|
||
raise
|
||
except Exception:
|
||
raise BadRequestError("Invalid cursor format")
|