Add account settings and memory coach
This commit is contained in:
@@ -6,7 +6,7 @@ from sqlalchemy.orm import Session
|
||||
from auth import create_access_token, get_current_user, hash_password, verify_password
|
||||
from database import get_db
|
||||
from models import User, UserSettings
|
||||
from schemas import TokenResponse, UserLogin, UserOut, UserRegister
|
||||
from schemas import TokenResponse, UserLogin, UserOut, UserRegister, UserUpdate
|
||||
|
||||
router = APIRouter(prefix="/api/auth", tags=["auth"])
|
||||
|
||||
@@ -53,3 +53,38 @@ def login(data: UserLogin, db: Session = Depends(get_db)):
|
||||
@router.get("/me", response_model=UserOut)
|
||||
def me(current_user: User = Depends(get_current_user)):
|
||||
return current_user
|
||||
|
||||
|
||||
@router.patch("/me", response_model=UserOut)
|
||||
def update_me(
|
||||
data: UserUpdate,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user),
|
||||
):
|
||||
if data.username is None and data.new_password is None:
|
||||
raise HTTPException(status_code=400, detail="请填写要修改的内容")
|
||||
|
||||
if data.username is not None:
|
||||
username = data.username.strip()
|
||||
if not username:
|
||||
raise HTTPException(status_code=400, detail="用户名不能为空")
|
||||
exists = (
|
||||
db.query(User)
|
||||
.filter(User.username == username, User.id != current_user.id)
|
||||
.first()
|
||||
)
|
||||
if exists:
|
||||
raise HTTPException(status_code=400, detail="用户名已存在")
|
||||
current_user.username = username
|
||||
|
||||
if data.new_password is not None:
|
||||
if not data.current_password:
|
||||
raise HTTPException(status_code=400, detail="修改密码需要先输入当前密码")
|
||||
if not verify_password(data.current_password, current_user.password_hash):
|
||||
raise HTTPException(status_code=400, detail="当前密码不正确")
|
||||
current_user.password_hash = hash_password(data.new_password)
|
||||
|
||||
db.add(current_user)
|
||||
db.commit()
|
||||
db.refresh(current_user)
|
||||
return current_user
|
||||
|
||||
@@ -28,6 +28,12 @@ class UserOut(BaseModel):
|
||||
from_attributes = True
|
||||
|
||||
|
||||
class UserUpdate(BaseModel):
|
||||
username: Optional[str] = Field(None, min_length=2, max_length=50)
|
||||
current_password: Optional[str] = Field(None, min_length=6, max_length=100)
|
||||
new_password: Optional[str] = Field(None, min_length=6, max_length=100)
|
||||
|
||||
|
||||
# Translate
|
||||
class TranslateRequest(BaseModel):
|
||||
text: str = Field(min_length=1)
|
||||
|
||||
Reference in New Issue
Block a user