Files

78 lines
2.6 KiB
Python

"""HTTP request models; all strings use Unicode code point limits."""
import re
import uuid
from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
USERNAME_RE = re.compile(r"^[a-z0-9_]{3,32}$")
class StrictModel(BaseModel):
model_config = ConfigDict(extra="forbid", strict=True)
class CreateUser(StrictModel):
username: str
display_name: str = Field(min_length=1, max_length=100)
password: str = Field(min_length=12, max_length=128)
@field_validator("username")
@classmethod
def username_valid(cls, value: str) -> str:
if not USERNAME_RE.fullmatch(value):
raise ValueError("Invalid username")
return value
@field_validator("display_name", "password")
@classmethod
def non_blank(cls, value: str) -> str:
if not value.strip():
raise ValueError("Blank value")
value.encode("utf-8", errors="strict")
return value
class CreateChat(StrictModel):
title: str = Field(min_length=1, max_length=100)
member_ids: list[str] = Field(min_length=1, max_length=100)
@field_validator("title")
@classmethod
def non_blank(cls, value: str) -> str:
if not value.strip():
raise ValueError("Blank title")
value.encode("utf-8", errors="strict")
return value
@field_validator("member_ids")
@classmethod
def uuid_members(cls, value: list[str]) -> list[str]:
for member in value:
if not isinstance(member, str) or str(uuid.UUID(member)) != member:
raise ValueError("Invalid member UUID")
if len(value) != len(set(value)):
raise ValueError("Duplicate member")
return value
class CreateMessage(StrictModel):
text: str = Field(min_length=0, max_length=4000)
attachment_ids: list[str] = Field(default_factory=list, max_length=10)
@field_validator("text")
@classmethod
def non_blank(cls, value: str) -> str:
value.encode("utf-8", errors="strict")
return value
@field_validator("attachment_ids")
@classmethod
def valid_attachments(cls, value: list[str]) -> list[str]:
if len(value) != len(set(value)):
raise ValueError("Duplicate attachment IDs")
for item in value:
if not isinstance(item, str) or str(uuid.UUID(item)) != item:
raise ValueError("Invalid attachment UUID")
return value
@model_validator(mode="after")
def nonempty_message(self):
if not self.text.strip() and not self.attachment_ids:
raise ValueError("Empty message")
return self