重构h5页面加入管理员相关权限控制
This commit is contained in:
@@ -76,6 +76,8 @@ auth: # users 留空 = 不启用登
|
||||
users:
|
||||
- user: admin # 默认账号
|
||||
password: "admin" # 默认密码,请务必修改
|
||||
role: admin # admin=管理员(全部设置 + 用户管理);user 或缺省=普通用户(仅账户页)
|
||||
# model: qwen-tp/qwen3.8-flash # 选填:该用户新建会话时锁定的模型(内部键「平台名/模型id」)
|
||||
|
||||
# 外部 MCP 服务列表:每项 {name?, url, headers?, enable?(默认 true), timeout_ms?, tools_allow?, tools_deny?}。
|
||||
mcp_servers: []
|
||||
|
||||
+37
-6
@@ -94,13 +94,21 @@ function isSignedDownload(req) {
|
||||
return req.method === 'GET' && /\/files\/(download(-name\/.+)?|zip(-name\/.+)?)$/.test(req.path) && !!req.query.t;
|
||||
}
|
||||
|
||||
// cfg.auth = { users: [{user, password}], secret?, ttl_ms? }
|
||||
// cfg.auth = { users: [{user, password, role?, model?}], secret?, ttl_ms? }
|
||||
// users 为空则整个认证关闭(cfg.auth 为 null)。
|
||||
function createAuth(cfg) {
|
||||
const router = express.Router();
|
||||
const users = (cfg.auth && cfg.auth.users) || [];
|
||||
let users = (cfg.auth && cfg.auth.users) || [];
|
||||
if (!users.length) {
|
||||
return { enabled: false, middleware: (req, res, next) => next(), router };
|
||||
// 未启用认证 = 单用户自用:管理接口按「本机主人」放行,用户 CRUD 由 routes/users.js 自己拒绝。
|
||||
return {
|
||||
enabled: false,
|
||||
middleware: (req, res, next) => next(),
|
||||
router,
|
||||
requireAdmin: (req, res, next) => next(),
|
||||
refreshUsers: () => {},
|
||||
isAdmin: () => false,
|
||||
};
|
||||
}
|
||||
|
||||
const secret = (cfg.auth.secret && String(cfg.auth.secret)) || crypto.randomBytes(32).toString('hex');
|
||||
@@ -108,7 +116,21 @@ function createAuth(cfg) {
|
||||
log.warn('auth', '未配置 auth.secret,已使用随机密钥:进程重启后所有登录态失效');
|
||||
}
|
||||
const ttlMs = Number(cfg.auth.ttl_ms) || DEFAULT_TTL_MS;
|
||||
const validUsers = new Map(users.map(u => [String(u.user), String(u.password)]));
|
||||
let validUsers = new Map(users.map(u => [String(u.user), String(u.password)]));
|
||||
|
||||
function userRow(name) {
|
||||
const n = String(name == null ? '' : name);
|
||||
return users.find(u => String(u.user) === n) || null;
|
||||
}
|
||||
function isAdmin(name) {
|
||||
const u = userRow(name);
|
||||
return !!u && u.role === 'admin';
|
||||
}
|
||||
// 用户增删改后由 routes/users.js 调用:重建登录校验表(删除的用户旧 token 随即失效)。
|
||||
function refreshUsers(next) {
|
||||
users = Array.isArray(next) ? next : [];
|
||||
validUsers = new Map(users.map(u => [String(u.user), String(u.password)]));
|
||||
}
|
||||
|
||||
function setAuthCookie(res, username) {
|
||||
const token = signToken(username, Date.now() + ttlMs, secret);
|
||||
@@ -205,7 +227,9 @@ function createAuth(cfg) {
|
||||
|
||||
router.get('/api/me', (req, res) => {
|
||||
// 与中间件同一解析顺序(cookie 优先),保证 /api/me 显示的用户与业务路由认定的用户一致
|
||||
res.json({ user: authUser(req) });
|
||||
const name = authUser(req);
|
||||
const row = name ? userRow(name) : null;
|
||||
res.json({ user: name, role: row ? row.role : '', model: row ? (row.model || '') : '' });
|
||||
});
|
||||
|
||||
// ----- 登录页 / 登出跳转 -----
|
||||
@@ -231,7 +255,14 @@ function createAuth(cfg) {
|
||||
return res.redirect('/login?next=' + encodeURIComponent(req.originalUrl));
|
||||
};
|
||||
|
||||
return { enabled: true, middleware, router };
|
||||
// 管理接口门禁(挂在 auth.middleware 之后):仅 admin 可进。
|
||||
function requireAdmin(req, res, next) {
|
||||
if (!req.user) return res.status(401).json({ error: '未登录' });
|
||||
if (!isAdmin(req.user)) return res.status(403).json({ error: '需要管理员权限' });
|
||||
next();
|
||||
}
|
||||
|
||||
return { enabled: true, middleware, router, requireAdmin, refreshUsers, isAdmin };
|
||||
}
|
||||
|
||||
module.exports = { createAuth, COOKIE_NAME };
|
||||
|
||||
+11
-3
@@ -309,14 +309,22 @@ function parseAndValidate(rawText, configPath) {
|
||||
cfg.skills.timeout_ms = (cfg.skills.timeout_ms == null) ? 120000 : cfg.skills.timeout_ms;
|
||||
}
|
||||
|
||||
// auth 规范化:多用户 auth.users: [{user, password}];兼容旧的单用户 auth.{user,password}
|
||||
// auth 规范化:多用户 auth.users: [{user, password, role?, model?}];兼容旧的单用户 auth.{user,password}
|
||||
if (cfg.auth && !Array.isArray(cfg.auth.users)) {
|
||||
cfg.auth.users = cfg.auth.user ? [{ user: cfg.auth.user, password: cfg.auth.password }] : [];
|
||||
cfg.auth.users = cfg.auth.user ? [{ user: cfg.auth.user, password: cfg.auth.password, role: cfg.auth.role, model: cfg.auth.model }] : [];
|
||||
}
|
||||
if (cfg.auth && Array.isArray(cfg.auth.users)) {
|
||||
cfg.auth.users = cfg.auth.users
|
||||
.filter(u => u && u.user)
|
||||
.map(u => ({ user: String(u.user), password: String(u.password == null ? '' : u.password) }));
|
||||
.map(u => ({
|
||||
user: String(u.user),
|
||||
password: String(u.password == null ? '' : u.password),
|
||||
// 角色:admin = 管理员(设置页全部功能 + 用户管理);缺省 user = 普通用户(设置只开账户页)。
|
||||
role: u.role === 'admin' ? 'admin' : 'user',
|
||||
// 选填:该用户新建会话时锁定的模型(内部唯一键「平台名/模型id」,如 qwen-tp/qwen3.8-flash)。
|
||||
// 未配/空串 = 按原逻辑(前端预选或全局自动选择);配了但模型无效/被禁用时同样退回原逻辑。
|
||||
model: u.model ? String(u.model).trim() : '',
|
||||
}));
|
||||
if (!cfg.auth.users.length) cfg.auth = null;
|
||||
}
|
||||
|
||||
|
||||
+14
-1
@@ -286,6 +286,13 @@ function platformModels(platform) {
|
||||
return out;
|
||||
}
|
||||
|
||||
// 用户在 auth.users[].model 里锁定的模型(选填):新建会话时优先于前端预选。
|
||||
// 空串 = 未锁定(未启用认证时 user 为空串,同样不命中)。
|
||||
function lockedModelOf(user) {
|
||||
const u = ((cfg.auth && cfg.auth.users) || []).find(x => String(x.user) === String(user || ''));
|
||||
return (u && u.model) || '';
|
||||
}
|
||||
|
||||
// 在 key 所属平台的模型里选一个:preferred(会话上次用过的同平台模型)优先;
|
||||
// 否则取平台内当前绑定会话数最少的(打平按配置顺序),同平台多模型也轮转摊平。
|
||||
function chooseModel(platform, preferred) {
|
||||
@@ -995,7 +1002,13 @@ function sleep(ms) { return new Promise(r => setTimeout(r, ms)); }
|
||||
// 新建即绑模(无排队):指定了优先模型(welcome 预选)就取其平台「最不 active」的 key;
|
||||
// 模型无效或平台无槽位退回全局优先级选。池完全为空直接报错(配置问题),不建吊儿郎当的会话。
|
||||
function createSession(title, preferModelId, assistantType, user) {
|
||||
const want = String(preferModelId || '');
|
||||
// 用户锁定模型(auth.users[].model)优先于前端预选;锁定值无效/被禁用时退回原逻辑(用前端预选或全局自动选择)。
|
||||
const lock = lockedModelOf(user);
|
||||
const lockValid = !!lock && platformModels(platformOf(lock)).includes(lock);
|
||||
if (lock && !lockValid) {
|
||||
log.warn('model', '用户 ' + (user || '-') + ' 锁定的模型 ' + lock + ' 无效或已禁用,按原逻辑选择');
|
||||
}
|
||||
const want = String((lockValid ? lock : preferModelId) || '');
|
||||
let key = null, modelId = '';
|
||||
if (want && platformModels(platformOf(want)).includes(want)) {
|
||||
key = chooseKey(platformOf(want), true);
|
||||
|
||||
@@ -286,6 +286,28 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 用户编辑弹窗(设置→用户;仅管理员):用户名 / 密码 / 角色 / 默认模型;保存后即时生效无需重启 -->
|
||||
<div id="user-edit-modal" class="modal-overlay hidden" onclick="if(event.target===this)sUI.closeUserModal()">
|
||||
<div class="modal">
|
||||
<button class="modal-close-btn" onclick="sUI.closeUserModal()">
|
||||
<svg viewBox="0 0 24 24"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg>
|
||||
</button>
|
||||
<h3 id="ue-title">添加用户</h3>
|
||||
<input type="text" id="ue-user" placeholder="用户名(字母/数字/下划线)" autocomplete="off">
|
||||
<input type="password" id="ue-pass" placeholder="初始密码(至少 6 位)" autocomplete="new-password">
|
||||
<select id="ue-role">
|
||||
<option value="user">普通用户(仅账户页)</option>
|
||||
<option value="admin">管理员(全部设置)</option>
|
||||
</select>
|
||||
<select id="ue-model"></select>
|
||||
<div class="btn-row mpe-foot">
|
||||
<button class="ghost-btn danger hidden" id="ue-del-btn" onclick="sUI.userDelFromModal()">删除用户</button>
|
||||
<button class="primary-btn" onclick="sUI.saveUser()">保存</button>
|
||||
</div>
|
||||
<div class="cfg-note">默认模型 = 该用户新建会话时自动选择的模型;选「不锁定」则按原逻辑。</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- MCP 服务编辑/新增弹窗:配置 name / url / 多条 headers / 单次调用超时 / 启用开关;保存后写入 config.yml,重启生效 -->
|
||||
<div id="mcp-edit-modal" class="modal-overlay hidden" onclick="if(event.target===this)mcpUI.close()">
|
||||
<div class="modal modal-wide">
|
||||
|
||||
@@ -17,11 +17,12 @@
|
||||
* DELETE /api/sessions/:id/messages/:messageId 删除单条消息/工具卡(删 assistant 连带工具回执;单删工具卡同步摘除父调用)
|
||||
* GET /api/models 状态栏「选择模型」弹窗模型列表
|
||||
*
|
||||
* 设置区(侧边栏用户区整行点击进入;页面搬自 index.html,未新增任何接口):
|
||||
* 设置区(侧边栏用户区整行点击进入;页面搬自 index.html):
|
||||
* GET /api/system/status | POST /api/system/restart[?force=true] 服务·状态与重启
|
||||
* GET/PUT/PATCH /api/config | POST /api/config/validate 系统配置 / 原文编辑 / 模型增删改
|
||||
* GET /api/models | GET /api/platforms/balance 模型·模型池与余额
|
||||
* GET/POST/PUT/DELETE /api/skills[/:name][/file|/upload|/rename] 技能·技能与文件管理
|
||||
* GET/POST/PATCH/DELETE /api/users[/:name] 用户·账号/角色/默认模型(管理员,热生效)
|
||||
* GET /api/me | POST /api/password | GET /logout 账户·信息/改密/退出
|
||||
* GET/PUT /api/profile 账户·用户画像(可见/可改/可关)
|
||||
* GET/POST/DELETE /api/wechat[/:id][/qr|/refresh] 账户·微信绑定(未配 wxbot 时入口自动隐藏)
|
||||
|
||||
@@ -15,8 +15,11 @@
|
||||
const SET = {
|
||||
stack: [],
|
||||
snaps: {}, // 页名 → 静态快照 HTML(setPush 时刷新;右滑返回垫底用)
|
||||
role: 'user', // 当前登录用户角色(admin | user);启动时由 /api/me 回填
|
||||
authEnabled: true, // 是否启用多用户认证(/api/me 404 = 未启用,单用户自用)
|
||||
pendingKeys: new Set(), // 已写盘、尚未重启生效的顶层配置段
|
||||
effCfg: null, cfgOrig: '',
|
||||
users: [], userModels: [], // 用户管理页:账号/角色/默认模型 + 可选模型清单
|
||||
curSkill: null, // 技能详情/编辑视图对应的技能名
|
||||
editorPath: null, editorOrig: '', editorText: '', editorLabel: '',
|
||||
// 模型池(搬自 models.js)
|
||||
@@ -122,7 +125,8 @@
|
||||
u.classList.remove('show'); u.innerHTML = '';
|
||||
}
|
||||
function showSettings() {
|
||||
SET.stack = ['home']; SET.snaps = {}; setUnderHide();
|
||||
// 普通用户没有设置主页:直接进账户页(栈里只有一页,返回即退出设置)
|
||||
SET.stack = [SET.role === 'admin' ? 'home' : 'account']; SET.snaps = {}; setUnderHide();
|
||||
// 桌面端:打开设置时收起侧边栏让设置页占满窗口,关闭时恢复之前的展开态
|
||||
if (drawerMQ.matches) { drawerWasOpenBeforeSet = document.body.classList.contains('drawer-open'); openDrawer(false); }
|
||||
$('settings-page').classList.remove('hidden'); renderSetPage();
|
||||
@@ -250,6 +254,7 @@
|
||||
const ctx = () => tok === setTok && setTop() === p; // 异步回包时页面可能已切走
|
||||
if (p === 'home') return setPageHome(ctx);
|
||||
if (p === 'account') return setPageAccount(ctx);
|
||||
if (p === 'users') return setPageUsers(ctx);
|
||||
if (p === 'service') return setPageService(ctx);
|
||||
if (p === 'cfg-editor') return setPageCfgEditor(ctx);
|
||||
if (p === 'skills') return setPageSkills(ctx);
|
||||
@@ -274,19 +279,23 @@
|
||||
const SET_CARDS = [
|
||||
{ go: 'account', name: '账户', desc: '修改密码 · 用户画像 · 退出登录',
|
||||
icon: '<svg class="ic" viewBox="0 0 24 24"><circle cx="12" cy="8" r="4"></circle><path d="M4 21c0-4 4-6 8-6s8 2 8 6"></path></svg>' },
|
||||
{ go: 'service', name: '服务', desc: '服务状态 · 系统配置',
|
||||
{ go: 'users', name: '用户', desc: '账号 · 角色 · 默认模型', adminOnly: true, needAuth: true,
|
||||
icon: '<svg class="ic" viewBox="0 0 24 24"><circle cx="9" cy="8" r="3.5"></circle><path d="M2 21c0-3.6 3.1-5.5 7-5.5s7 1.9 7 5.5"></path><path d="M16 8.5a3 3 0 0 1 0 6"></path><path d="M18 21c0-2.8-1.4-4.5-4-5.2"></path></svg>' },
|
||||
{ go: 'service', name: '服务', desc: '服务状态 · 系统配置', adminOnly: true,
|
||||
icon: '<svg class="ic" viewBox="0 0 24 24"><line x1="4" y1="21" x2="4" y2="14"></line><line x1="4" y1="10" x2="4" y2="3"></line><line x1="12" y1="21" x2="12" y2="12"></line><line x1="12" y1="8" x2="12" y2="3"></line><line x1="20" y1="21" x2="20" y2="16"></line><line x1="20" y1="12" x2="20" y2="3"></line><line x1="1" y1="14" x2="7" y2="14"></line><line x1="9" y1="8" x2="15" y2="8"></line><line x1="17" y1="16" x2="23" y2="16"></line></svg>' },
|
||||
{ go: 'skills', name: '技能', desc: '技能管理 · 技能文件编辑',
|
||||
{ go: 'skills', name: '技能', desc: '技能管理 · 技能文件编辑', adminOnly: true,
|
||||
icon: '<svg class="ic" viewBox="0 0 24 24"><polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"></polygon></svg>' },
|
||||
{ go: 'models', name: '模型', desc: '模型池状态 · 增删改',
|
||||
{ go: 'models', name: '模型', desc: '模型池状态 · 增删改', adminOnly: true,
|
||||
icon: '<svg class="ic" viewBox="0 0 24 24"><rect x="4" y="4" width="16" height="16" rx="2"></rect><rect x="9" y="9" width="6" height="6"></rect><line x1="9" y1="1" x2="9" y2="4"></line><line x1="15" y1="1" x2="15" y2="4"></line><line x1="9" y1="20" x2="9" y2="23"></line><line x1="15" y1="20" x2="15" y2="23"></line><line x1="20" y1="9" x2="23" y2="9"></line><line x1="20" y1="14" x2="23" y2="14"></line><line x1="1" y1="9" x2="4" y2="9"></line><line x1="1" y1="14" x2="4" y2="14"></line></svg>' },
|
||||
{ go: 'mcp', name: 'MCP', desc: 'MCP 服务 · 增删改',
|
||||
{ go: 'mcp', name: 'MCP', desc: 'MCP 服务 · 增删改', adminOnly: true,
|
||||
icon: '<svg class="ic" viewBox="0 0 24 24"><rect x="3" y="4" width="18" height="16" rx="2"></rect><line x1="3" y1="10" x2="21" y2="10"></line><circle cx="7" cy="15" r="1.2" fill="currentColor" stroke="none"></circle><circle cx="12" cy="15" r="1.2" fill="currentColor" stroke="none"></circle><circle cx="17" cy="15" r="1.2" fill="currentColor" stroke="none"></circle></svg>' },
|
||||
];
|
||||
function setPageHome(ctx) {
|
||||
setTitle('设置');
|
||||
setActions('');
|
||||
setBody('<div class="set-scroll set-home">' + SET_CARDS.map(c =>
|
||||
// 普通用户只保留账户页;用户管理卡另需多用户认证启用
|
||||
const cards = SET_CARDS.filter(c => (!c.adminOnly || SET.role === 'admin') && (!c.needAuth || SET.authEnabled));
|
||||
setBody('<div class="set-scroll set-home">' + cards.map(c =>
|
||||
'<button class="set-card" data-go="' + c.go + '">' +
|
||||
'<span class="set-ico">' + c.icon + '</span>' +
|
||||
'<span class="set-tt"><span class="set-name">' + c.name + '</span>' +
|
||||
@@ -392,6 +401,99 @@
|
||||
catch (e) { toast('保存失败:' + e.message); }
|
||||
}
|
||||
|
||||
// ---------- 页:用户管理(仅管理员;增删改 + 角色 + 默认模型) ----------
|
||||
// 数据面全部走 /api/users:后端写盘后热更新内存,新增/删除/改角色/锁模型都即时生效,无需重启。
|
||||
// 普通用户看不到本页,且后端 /api/users 与 /api/config 都有 requireAdmin 门禁(不只靠藏 UI)。
|
||||
async function setPageUsers(ctx) {
|
||||
setTitle('用户');
|
||||
setActions('<button class="icon-btn" title="添加用户" onclick="sUI.openUserAdd()">' +
|
||||
'<svg class="ic" viewBox="0 0 24 24"><line x1="12" y1="5" x2="12" y2="19"></line><line x1="5" y1="12" x2="19" y2="12"></line></svg></button>');
|
||||
setBody('<div class="set-scroll" id="user-list"><div class="empty-tip">加载中…</div></div>');
|
||||
try {
|
||||
const r = await req('GET', '/api/users');
|
||||
if (!ctx()) return;
|
||||
SET.users = (r && r.users) || [];
|
||||
SET.userModels = (r && r.models) || [];
|
||||
renderUserList();
|
||||
} catch (e) {
|
||||
if (ctx()) setBody('<div class="set-scroll"><div class="empty-tip">加载失败:' + esc(e.message) + '</div></div>');
|
||||
}
|
||||
}
|
||||
function userModelOptions(cur) {
|
||||
return '<option value="">不锁定(按原逻辑)</option>' + SET.userModels.map(m =>
|
||||
'<option value="' + att(m.id) + '"' + (m.id === cur ? ' selected' : '') + '>' + esc(m.name || m.id) + '</option>').join('');
|
||||
}
|
||||
function renderUserList() {
|
||||
const box = $('user-list');
|
||||
if (!box) return;
|
||||
if (!SET.users.length) {
|
||||
box.innerHTML = '<div class="empty-tip">还没有用户,点右上角 + 添加。</div>';
|
||||
return;
|
||||
}
|
||||
// 与服务页同一套白卡 + 虚线 kv 行;整卡点击进弹窗编辑(同 MCP 页的列表交互)
|
||||
box.innerHTML = SET.users.map((u, i) =>
|
||||
'<div class="settings-card" style="cursor:pointer" onclick="sUI.openUserEdit(' + i + ')">' +
|
||||
'<h4>' + esc(u.user) + (u.role === 'admin' ? ' <span class="badge active">管理员</span>' : '') + '</h4>' +
|
||||
'<div class="cfg-kv"><label>角色</label><b>' + (u.role === 'admin' ? '管理员' : '普通用户') + '</b></div>' +
|
||||
'<div class="cfg-kv"><label>默认模型</label><b>' + esc(u.model || '不锁定') + '</b></div>' +
|
||||
'</div>').join('') +
|
||||
'<div class="empty-tip">点用户卡片修改角色、默认模型或密码。</div>';
|
||||
}
|
||||
// 弹窗工作态:-1 = 新增;否则 SET.users 下标。用户名不可改(后端也没有改名接口)。
|
||||
let userEditIdx = -1;
|
||||
function openUserEditor(i) {
|
||||
const u = i == null ? null : SET.users[i];
|
||||
userEditIdx = u ? i : -1;
|
||||
$('ue-title').textContent = u ? '编辑用户' : '添加用户';
|
||||
$('ue-user').value = u ? u.user : '';
|
||||
$('ue-user').disabled = !!u;
|
||||
$('ue-pass').value = '';
|
||||
$('ue-pass').placeholder = u ? '留空 = 不修改密码' : '初始密码(至少 6 位)';
|
||||
$('ue-role').value = u ? u.role : 'user';
|
||||
$('ue-model').innerHTML = userModelOptions(u ? u.model : '');
|
||||
$('ue-del-btn').classList.toggle('hidden', !u);
|
||||
$('user-edit-modal').classList.remove('hidden');
|
||||
if (!u) $('ue-user').focus();
|
||||
}
|
||||
function openUserAdd() { openUserEditor(null); }
|
||||
function closeUserModal() {
|
||||
$('user-edit-modal').classList.add('hidden');
|
||||
userEditIdx = -1;
|
||||
}
|
||||
async function saveUser() {
|
||||
const editing = userEditIdx >= 0;
|
||||
const user = $('ue-user').value.trim();
|
||||
const password = $('ue-pass').value;
|
||||
const role = $('ue-role').value;
|
||||
const model = $('ue-model').value;
|
||||
if (!user) return toast('用户名不能为空');
|
||||
if (!editing && password.length < 6) return toast('密码至少 6 位');
|
||||
if (editing && password && password.length < 6) return toast('新密码至少 6 位');
|
||||
try {
|
||||
if (editing) {
|
||||
const body = { role, model };
|
||||
if (password) body.password = password;
|
||||
await req('PATCH', '/api/users/' + encodeURIComponent(user), body);
|
||||
} else {
|
||||
await req('POST', '/api/users', { user, password, role, model });
|
||||
}
|
||||
closeUserModal();
|
||||
toast(editing ? '已保存' : '已添加用户 ' + user);
|
||||
renderSetPage();
|
||||
} catch (e) { toast('保存失败:' + e.message); }
|
||||
}
|
||||
async function userDelFromModal() {
|
||||
const u = SET.users[userEditIdx];
|
||||
if (!u) return;
|
||||
if (!await confirmModal('删除用户', '删除「' + u.user + '」后该账号立即失效;其会话与画像数据保留。', '删除', true)) return;
|
||||
try {
|
||||
await req('DELETE', '/api/users/' + encodeURIComponent(u.user));
|
||||
closeUserModal();
|
||||
toast('已删除');
|
||||
renderSetPage();
|
||||
} catch (e) { toast('删除失败:' + e.message); }
|
||||
}
|
||||
|
||||
// ---------- 微信绑定(账户页内联卡 #wx-zone;一人一绑无子页,签名比对增量更新防闪烁) ----------
|
||||
// 体验约定:后端绑定/刷新/解绑全 fire-and-forget,点击秒回;QR 只在 has_qr(wxbot 实例快照里码已就绪)
|
||||
// 后才 fetch 内联 SVG——不再有无码必坏的 <img> 首帧;轮询只在渲染串真的变了才动 DOM,pending 之外停表。
|
||||
@@ -593,10 +695,8 @@
|
||||
}
|
||||
async function setPageService(ctx) {
|
||||
setTitle('服务');
|
||||
// 临时隐藏右上角"编辑配置文件"按钮(sUI.openCfg),恢复时取消下方注释即可
|
||||
// setActions('<button class="icon-btn" title="编辑配置文件" onclick="sUI.openCfg()">' +
|
||||
// '<svg class="ic" viewBox="0 0 24 24"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"></path><path d="M18.5 2.5a2.12 2.12 0 0 1 3 3L12 15l-4 1 1-4z"></path></svg></button>');
|
||||
setActions('');
|
||||
setActions('<button class="icon-btn" title="编辑配置文件" onclick="sUI.openCfg()">' +
|
||||
'<svg class="ic" viewBox="0 0 24 24"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"></path><path d="M18.5 2.5a2.12 2.12 0 0 1 3 3L12 15l-4 1 1-4z"></path></svg></button>');
|
||||
setBody('<div class="set-scroll" id="svc-body"><div class="empty-tip">加载中…</div></div>');
|
||||
try {
|
||||
const [st, cg] = await Promise.all([
|
||||
@@ -1518,6 +1618,12 @@
|
||||
// 账户
|
||||
changePassword: changePassword,
|
||||
saveProfile: saveProfile,
|
||||
// 用户管理(仅管理员)
|
||||
openUserAdd: openUserAdd,
|
||||
openUserEdit: openUserEditor,
|
||||
closeUserModal: closeUserModal,
|
||||
saveUser: saveUser,
|
||||
userDelFromModal: userDelFromModal,
|
||||
// 微信绑定
|
||||
wxBind: wxBind,
|
||||
wxRefresh: wxRefresh,
|
||||
@@ -1587,6 +1693,12 @@
|
||||
return;
|
||||
}
|
||||
verifiedUser = String(j.user);
|
||||
SET.role = j.role === 'admin' ? 'admin' : 'user';
|
||||
SET.authEnabled = true;
|
||||
} else {
|
||||
// /api/me 404 = 未启用多用户认证:单用户自用,全部设置可见(用户管理页因 auth 关闭而隐藏)
|
||||
SET.role = 'admin';
|
||||
SET.authEnabled = false;
|
||||
}
|
||||
} catch (_) { /* 网络错误放过,让后续请求正常走 */ }
|
||||
loadSessionList();
|
||||
|
||||
@@ -0,0 +1,175 @@
|
||||
// 用户管理(仅管理员):增删改查 config.yml 的 auth.users(用户名 / 密码 / 角色 / 默认模型)。
|
||||
// 写盘后同步刷新内存(engine.cfg.auth.users + auth 的登录校验表),立即生效、无需重启:
|
||||
// 新增用户马上能登录,删除的用户已签发 token 立刻失效(sessionUser 查的是刷新后的表)。
|
||||
// 删除只移除登录能力:会话、画像、长期记忆、微信绑定等数据按约定保留。
|
||||
const express = require('express');
|
||||
const engine = require('../engine');
|
||||
const log = require('../log');
|
||||
const { readConfigText, applyEditsToText, loadConfigFromText, writeConfigText } = require('../config');
|
||||
|
||||
// 用户名同时是 YAML 值、日志字段和 URL 路径参数:只允许字母/数字/下划线/点/横线/@/中文,
|
||||
// 放开空白或斜杠会让 PATCH/DELETE 的路径与日志难以辨认。
|
||||
const USER_RE = /^[\w.\-@\u4e00-\u9fa5]{1,32}$/;
|
||||
|
||||
function bad(msg, code) { return Object.assign(new Error(msg), { status_code: code || 400 }); }
|
||||
function sendErr(res, err) { res.status((err && err.status_code) || 500).json({ error: String((err && err.message) || err) }); }
|
||||
function wrap(fn) {
|
||||
return function (req, res) {
|
||||
try {
|
||||
const r = fn(req, res);
|
||||
if (r && typeof r.catch === 'function') r.catch(err => sendErr(res, err));
|
||||
} catch (err) { sendErr(res, err); }
|
||||
};
|
||||
}
|
||||
|
||||
function publicUsers(users) {
|
||||
return (users || []).map(u => ({ user: u.user, role: u.role, model: u.model || '' }));
|
||||
}
|
||||
|
||||
// 启用中的模型清单(cfg.models 按 key 展开过,这里按 id 去重、过滤禁用),供前端下拉。
|
||||
function modelChoices(cfg) {
|
||||
const seen = new Set();
|
||||
const out = [];
|
||||
for (const m of cfg.models || []) {
|
||||
if (m.enable === false || seen.has(m.id)) continue;
|
||||
seen.add(m.id);
|
||||
out.push({ id: m.id, name: m.display_name || m.mid || m.id });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function adminCount(users) {
|
||||
return (users || []).filter(u => u.role === 'admin').length;
|
||||
}
|
||||
|
||||
function requireAuthCfg() {
|
||||
const cfg = engine.getConfig();
|
||||
if (!cfg.auth || !Array.isArray(cfg.auth.users) || !cfg.auth.users.length) {
|
||||
throw bad('未启用多用户认证(config.yml 的 auth.users 为空)');
|
||||
}
|
||||
return cfg;
|
||||
}
|
||||
|
||||
function normName(v) {
|
||||
const name = String(v == null ? '' : v).trim();
|
||||
if (!name) throw bad('用户名不能为空');
|
||||
if (!USER_RE.test(name)) throw bad('用户名只能包含字母/数字/下划线/点/横线/@/中文,最长 32 字符');
|
||||
return name;
|
||||
}
|
||||
function normPassword(v) {
|
||||
const p = String(v == null ? '' : v);
|
||||
if (p.length < 6) throw bad('密码至少 6 位');
|
||||
return p;
|
||||
}
|
||||
function normRole(v) {
|
||||
const r = String(v == null ? '' : v).trim();
|
||||
if (!r) return 'user';
|
||||
if (r !== 'admin' && r !== 'user') throw bad('角色只能是 admin 或 user');
|
||||
return r;
|
||||
}
|
||||
function normModel(cfg, v) {
|
||||
const model = String(v == null ? '' : v).trim();
|
||||
if (!model) return '';
|
||||
if (!modelChoices(cfg).some(m => m.id === model)) throw bad('模型不存在或已禁用:' + model);
|
||||
return model;
|
||||
}
|
||||
|
||||
// 写盘 + 热更新:先校验(不合法不动文件),再同步 cfg.auth.users 与 auth 的登录校验表。
|
||||
function saveUsers(cfg, nextText, auth) {
|
||||
const next = loadConfigFromText(nextText, cfg.config_path);
|
||||
writeConfigText(cfg, nextText);
|
||||
const nextUsers = (next.auth && next.auth.users) || [];
|
||||
if (next.auth) {
|
||||
if (!cfg.auth) cfg.auth = next.auth;
|
||||
else cfg.auth.users = nextUsers;
|
||||
} else {
|
||||
cfg.auth = null;
|
||||
}
|
||||
auth.refreshUsers(nextUsers);
|
||||
return nextUsers;
|
||||
}
|
||||
|
||||
module.exports = function createUsersRouter(auth) {
|
||||
const router = express.Router();
|
||||
router.use(auth.requireAdmin);
|
||||
|
||||
// 列表:用户名/角色/默认模型(不回密码)+ 可选模型清单
|
||||
router.get('/', wrap((req, res) => {
|
||||
const cfg = engine.getConfig();
|
||||
const users = (cfg.auth && cfg.auth.users) || [];
|
||||
res.json({
|
||||
enabled: !!(cfg.auth && users.length),
|
||||
users: publicUsers(users),
|
||||
models: modelChoices(cfg),
|
||||
});
|
||||
}));
|
||||
|
||||
// 新增
|
||||
router.post('/', wrap((req, res) => {
|
||||
const cfg = requireAuthCfg();
|
||||
const b = req.body || {};
|
||||
const name = normName(b.user);
|
||||
const password = normPassword(b.password);
|
||||
const role = normRole(b.role);
|
||||
const model = normModel(cfg, b.model);
|
||||
if (cfg.auth.users.some(u => String(u.user) === name)) throw bad('用户名已存在:' + name, 409);
|
||||
const text = readConfigText(cfg);
|
||||
if (text === null) throw bad('配置文件不存在,无法保存用户', 409);
|
||||
const value = { user: name, password, role };
|
||||
if (model) value.model = model;
|
||||
const nextText = applyEditsToText(text, [{ path: ['auth', 'users'], append: true, value }]);
|
||||
const users = saveUsers(cfg, nextText, auth);
|
||||
log.info('auth', (req.user || '-') + ' 新增用户 ' + name + '(' + role + (model ? ',模型 ' + model : '') + ')');
|
||||
res.json({ ok: true, users: publicUsers(users) });
|
||||
}));
|
||||
|
||||
// 修改密码 / 角色 / 默认模型(只改传入的字段)
|
||||
router.patch('/:name', wrap((req, res) => {
|
||||
const cfg = requireAuthCfg();
|
||||
const name = String(req.params.name || '');
|
||||
const idx = cfg.auth.users.findIndex(u => String(u.user) === name);
|
||||
if (idx < 0) throw bad('用户不存在:' + name, 404);
|
||||
const cur = cfg.auth.users[idx];
|
||||
const b = req.body || {};
|
||||
const edits = [];
|
||||
if (b.password !== undefined) {
|
||||
edits.push({ path: ['auth', 'users', idx, 'password'], value: normPassword(b.password) });
|
||||
}
|
||||
if (b.role !== undefined) {
|
||||
const role = normRole(b.role);
|
||||
if (cur.role === 'admin' && role !== 'admin' && adminCount(cfg.auth.users) <= 1) {
|
||||
throw bad('至少保留一个管理员');
|
||||
}
|
||||
edits.push({ path: ['auth', 'users', idx, 'role'], value: role });
|
||||
}
|
||||
if (b.model !== undefined) {
|
||||
const model = normModel(cfg, b.model);
|
||||
if (model) edits.push({ path: ['auth', 'users', idx, 'model'], value: model });
|
||||
else if (cur.model) edits.push({ path: ['auth', 'users', idx, 'model'], delete: true });
|
||||
}
|
||||
if (!edits.length) throw bad('没有可修改的字段');
|
||||
const text = readConfigText(cfg);
|
||||
if (text === null) throw bad('配置文件不存在,无法保存用户', 409);
|
||||
const users = saveUsers(cfg, applyEditsToText(text, edits), auth);
|
||||
log.info('auth', (req.user || '-') + ' 修改用户 ' + name + ':' + Object.keys(b).join(','));
|
||||
res.json({ ok: true, users: publicUsers(users) });
|
||||
}));
|
||||
|
||||
// 删除(不允许删自己;至少保留一个管理员)
|
||||
router.delete('/:name', wrap((req, res) => {
|
||||
const cfg = requireAuthCfg();
|
||||
const name = String(req.params.name || '');
|
||||
if (name === String(req.user || '')) throw bad('不能删除当前登录用户');
|
||||
const idx = cfg.auth.users.findIndex(u => String(u.user) === name);
|
||||
if (idx < 0) throw bad('用户不存在:' + name, 404);
|
||||
if (cfg.auth.users[idx].role === 'admin' && adminCount(cfg.auth.users) <= 1) throw bad('至少保留一个管理员');
|
||||
const text = readConfigText(cfg);
|
||||
if (text === null) throw bad('配置文件不存在,无法保存用户', 409);
|
||||
const nextText = applyEditsToText(text, [{ path: ['auth', 'users', idx], delete: true }]);
|
||||
const users = saveUsers(cfg, nextText, auth);
|
||||
log.info('auth', (req.user || '-') + ' 删除用户 ' + name + '(会话与画像数据保留)');
|
||||
res.json({ ok: true, users: publicUsers(users) });
|
||||
}));
|
||||
|
||||
return router;
|
||||
};
|
||||
@@ -68,9 +68,16 @@ app.use('/api/sessions', require('./routes/sessions'));
|
||||
app.use('/api/sessions', require('./routes/messages'));
|
||||
app.use('/api/sessions', require('./routes/files'));
|
||||
app.use('/api/skills', require('./routes/skills'));
|
||||
app.use('/api/config', require('./routes/config'));
|
||||
// 系统配置含全部用户(脱敏密码)与平台密钥,且可整份改写 YAML:仅管理员可访问。
|
||||
app.use('/api/config', auth.requireAdmin, require('./routes/config'));
|
||||
app.use('/api/platforms', require('./routes/platforms'));
|
||||
app.use('/api/system', require('./routes/system'));
|
||||
// 系统状态(上传参数等)所有登录用户可用;重启仅管理员。
|
||||
const systemRouter = require('./routes/system');
|
||||
app.use('/api/system', (req, res, next) => (
|
||||
req.path === '/restart' ? auth.requireAdmin(req, res, next) : next()
|
||||
), systemRouter);
|
||||
// 用户管理(管理员):auth.users 增删改 + 角色/默认模型;写盘后热更新,无需重启。
|
||||
app.use('/api/users', require('./routes/users')(auth));
|
||||
// 用户画像(账户设置):读写按登录用户隔离,逻辑在 user-profile.js
|
||||
app.use('/api/profile', require('./routes/profile'));
|
||||
// 长期记忆(日记)只读调试视图:独立页 /memory.html 的供数接口,查表即答零写操作
|
||||
|
||||
@@ -197,6 +197,7 @@ auth:
|
||||
users:
|
||||
- user: $AUTH_USER
|
||||
password: "$AUTH_PASSWORD"
|
||||
role: admin # 初始账号为管理员;其余用户的增删/角色/默认模型在前端「设置→用户」里配
|
||||
|
||||
mcp_servers:
|
||||
- name: web_search
|
||||
|
||||
Reference in New Issue
Block a user