73 lines
2.0 KiB
Python
73 lines
2.0 KiB
Python
from __future__ import annotations
|
|
|
|
import re
|
|
from typing import List
|
|
from uuid import UUID
|
|
|
|
from pydantic import BaseModel, ConfigDict, Field, field_validator
|
|
|
|
USERNAME_RE = re.compile(r"^[a-z0-9_]{3,32}$")
|
|
|
|
|
|
def _not_blank(value: str, field_name: str) -> str:
|
|
if value.strip() == "":
|
|
raise ValueError(f"{field_name} must not be blank")
|
|
return value
|
|
|
|
|
|
class CreateUser(BaseModel):
|
|
model_config = ConfigDict(extra="forbid")
|
|
|
|
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 validate_username(cls, value: str) -> str:
|
|
if not USERNAME_RE.fullmatch(value):
|
|
raise ValueError("username must match [a-z0-9_]{3,32}")
|
|
return value
|
|
|
|
@field_validator("display_name")
|
|
@classmethod
|
|
def validate_display_name(cls, value: str) -> str:
|
|
return _not_blank(value, "display_name")
|
|
|
|
@field_validator("password")
|
|
@classmethod
|
|
def validate_password(cls, value: str) -> str:
|
|
if len(value) < 12 or len(value) > 128:
|
|
raise ValueError("password length must be 12-128")
|
|
return value
|
|
|
|
|
|
class CreateChat(BaseModel):
|
|
model_config = ConfigDict(extra="forbid")
|
|
|
|
title: str = Field(min_length=1, max_length=100)
|
|
member_ids: List[UUID] = Field(min_length=1, max_length=100)
|
|
|
|
@field_validator("title")
|
|
@classmethod
|
|
def validate_title(cls, value: str) -> str:
|
|
return _not_blank(value, "title")
|
|
|
|
@field_validator("member_ids")
|
|
@classmethod
|
|
def validate_members(cls, value: List[UUID]) -> List[UUID]:
|
|
if len(value) != len(set(value)):
|
|
raise ValueError("member_ids must be unique")
|
|
return value
|
|
|
|
|
|
class CreateMessage(BaseModel):
|
|
model_config = ConfigDict(extra="forbid")
|
|
|
|
text: str = Field(min_length=1, max_length=4000)
|
|
|
|
@field_validator("text")
|
|
@classmethod
|
|
def validate_text(cls, value: str) -> str:
|
|
return _not_blank(value, "text")
|