support change password

This commit is contained in:
xtaodada 2023-04-14 22:30:18 +08:00
parent 51c9e6a6bc
commit dffb1e8d06
Signed by: xtaodada
GPG Key ID: 4CBB3F4FA8C85659
2 changed files with 38 additions and 0 deletions

34
apis/change_password.py Normal file
View File

@ -0,0 +1,34 @@
from errors.user import UserPasswordIncorrectError, UserNotFoundError
from pydantic import BaseModel
from defs import app
from models.services.user import UserAction
class ChangeUser(BaseModel):
username: str
old_password: str
new_password: str
async def change_user_password(change_user: ChangeUser):
user = await UserAction.get_user_by_username(change_user.username)
if user is None:
raise UserNotFoundError
if user.password != change_user.old_password:
raise UserPasswordIncorrectError
user.password = change_user.new_password
await UserAction.update_user(user)
@app.post("/change_password")
async def change_password(change_user: ChangeUser):
if change_user.old_password == change_user.new_password:
return {"code": 403, "msg": "新密码不能与旧密码相同"}
try:
await change_user_password(change_user)
except UserNotFoundError:
return {"code": 403, "msg": "用户不存在"}
except UserPasswordIncorrectError:
return {"code": 403, "msg": "用户名或密码错误"}
return {"code": 200, "msg": "密码修改成功"}

View File

@ -1,10 +1,14 @@
import asyncio
from fastapi import FastAPI
from starlette.middleware.trustedhost import TrustedHostMiddleware
from models.sqlite import Sqlite
loop = asyncio.get_event_loop()
app = FastAPI()
app.add_middleware(
TrustedHostMiddleware, allowed_hosts=["127.0.0.1"]
)
sqlite = Sqlite()
need_auth_routes = []