username validation

This commit is contained in:
IluaAir
2025-09-20 14:11:14 +03:00
parent c642b89581
commit 9099120ee2
2 changed files with 14 additions and 4 deletions

View File

@@ -3,7 +3,7 @@ from typing import Annotated
from pydantic import BaseModel, BeforeValidator, ConfigDict, EmailStr from pydantic import BaseModel, BeforeValidator, ConfigDict, EmailStr
from src.schemas.tasks import TaskWithId from src.schemas.tasks import TaskWithId
from src.schemas.validators import ensure_password from src.schemas.validators import ensure_password, ensure_username
class UserUpdate(BaseModel): class UserUpdate(BaseModel):
@@ -38,7 +38,7 @@ class UserRequest(BaseModel):
class UserRequestADD(BaseModel): class UserRequestADD(BaseModel):
username: str username: Annotated[str, BeforeValidator(ensure_username)]
email: EmailStr | None = None email: EmailStr | None = None
password: Annotated[str, BeforeValidator(ensure_password)] password: Annotated[str, BeforeValidator(ensure_password)]

View File

@@ -1,11 +1,21 @@
from typing import Any from typing import Any
def ensure_password(value: Any) -> Any: def ensure_password(value: Any) -> str:
if not isinstance(value, str): if not isinstance(value, str):
raise TypeError("Password must be a string") raise TypeError("Password must be a string")
value = value.strip()
if len(value) < 8: if len(value) < 8:
raise ValueError("Password must be at least 8 characters") raise ValueError("Password must be at least 8 characters")
if value.strip() == "": elif value.strip() == "":
raise ValueError("Password cannot be empty") raise ValueError("Password cannot be empty")
return value return value
def ensure_username(value: str) -> str:
value = value.strip()
if len(value) < 3:
raise ValueError("Username must be at least 3 characters")
elif value.lower() in ['admin', 'moderator', 'админ', 'модератор']:
raise ValueError("Login is already taken")
return value