modify: auth 插件
This commit is contained in:
@@ -0,0 +1,81 @@
|
||||
import time
|
||||
from datetime import datetime
|
||||
|
||||
from sqlalchemy import select
|
||||
|
||||
from chongming_worker import rpc_method
|
||||
from chongming_password import hash_password, verify_password
|
||||
|
||||
from ..models.pydantic import (
|
||||
ChangePasswordPostRequest,
|
||||
ChangePasswordPostResponse
|
||||
)
|
||||
from ..models.auth import Users
|
||||
|
||||
|
||||
@rpc_method(
|
||||
subject="auth.change_password",
|
||||
method="POST",
|
||||
summary="修改密码",
|
||||
response_model=ChangePasswordPostResponse,
|
||||
)
|
||||
async def change_password(change_password_post_request: ChangePasswordPostRequest) -> ChangePasswordPostResponse:
|
||||
from ..global_var import db
|
||||
|
||||
if db is None:
|
||||
raise RuntimeError("Database not initialized")
|
||||
|
||||
user_id = change_password_post_request.user_id
|
||||
old_password = change_password_post_request.old_password
|
||||
new_password = change_password_post_request.new_password
|
||||
|
||||
if not old_password:
|
||||
return ChangePasswordPostResponse(
|
||||
result="fail",
|
||||
message="旧密码不能为空",
|
||||
timestamp=time.time()
|
||||
)
|
||||
if not new_password:
|
||||
return ChangePasswordPostResponse(
|
||||
result="fail",
|
||||
message="新密码不能为空",
|
||||
timestamp=time.time()
|
||||
)
|
||||
if old_password == new_password:
|
||||
return ChangePasswordPostResponse(
|
||||
result="fail",
|
||||
message="新密码不能与旧密码相同",
|
||||
timestamp=time.time()
|
||||
)
|
||||
|
||||
async with db.get_session() as session:
|
||||
stmt = select(Users).filter_by(id=user_id)
|
||||
result = await session.execute(stmt)
|
||||
user: Users | None = result.scalar_one_or_none()
|
||||
|
||||
if user is None:
|
||||
return ChangePasswordPostResponse(
|
||||
result="fail",
|
||||
message="用户不存在",
|
||||
timestamp=time.time()
|
||||
)
|
||||
|
||||
# 验证旧密码
|
||||
if not verify_password(old_password, user.hashed_password):
|
||||
return ChangePasswordPostResponse(
|
||||
result="fail",
|
||||
message="旧密码错误",
|
||||
timestamp=time.time()
|
||||
)
|
||||
|
||||
# 更新密码
|
||||
user.hashed_password = hash_password(new_password)
|
||||
user.updated_at = datetime.now()
|
||||
session.add(user)
|
||||
await session.commit()
|
||||
|
||||
return ChangePasswordPostResponse(
|
||||
result="success",
|
||||
message="密码修改成功",
|
||||
timestamp=time.time()
|
||||
)
|
||||
Reference in New Issue
Block a user