改密码=旧密钥解密→新密钥重加密(含明文迁移数据);角色人设/开场白纳入加密范围;后台渠道分配UI+改密码入口

This commit is contained in:
zhiqui
2026-11-14 23:35:13 +08:00
parent f8faed9ea7
commit ec4d5102d2
5 changed files with 116 additions and 6 deletions
+46
View File
@@ -109,3 +109,49 @@ async def delete_account(body: AuthIn, user: User = Depends(current_user), db=De
@router.get("/me")
async def me(user: User = Depends(current_user)):
return {"id": user.id, "username": user.username, "is_admin": user.is_admin}
class ChangePasswordIn(BaseModel):
old_password: str
new_password: str
@router.post("/change_password")
async def change_password(body: ChangePasswordIn, user: User = Depends(current_user),
db=Depends(get_db)):
"""旧密码解密 → 新密码重加密 → 换盐换 hash。"""
if not security.verify_password(body.old_password, user.password_hash):
raise HTTPException(401, "旧密码错误")
if len(body.new_password) < 6:
raise HTTPException(400, "新密码至少6位")
old_key = security.derive_key(body.old_password, bytes.fromhex(user.kdf_salt))
new_salt = security.os.urandom(16)
new_key = security.derive_key(body.new_password, new_salt)
# 当前是否要求加密落库
from ...db import repos as _repos
need_encrypt = await _repos.SettingRepo.get(db, "admin_data_visible") != "true"
from ...models.entities import (Memory, WorldbookEntry, Character,
ChatSession, Message)
tables = [(Memory, "content_enc"), (WorldbookEntry, "content_enc"),
(Message, "content_enc"), (ChatSession, "novel_setting_enc"),
(Character, "persona"), (Character, "greeting")]
for model, col in tables:
rows = (await db.execute(
select(model).where(model.user_id == user.id))).scalars().all()
for row in rows:
v = getattr(row, col)
if not v:
continue
plain = (security.decrypt_text(old_key, v)
if security.is_encrypted(v) else v)
setattr(row, col, security.encrypt_text(new_key, plain)
if need_encrypt else plain)
user.kdf_salt = new_salt.hex()
user.password_hash = security.hash_password(body.new_password)
await db.commit()
security.key_cache[user.id] = new_key
return {"ok": True}