改密码=旧密钥解密→新密钥重加密(含明文迁移数据);角色人设/开场白纳入加密范围;后台渠道分配UI+改密码入口
This commit is contained in:
@@ -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}
|
||||
|
||||
|
||||
@@ -50,16 +50,28 @@ async def _own_character(db, user, cid) -> Character:
|
||||
@router.get("")
|
||||
async def list_characters(user: User = Depends(current_user), db=Depends(get_db)):
|
||||
rows = await repos.CharacterRepo.list_for(db, user.id)
|
||||
return {"characters": [{"id": c.id, "name": c.name, "persona": c.persona,
|
||||
"greeting": c.greeting, "voice": c.voice,
|
||||
key = _key(user)
|
||||
return {"characters": [{"id": c.id, "name": c.name, "persona": repos.dec(key, c.persona),
|
||||
"greeting": repos.dec(key, c.greeting), "voice": c.voice,
|
||||
"avatar_url": c.avatar_url, "source": c.source,
|
||||
"novel_id": c.novel_id} for c in rows]}
|
||||
|
||||
|
||||
async def _enc_persona(user, c):
|
||||
"""人设/开场白按当前开关决定是否加密落库"""
|
||||
db = c._sa_instance_state.session
|
||||
key = _key(user)
|
||||
visible = await repos.SettingRepo.get(db, "admin_data_visible") == "true"
|
||||
ek = None if visible else key
|
||||
c.persona = repos.enc(ek, c.persona)
|
||||
c.greeting = repos.enc(ek, c.greeting)
|
||||
|
||||
|
||||
@router.post("")
|
||||
async def create_character(body: CharacterIn, user: User = Depends(current_user),
|
||||
db=Depends(get_db)):
|
||||
c = Character(user_id=user.id, **body.model_dump())
|
||||
await _enc_persona(user, c)
|
||||
db.add(c)
|
||||
await db.commit()
|
||||
return {"id": c.id}
|
||||
@@ -71,6 +83,7 @@ async def update_character(cid: int, body: CharacterIn,
|
||||
c = await _own_character(db, user, cid)
|
||||
for k, v in body.model_dump().items():
|
||||
setattr(c, k, v)
|
||||
await _enc_persona(user, c)
|
||||
await db.commit()
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@@ -11,6 +11,7 @@ from ...db import repos
|
||||
from ...models.entities import (User, ChatSession, Message, Character,
|
||||
Memory, WorldbookEntry)
|
||||
from ...api.routers.auth import current_user
|
||||
from ...api.routers.characters import _enc_persona, _key # noqa
|
||||
from ...core import security
|
||||
from ...services.llm import LLMClient
|
||||
from ...services import novel_pipeline
|
||||
@@ -74,7 +75,7 @@ async def build_context(db, user, session, history) -> list[dict]:
|
||||
msgs = []
|
||||
if session.mode == "roleplay":
|
||||
ch = await db.get(Character, session.character_id)
|
||||
persona = f"你扮演角色「{ch.name}」。人设:\n{ch.persona}\n始终以该角色的口吻回复,不要出戏。"
|
||||
persona = f"你扮演角色「{ch.name}」。人设:\n{_dec(user, ch.persona)}\n始终以该角色的口吻回复,不要出戏。"
|
||||
mems = await repos.MemoryRepo.list_for(db, user.id, ch.id)
|
||||
key = _key(user)
|
||||
mem_text = "\n".join(f"- [{m.kind}] {_dec(user, m.content_enc)}" for m in mems)
|
||||
@@ -125,7 +126,7 @@ async def create_session(body: SessionIn, user: User = Depends(current_user),
|
||||
ch = await db.get(Character, body.character_id)
|
||||
if ch and ch.greeting:
|
||||
db.add(Message(session_id=s.id, user_id=user.id, role="assistant",
|
||||
speaker=ch.name, content_enc=_enc(user, ch.greeting)))
|
||||
speaker=ch.name, content_enc=_enc(user, _dec(user, ch.greeting))))
|
||||
await db.commit()
|
||||
return {"id": s.id}
|
||||
|
||||
@@ -190,6 +191,7 @@ async def _run_extraction(db, user, session, client, models, auto_avatar, story_
|
||||
data["avatar_url"] = await novel_pipeline.gen_avatar(
|
||||
client, image_model, d.get("appearance", ""))
|
||||
ch = Character(**data)
|
||||
await _enc_persona(user, ch)
|
||||
db.add(ch)
|
||||
await db.flush()
|
||||
# 自动记忆
|
||||
@@ -205,7 +207,7 @@ async def _run_extraction(db, user, session, client, models, auto_avatar, story_
|
||||
content_enc=repos.enc(None if visible else key,
|
||||
f"{d['name']}:{d.get('identity','')}。"
|
||||
f"{d.get('personality','')} 与主角关系:{d.get('relation','')}")))
|
||||
out.append({"id": ch.id, "name": ch.name, "persona": ch.persona,
|
||||
out.append({"id": ch.id, "name": ch.name, "persona": _dec(user, ch.persona),
|
||||
"avatar_url": ch.avatar_url, "voice": ch.voice})
|
||||
await db.commit()
|
||||
return out
|
||||
|
||||
@@ -32,6 +32,7 @@
|
||||
<button data-page="admin" class="nav-btn admin-only">⚙️ 后台</button>
|
||||
<span class="spacer"></span>
|
||||
<span id="whoami" class="who"></span>
|
||||
<button class="nav-btn" onclick="editPassword()">🔑</button>
|
||||
<button class="nav-btn" onclick="logout()">退出</button>
|
||||
</nav>
|
||||
|
||||
|
||||
+49
-1
@@ -350,7 +350,7 @@ async function loadAdmin() {
|
||||
<button class="btn small ${s[k] === "true" ? "primary" : ""}" onclick="toggleSetting('${k}',this)">${s[k] === "true" ? "开" : "关"}</button></div>`).join("");
|
||||
const u = await api("/admin/users");
|
||||
$("#admin-stats").textContent = `用户 ${u.stats.users} · 会话 ${u.stats.sessions}`;
|
||||
$("#admin-users").innerHTML = u.users.map(x =>
|
||||
$("#admin-users").innerHTML = `<button class="btn small primary" onclick="adminGrantChannel()">🔌 渠道分配</button>` + u.users.map(x =>
|
||||
`<div class="mem-item"><b>${esc(x.username)}</b> ${x.is_admin ? '<span class="tag">管理员</span>' : ""}
|
||||
${x.is_active ? "" : '<span class="tag">已封禁</span>'}
|
||||
<div class="row">
|
||||
@@ -399,6 +399,54 @@ async function guideNext() {
|
||||
loadChannels();
|
||||
}
|
||||
|
||||
/* ---------- 改密码(自动重加密) ---------- */
|
||||
function editPassword() {
|
||||
openModal(`<h3>修改密码</h3>
|
||||
<p class="hint">加密数据将自动用旧密码解密、新密码重加密,历史记录无损。</p>
|
||||
<input id="pw-old" type="password" placeholder="旧密码">
|
||||
<input id="pw-new" type="password" placeholder="新密码(至少6位)">
|
||||
<div class="row" style="margin-top:12px">
|
||||
<button class="btn primary" onclick="savePassword()">确认修改</button>
|
||||
<button class="btn" onclick="closeModal()">取消</button></div>`);
|
||||
}
|
||||
async function savePassword() {
|
||||
try {
|
||||
await api("/auth/change_password", { method: "POST", body: {
|
||||
old_password: $("#pw-old").value, new_password: $("#pw-new").value } });
|
||||
closeModal(); toast("密码已修改,加密数据已重加密");
|
||||
} catch (e) { toast(e.message); }
|
||||
}
|
||||
|
||||
/* ---------- 后台:渠道分配 ---------- */
|
||||
async function adminGrantChannel() {
|
||||
const chans = (await api("/channels")).channels; // 管理员可见全部
|
||||
const users = (await api("/admin/users")).users;
|
||||
openModal(`<h3>渠道分配</h3>
|
||||
<select id="gr-chan">${chans.map(c => `<option value="${c.id}">${esc(c.name)} (#${c.id})</option>`).join("")}</select>
|
||||
<select id="gr-user">${users.filter(u => !u.is_admin).map(u => `<option value="${u.id}">${esc(u.username)}</option>`).join("")}</select>
|
||||
<div class="row" style="margin-top:12px">
|
||||
<button class="btn primary" onclick="doGrant()">授权</button>
|
||||
<button class="btn" onclick="closeModal()">关闭</button></div>
|
||||
<div id="gr-list" style="margin-top:12px"></div>`);
|
||||
const c = +$("#gr-chan").value;
|
||||
const g = await api(`/channels/${c}/grants`);
|
||||
$("#gr-list").innerHTML = g.user_ids.length
|
||||
? "已授权用户: " + g.user_ids.map(uid => {
|
||||
const u = users.find(x => x.id === uid);
|
||||
return `<span class="tag">${esc(u ? u.username : uid)}
|
||||
<button class="btn small danger" onclick="revokeGrant(${c},${uid})">✕</button></span>`;
|
||||
}).join(" ")
|
||||
: '<p class="hint">该渠道尚未授权给任何用户。</p>';
|
||||
}
|
||||
async function doGrant() {
|
||||
await api(`/admin/channels/${$("#gr-chan").value}/grant/${$("#gr-user").value}`, { method: "POST" });
|
||||
adminGrantChannel(); toast("已授权");
|
||||
}
|
||||
async function revokeGrant(cid, uid) {
|
||||
await api(`/admin/channels/${cid}/grant/${uid}`, { method: "DELETE" });
|
||||
adminGrantChannel();
|
||||
}
|
||||
|
||||
/* ---------- 通用 ---------- */
|
||||
function openModal(html) { $("#modal").innerHTML = html; $("#modal").classList.remove("hidden");
|
||||
$("#modal-mask").classList.remove("hidden"); }
|
||||
|
||||
Reference in New Issue
Block a user