Files
3970260761 b48a526935 feat: 记录用户最后登录时间 + 面板时间列兼容毫秒时间戳
- patches/last-login.js: 最小 Redis RESP 客户端(touch/readMany)
- patches/inject_last_login.py: 注入 login 路由两条成功分支写 u:<user>:last_login,
  admin/users 回填 last_login_at / created_at(含 est 标记),可重复执行
- patches/apply.sh: 新增 4h 步骤,重建 .next 后自动恢复
- public-live/user-admin.js: toDate 兼容毫秒时间戳与 ISO
- patches/backfill_user_times.py: 默认演练(IDLETIME 在 Redis 重载后同值,会造假数据)
2026-11-07 01:26:12 +08:00

338 lines
17 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/* 米视TV 全新用户管理面板 V1 —— 原生JS,独立于React,点击“用户配置”打开 */
(function () {
if (window.__KAT_USERMGMT__) return;
window.__KAT_USERMGMT__ = 1;
var API_CFG = '/api/admin/config';
var API_USER = '/api/admin/user';
var API_USERS = '/api/admin/users';
var state = { users: [], allowRegister: false, loading: false, open: false };
function el(tag, attrs, kids) {
var n = document.createElement(tag);
if (attrs) for (var k in attrs) {
if (k === 'style') n.style.cssText = attrs[k];
else if (k === 'text') n.textContent = attrs[k];
else if (k.slice(0, 2) === 'on') n.addEventListener(k.slice(2).toLowerCase(), attrs[k]);
else n.setAttribute(k, attrs[k]);
}
(kids || []).forEach(function (c) { if (c) n.appendChild(c); });
return n;
}
function toast(msg, ok) {
var t = el('div', {
text: msg,
style: 'position:fixed;left:50%;top:24px;transform:translateX(-50%);z-index:2147483647;' +
'background:' + (ok === false ? '#dc2626' : '#059669') + ';color:#fff;padding:10px 20px;border-radius:10px;' +
'font-size:14px;box-shadow:0 8px 24px rgba(0,0,0,.25);font-family:inherit'
});
document.body.appendChild(t);
setTimeout(function () { t.remove(); }, 2200);
}
function api(action, targetUsername, targetPassword, extra) {
var body = { action: action };
if (targetUsername) body.targetUsername = targetUsername;
if (targetPassword) body.targetPassword = targetPassword;
if (extra) for (var k in extra) body[k] = extra[k];
return fetch(API_USER, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body)
}).then(function (r) { return r.json().then(function (j) { return { ok: r.ok, data: j }; }).catch(function () { return { ok: r.ok, data: {} }; }); });
}
function load() {
state.loading = true; render();
var times = {};
// 时间信息(注册/最后登录)来自 /api/admin/users
var pTimes = fetch(API_USERS, { headers: { 'Cache-Control': 'no-cache' } })
.then(function (r) { return r.json(); })
.then(function (j) {
var arr = (j && Array.isArray(j.users)) ? j.users : [];
arr.forEach(function (x) {
if (x && x.username) times[String(x.username)] = x;
});
})
.catch(function () { });
return pTimes
.then(function () {
return fetch(API_CFG, { headers: { 'Cache-Control': 'no-cache' } });
})
.then(function (r) { return r.json(); })
.then(function (cfg) {
var root = (cfg && cfg.Config) ? cfg.Config : (cfg || {});
var uc = root.UserConfig || {};
var list = Array.isArray(uc.Users) ? uc.Users : [];
state.users = list.filter(function (u) { return u && typeof u === 'object'; }).map(function (u) {
var name = String(typeof u.username === 'object' && u.username ? (u.username.username || '') : (u.username || ''));
var t = times[name] || {};
return {
username: name,
role: String(u.role || t.role || 'user'),
banned: !!u.banned,
created_at: t.created_at ? String(t.created_at) : (u.created_at ? String(u.created_at) : ''),
created_at_estimated: !!(t.created_at_estimated || u.created_at_estimated),
last_login_at: t.last_login_at ? String(t.last_login_at) : '',
last_login_estimated: !!(t.last_login_estimated || u.last_login_estimated)
};
});
state.allowRegister = !!uc.AllowRegister;
})
.catch(function () { toast('读取用户列表失败', false); })
.then(function () { state.loading = false; render(); });
}
function roleLabel(r) { return r === 'owner' ? '站长' : r === 'admin' ? '管理员' : '普通用户'; }
function toDate(v) {
if (!v) return null;
var s = String(v);
var d = /^\d+$/.test(s) ? new Date(Number(s)) : new Date(v);
return isNaN(d.getTime()) ? null : d;
}
function fmtDateTime(v) {
if (!v) return '从未登录';
var d = toDate(v);
if (!d) return String(v).slice(0, 16).replace('T', ' ');
var p = function (n) { return (n < 10 ? '0' : '') + n; };
return d.getFullYear() + '-' + p(d.getMonth() + 1) + '-' + p(d.getDate()) + ' ' + p(d.getHours()) + ':' + p(d.getMinutes());
}
function fmtDate(v) {
if (!v) return '-';
var d = toDate(v);
if (!d) return String(v).slice(0, 10);
var p = function (n) { return (n < 10 ? '0' : '') + n; };
return d.getFullYear() + '-' + p(d.getMonth() + 1) + '-' + p(d.getDate());
}
function btn(text, color, fn, disabled) {
var colors = {
green: 'background:#059669;color:#fff',
red: 'background:#dc2626;color:#fff',
gray: 'background:#e5e7eb;color:#111827',
purple: 'background:#7c3aed;color:#fff',
blue: 'background:#2563eb;color:#fff'
};
var b = el('button', {
text: text,
style: 'border:0;border-radius:6px;padding:5px 10px;font-size:12px;cursor:pointer;margin:2px 3px;' +
(colors[color] || colors.gray) + ';font-family:inherit' + (disabled ? ';opacity:.5;cursor:not-allowed' : '')
}, []);
if (!disabled) b.addEventListener('click', function () { fn(); });
return b;
}
function ask(title, fields, cb) {
var wrap = el('div', { style: 'position:fixed;inset:0;background:rgba(0,0,0,.5);z-index:2147483646;display:flex;align-items:center;justify-content:center' });
var box = el('div', { style: 'background:#fff;border-radius:12px;padding:20px;min-width:300px;max-width:92vw;box-shadow:0 20px 50px rgba(0,0,0,.3);font-family:inherit' });
box.appendChild(el('div', { text: title, style: 'font-size:16px;font-weight:600;margin-bottom:14px;color:#111827' }));
var inputs = {};
fields.forEach(function (f) {
var lab = el('div', { text: f.label, style: 'font-size:12px;color:#6b7280;margin:8px 0 4px' });
var inp = el('input', { type: f.password ? 'password' : 'text', placeholder: f.placeholder || '', style: 'width:100%;box-sizing:border-box;border:1px solid #d1d5db;border-radius:8px;padding:8px 10px;font-size:14px;outline:none' });
if (f.value) inp.value = f.value;
if (f.readonly) inp.readOnly = true;
inputs[f.key] = inp;
box.appendChild(lab); box.appendChild(inp);
});
var bar = el('div', { style: 'display:flex;justify-content:flex-end;gap:8px;margin-top:18px' });
bar.appendChild(el('button', { text: '取消', style: 'border:0;background:#e5e7eb;color:#111827;padding:8px 16px;border-radius:8px;cursor:pointer;font-size:14px', onclick: function () { wrap.remove(); } }));
bar.appendChild(el('button', { text: '确定', style: 'border:0;background:#059669;color:#fff;padding:8px 16px;border-radius:8px;cursor:pointer;font-size:14px', onclick: function () { cb(inputs, wrap); } }));
box.appendChild(bar); wrap.appendChild(box); document.body.appendChild(wrap);
var first = inputs[fields[0].key]; if (first) first.focus();
}
function confirmDo(msg, fn) {
var wrap = el('div', { style: 'position:fixed;inset:0;background:rgba(0,0,0,.5);z-index:2147483646;display:flex;align-items:center;justify-content:center' });
var box = el('div', { style: 'background:#fff;border-radius:12px;padding:20px;min-width:280px;max-width:92vw;box-shadow:0 20px 50px rgba(0,0,0,.3);font-family:inherit' });
box.appendChild(el('div', { text: msg, style: 'font-size:15px;color:#111827;margin-bottom:16px;line-height:1.5' }));
var bar = el('div', { style: 'display:flex;justify-content:flex-end;gap:8px' });
bar.appendChild(el('button', { text: '取消', style: 'border:0;background:#e5e7eb;color:#111827;padding:8px 16px;border-radius:8px;cursor:pointer;font-size:14px', onclick: function () { wrap.remove(); } }));
bar.appendChild(el('button', { text: '确定', style: 'border:0;background:#dc2626;color:#fff;padding:8px 16px;border-radius:8px;cursor:pointer;font-size:14px', onclick: function () { wrap.remove(); fn(); } }));
box.appendChild(bar); wrap.appendChild(box); document.body.appendChild(wrap);
}
var overlay, bodyBox;
function render() {
if (!overlay) return;
bodyBox.innerHTML = '';
var me = '';
try { var u = JSON.parse(localStorage.getItem('user') || '{}'); me = u && u.username ? String(u.username) : ''; } catch (e) { }
bodyBox.appendChild(el('div', {
text: state.loading ? '加载中…' : '共 ' + state.users.length + ' 个用户',
style: 'font-size:12px;color:#6b7280;margin-bottom:10px'
}));
var table = el('table', { style: 'width:100%;border-collapse:collapse;font-size:13px' });
var thead = el('thead', {}, [el('tr', {}, ['用户名', '角色', '状态', '注册时间', '最后登录', '操作'].map(function (h) {
return el('th', { text: h, style: 'text-align:left;padding:8px 6px;color:#6b7280;font-weight:600;border-bottom:1px solid #e5e7eb;white-space:nowrap' });
}))]);
table.appendChild(thead);
var tbody = el('tbody', {}, []);
state.users.forEach(function (u) {
var isOwner = u.role === 'owner';
var isSelf = me && u.username === me;
var ops = el('div', { style: 'display:flex;flex-wrap:wrap' }, []);
ops.appendChild(btn('修改密码', 'blue', function () {
ask('修改用户密码 - ' + u.username, [{ key: 'pwd', label: '新密码', password: true, placeholder: '请输入新密码' }], function (inp, w) {
var pwd = inp.pwd.value.trim();
if (!pwd) { toast('密码不能为空', false); return; }
api('changePassword', u.username, pwd).then(function (r) {
w.remove();
if (r.ok) { toast('密码已修改'); } else { toast((r.data && r.data.error) || '修改失败', false); }
});
});
}));
if (!isOwner && !isSelf) {
if (u.role === 'admin') {
ops.appendChild(btn('取消管理', 'gray', function () {
confirmDo('确定取消 ' + u.username + ' 的管理员权限?', function () {
api('cancelAdmin', u.username).then(function (r) { toast(r.ok ? '已取消管理' : ((r.data && r.data.error) || '操作失败'), r.ok); load(); });
});
}));
} else {
ops.appendChild(btn('设为管理', 'purple', function () {
confirmDo('确定将 ' + u.username + ' 设为管理员?', function () {
api('setAdmin', u.username).then(function (r) { toast(r.ok ? '已设为管理员' : ((r.data && r.data.error) || '操作失败'), r.ok); load(); });
});
}));
}
ops.appendChild(btn(u.banned ? '解封' : '封禁', u.banned ? 'green' : 'red', function () {
confirmDo((u.banned ? '确定解封 ' : '确定封禁 ') + u.username + '?', function () {
api(u.banned ? 'unban' : 'ban', u.username).then(function (r) { toast(r.ok ? '操作成功' : ((r.data && r.data.error) || '操作失败'), r.ok); load(); });
});
}));
ops.appendChild(btn('删除', 'red', function () {
confirmDo('确定删除用户 ' + u.username + '?此操作不可恢复。', function () {
api('deleteUser', u.username).then(function (r) { toast(r.ok ? '已删除' : ((r.data && r.data.error) || '删除失败'), r.ok); load(); });
});
}));
} else if (isSelf) {
ops.appendChild(el('span', { text: '当前登录账号', style: 'font-size:12px;color:#9ca3af;padding:6px 4px' }));
}
var tr = el('tr', {}, [
el('td', { text: u.username, style: 'padding:8px 6px;border-bottom:1px solid #f3f4f6;font-weight:500;color:#111827;white-space:nowrap' }),
el('td', { text: roleLabel(u.role), style: 'padding:8px 6px;border-bottom:1px solid #f3f4f6;color:#374151;white-space:nowrap' }),
el('td', { text: u.banned ? '已封禁' : '正常', style: 'padding:8px 6px;border-bottom:1px solid #f3f4f6;color:' + (u.banned ? '#dc2626' : '#059669') + ';white-space:nowrap' }),
el('td', { text: (u.created_at ? (u.created_at_estimated ? '约 ' : '') + fmtDate(u.created_at) : '未记录'), style: 'padding:8px 6px;border-bottom:1px solid #f3f4f6;color:#6b7280;white-space:nowrap', title: u.created_at_estimated ? '该账号早于时间记录功能上线,此处为首次记录时间' : '' }),
el('td', { text: (u.last_login_at && u.last_login_estimated ? '约 ' : '') + fmtDateTime(u.last_login_at), title: u.last_login_estimated ? '按账号活跃记录推算的近似时间' : '', style: 'padding:8px 6px;border-bottom:1px solid #f3f4f6;color:' + (u.last_login_at ? '#6b7280' : '#9ca3af') + ';white-space:nowrap' }),
el('td', { style: 'padding:8px 6px;border-bottom:1px solid #f3f4f6' }, [ops])
]);
tbody.appendChild(tr);
});
table.appendChild(tbody);
bodyBox.appendChild(el('div', { style: 'overflow-x:auto;border:1px solid #f3f4f6;border-radius:10px' }, [table]));
// 底部操作区
var bar = el('div', { style: 'display:flex;flex-wrap:wrap;gap:8px;margin-top:14px;align-items:center' }, []);
bar.appendChild(btn('➕ 添加用户', 'green', function () {
ask('添加用户', [
{ key: 'u', label: '用户名', placeholder: '字母/数字' },
{ key: 'p', label: '密码', password: true, placeholder: '初始密码' }
], function (inp, w) {
var un = inp.u.value.trim(), pw = inp.p.value.trim();
if (!un || !pw) { toast('用户名和密码不能为空', false); return; }
api('add', un, pw).then(function (r) {
if (r.ok) { w.remove(); toast('用户已添加'); load(); }
else { toast((r.data && r.data.error) || '添加失败', false); }
});
});
}));
var regBtn = btn(state.allowRegister ? '注册:已开放(点击关闭)' : '注册:已关闭(点击开放)', state.allowRegister ? 'green' : 'gray', function () {
api('setAllowRegister', null, null, { allowRegister: !state.allowRegister }).then(function (r) {
toast(r.ok ? '注册设置已更新' : ((r.data && r.data.error) || '操作失败'), r.ok); load();
});
});
bar.appendChild(regBtn);
bar.appendChild(btn('刷新', 'blue', function () { load(); }));
bodyBox.appendChild(bar);
}
function openPanel() {
if (state.open) return;
state.open = true;
overlay = el('div', {
style: 'position:fixed;inset:0;background:rgba(0,0,0,.45);z-index:2147483600;display:flex;align-items:flex-start;justify-content:center;padding:5vh 12px;overflow:auto'
});
overlay.addEventListener('click', function (e) { if (e.target === overlay) closePanel(); });
var panel = el('div', {
style: 'background:#fff;border-radius:14px;padding:18px;width:100%;max-width:900px;box-shadow:0 24px 60px rgba(0,0,0,.35);font-family:inherit'
});
var head = el('div', { style: 'display:flex;align-items:center;justify-content:space-between;margin-bottom:12px' }, []);
head.appendChild(el('div', { text: '用户管理', style: 'font-size:18px;font-weight:700;color:#111827' }));
head.appendChild(el('button', {
text: '关闭', style: 'border:0;background:#f3f4f6;color:#374151;padding:6px 14px;border-radius:8px;cursor:pointer;font-size:13px',
onclick: closePanel
}));
panel.appendChild(head);
bodyBox = el('div', {}, []);
panel.appendChild(bodyBox);
overlay.appendChild(panel);
document.body.appendChild(overlay);
document.addEventListener('keydown', escClose);
load();
}
function escClose(e) { if (e.key === 'Escape') closePanel(); }
function closePanel() {
state.open = false;
if (overlay) { overlay.remove(); overlay = null; bodyBox = null; }
document.removeEventListener('keydown', escClose);
}
function findCardHeader() {
var nodes = document.querySelectorAll('div,button,h3,span');
for (var i = 0; i < nodes.length; i++) {
var n = nodes[i];
if (n.childElementCount === 0 && n.textContent.trim() === '用户配置') return n;
}
return null;
}
function hook() {
var header = findCardHeader();
if (!header || header.__katHooked) return !!header;
header.__katHooked = 1;
var card = header.closest('div');
// 捕获阶段拦截,阻止 React 展开已经损坏的旧组件
var stop = function (e) { e.preventDefault(); e.stopPropagation(); openPanel(); };
header.addEventListener('click', stop, true);
if (card) card.addEventListener('click', function (e) {
// 卡片内部点空白也打开我们的面板
if (!e.target.closest('#__kat_um_root')) { e.preventDefault(); e.stopPropagation(); openPanel(); }
}, true);
return true;
}
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', start);
else start();
function start() {
if (location.pathname !== '/admin') return;
setTimeout(function () {
var h = findCardHeader();
if (!h || h.__katCosmetic) return;
h.__katCosmetic = 1;
try { h.textContent = '用户管理'; } catch (e) {}
try {
var hint = document.createElement('span');
hint.textContent = ' · 点击打开管理面板';
hint.style.cssText = 'font-size:12px;color:#9ca3af;font-weight:400;margin-left:6px';
if (h.parentNode) h.parentNode.appendChild(hint);
} catch (e) {}
}, 4000);
var tries = 0;
var timer = setInterval(function () {
tries++;
if (hook() || tries > 120) clearInterval(timer);
}, 250);
}
})();