54 lines
1.7 KiB
Python
54 lines
1.7 KiB
Python
# scheme/users.py
|
|
# 用户认证模块的请求/响应模型
|
|
from typing import Optional
|
|
|
|
from pydantic import BaseModel, Field, field_validator
|
|
|
|
|
|
# -------------------- 请求体模型 -----------------------------
|
|
class UserAdd(BaseModel):
|
|
"""创建用户(仅管理员)"""
|
|
username: str = Field(..., min_length=3, max_length=50, description="登录名")
|
|
password: str = Field(..., min_length=6, max_length=64, description="密码(明文,服务端加密存储)")
|
|
role: str = Field(..., description="角色:admin/teacher/student")
|
|
teacher_id: Optional[int] = Field(None, ge=1, description="教师角色的工号")
|
|
stu_id: Optional[int] = Field(None, ge=1, description="学生角色的学号")
|
|
|
|
@field_validator("role")
|
|
@classmethod
|
|
def validate_role(cls, v):
|
|
allowed = ["admin", "teacher", "student"]
|
|
if v not in allowed:
|
|
raise ValueError(f"role 必须是 {allowed} 之一,当前值: {v}")
|
|
return v
|
|
|
|
|
|
class UserLogin(BaseModel):
|
|
"""登录"""
|
|
username: str = Field(..., description="登录名")
|
|
password: str = Field(..., description="密码")
|
|
|
|
|
|
# -------------------- 响应模型 ----------------------------
|
|
class UserResponse(BaseModel):
|
|
user_id: int
|
|
username: str
|
|
role: str
|
|
teacher_id: Optional[int] = None
|
|
stu_id: Optional[int] = None
|
|
|
|
class Config:
|
|
from_attributes = True
|
|
|
|
|
|
class TokenResponse(BaseModel):
|
|
"""登录成功返回"""
|
|
access_token: str = Field(..., description="JWT token")
|
|
token_type: str = Field("bearer", description="token 类型")
|
|
user: UserResponse
|
|
|
|
|
|
class MessageResponse(BaseModel):
|
|
"""通用消息响应"""
|
|
message: str
|