forked from mtusi2026/mtusi2026lab5
52 lines
1.6 KiB
Python
52 lines
1.6 KiB
Python
from fastapi import APIRouter, Depends
|
|
from pydantic import BaseModel, ConfigDict, Field, field_validator
|
|
import psycopg
|
|
|
|
from ..db import transaction
|
|
from ..errors import ApiError
|
|
from ..security import hash_password
|
|
from ..serializers import row_to_user
|
|
from .sessions import require_actor
|
|
|
|
router = APIRouter(prefix="/api/v1")
|
|
|
|
|
|
class CreateUser(BaseModel):
|
|
model_config = ConfigDict(extra="forbid")
|
|
|
|
username: str = Field(pattern=r"^[a-z0-9_]{3,32}$")
|
|
display_name: str = Field(min_length=1, max_length=100)
|
|
password: str = Field(min_length=12, max_length=128)
|
|
|
|
@field_validator("display_name")
|
|
@classmethod
|
|
def not_blank(cls, v: str) -> str:
|
|
if not v.strip():
|
|
raise ValueError("display_name must not be blank")
|
|
return v
|
|
|
|
|
|
@router.post("/users", status_code=201)
|
|
def create_user(body: CreateUser):
|
|
pwd_hash = hash_password(body.password)
|
|
try:
|
|
with transaction() as conn:
|
|
with conn.cursor(row_factory=psycopg.rows.dict_row) as cur:
|
|
cur.execute(
|
|
"""
|
|
INSERT INTO users (username, display_name, password_hash)
|
|
VALUES (%s, %s, %s)
|
|
RETURNING id, username, display_name, created_at
|
|
""",
|
|
(body.username, body.display_name, pwd_hash),
|
|
)
|
|
row = cur.fetchone()
|
|
except psycopg.errors.UniqueViolation:
|
|
raise ApiError(409, "conflict", "Имя пользователя занято")
|
|
|
|
return row_to_user(row)
|
|
|
|
|
|
@router.get("/users/me")
|
|
def current_user(actor: dict = Depends(require_actor)):
|
|
return actor["user"] |