import re import uuid from pydantic import BaseModel, ConfigDict, field_validator USERNAME_RE = re.compile(r"^[a-z0-9_]{3,32}$") class StrictModel(BaseModel): model_config = ConfigDict(extra="forbid") def _visible(value, limit): if not isinstance(value, str) or not value.strip() or len(value) > limit: raise ValueError("text") return value class CreateUser(StrictModel): username: str display_name: str password: str @field_validator("username") @classmethod def username_ok(cls, value): if not isinstance(value, str) or not USERNAME_RE.fullmatch(value): raise ValueError("username") return value @field_validator("display_name") @classmethod def display_name_ok(cls, value): return _visible(value, 100) @field_validator("password") @classmethod def password_ok(cls, value): if not isinstance(value, str) or not value.strip(): raise ValueError("password") # Длина в code points, не в байтах: bcrypt тут не подходит из-за усечения UTF-8. if len(value) < 12 or len(value) > 128: raise ValueError("password") return value class CreateChat(StrictModel): title: str member_ids: list @field_validator("title") @classmethod def title_ok(cls, value): return _visible(value, 100) @field_validator("member_ids") @classmethod def member_ids_ok(cls, value): if not isinstance(value, list) or not (1 <= len(value) <= 100): raise ValueError("member_ids") # Сравниваем и возвращаем канонический UUID (нижний регистр + дефисы), # иначе u и u.upper() проходят как «разные» строки и падают UniqueViolation в БД. normalized = [] seen = set() for item in value: if not isinstance(item, str): raise ValueError("member_ids") try: canonical = str(uuid.UUID(item)) except ValueError as exc: raise ValueError("member_ids") from exc if canonical in seen: raise ValueError("member_ids") seen.add(canonical) normalized.append(canonical) return normalized class CreateMessage(StrictModel): text: str @field_validator("text") @classmethod def text_ok(cls, value): return _visible(value, 4000)