feat: 登录验证 + 邀请码注册 + 用量监控后台

- 新增用户认证系统(登录/登出/邀请码注册)
- 新增管理后台(邀请码管理/用户管理/使用记录/用量统计)
- 合成接口加登录验证,每次调用记录用户和稿件内容
- SQLite存储用户数据和使用日志
- 默认admin账号: simonkoson

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
lanhao
2026-07-02 18:51:23 +08:00
parent 3b6019d0f2
commit 223761e717
10 changed files with 1304 additions and 27 deletions
+313
View File
@@ -0,0 +1,313 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>管理后台 - 军事科技AI配音</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="admin-container">
<header class="admin-header">
<h1>管理后台</h1>
<div class="admin-nav">
<a href="/" class="btn btn-secondary">返回配音</a>
<button id="logoutBtn" class="btn btn-secondary">退出登录</button>
</div>
</header>
<!-- Tab 导航 -->
<div class="admin-tabs">
<button class="tab-btn active" data-tab="invites">邀请码管理</button>
<button class="tab-btn" data-tab="users">用户管理</button>
<button class="tab-btn" data-tab="logs">使用记录</button>
<button class="tab-btn" data-tab="stats">用量统计</button>
</div>
<!-- 邀请码管理 -->
<div class="tab-panel active" id="panel-invites">
<div class="panel-toolbar">
<h2>邀请码管理</h2>
<div class="invite-create">
<input type="text" id="editorNameInput" placeholder="编导姓名(如:张三)">
<button id="createInviteBtn" class="btn btn-primary">生成邀请码</button>
</div>
</div>
<table class="admin-table">
<thead>
<tr>
<th>邀请码</th>
<th>对应编导</th>
<th>状态</th>
<th>注册用户名</th>
<th>创建时间</th>
<th>操作</th>
</tr>
</thead>
<tbody id="inviteTableBody"></tbody>
</table>
</div>
<!-- 用户管理 -->
<div class="tab-panel" id="panel-users">
<h2>用户管理</h2>
<table class="admin-table">
<thead>
<tr>
<th>用户名</th>
<th>显示名</th>
<th>角色</th>
<th>状态</th>
<th>调用次数</th>
<th>总字数</th>
<th>注册时间</th>
<th>操作</th>
</tr>
</thead>
<tbody id="userTableBody"></tbody>
</table>
</div>
<!-- 使用记录 -->
<div class="tab-panel" id="panel-logs">
<div class="panel-toolbar">
<h2>使用记录</h2>
<div class="log-filters">
<select id="logUserFilter"><option value="">全部用户</option></select>
<input type="date" id="logDateFrom">
<input type="date" id="logDateTo">
<button id="filterLogsBtn" class="btn btn-secondary">筛选</button>
</div>
</div>
<table class="admin-table">
<thead>
<tr>
<th>时间</th>
<th>用户</th>
<th>引擎</th>
<th>字数</th>
<th>稿件内容</th>
</tr>
</thead>
<tbody id="logTableBody"></tbody>
</table>
<div class="pagination" id="logPagination"></div>
</div>
<!-- 用量统计 -->
<div class="tab-panel" id="panel-stats">
<h2>用量统计</h2>
<div class="stats-summary" id="statsSummary"></div>
<table class="admin-table">
<thead>
<tr>
<th>用户</th>
<th>显示名</th>
<th>调用次数</th>
<th>总字数</th>
<th>最后使用</th>
</tr>
</thead>
<tbody id="statsTableBody"></tbody>
</table>
</div>
</div>
<script>
let currentLogPage = 1;
// ===== 权限检查 =====
async function checkAdmin() {
try {
const res = await fetch('/api/me');
if (!res.ok) { window.location.href = '/login.html'; return false; }
const data = await res.json();
if (data.user.role !== 'admin') {
alert('仅管理员可访问');
window.location.href = '/';
return false;
}
return true;
} catch (e) {
window.location.href = '/login.html';
return false;
}
}
// ===== Tab 切换 =====
document.querySelectorAll('.tab-btn').forEach(btn => {
btn.addEventListener('click', () => {
document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
document.querySelectorAll('.tab-panel').forEach(p => p.classList.remove('active'));
btn.classList.add('active');
document.getElementById('panel-' + btn.dataset.tab).classList.add('active');
});
});
// ===== 邀请码 =====
async function loadInvites() {
const res = await fetch('/api/admin/invites');
const data = await res.json();
document.getElementById('inviteTableBody').innerHTML = data.invites.map(inv => `
<tr>
<td><code class="invite-code">${inv.code}</code></td>
<td>${inv.editor_name}</td>
<td>${inv.is_used
? '<span class="badge badge-used">已使用</span>'
: '<span class="badge badge-active">未使用</span>'}</td>
<td>${inv.used_by_username || '-'}</td>
<td>${inv.created_at}</td>
<td>${inv.is_used
? '-'
: `<button class="btn-sm btn-danger" onclick="deleteInvite(${inv.id})">删除</button>`}</td>
</tr>
`).join('');
}
document.getElementById('createInviteBtn').addEventListener('click', async () => {
const name = document.getElementById('editorNameInput').value.trim();
if (!name) { alert('请填写编导姓名'); return; }
const res = await fetch('/api/admin/invites', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ editor_name: name })
});
const data = await res.json();
if (data.success) {
alert(`邀请码已生成:${data.code}\n对应编导:${data.editor_name}\n\n请将此邀请码发给该编导`);
document.getElementById('editorNameInput').value = '';
loadInvites();
}
});
async function deleteInvite(id) {
if (!confirm('确认删除该邀请码?')) return;
await fetch(`/api/admin/invites/${id}`, { method: 'DELETE' });
loadInvites();
}
// ===== 用户管理 =====
async function loadUsers() {
const res = await fetch('/api/admin/users');
const data = await res.json();
// 填充日志筛选下拉框
const filterSelect = document.getElementById('logUserFilter');
filterSelect.innerHTML = '<option value="">全部用户</option>'
+ data.users.map(u => `<option value="${u.id}">${u.display_name}(${u.username})</option>`).join('');
document.getElementById('userTableBody').innerHTML = data.users.map(u => `
<tr>
<td>${u.username}</td>
<td>${u.display_name}</td>
<td>${u.role === 'admin' ? '管理员' : '编导'}</td>
<td>${u.is_active
? '<span class="badge badge-active">启用</span>'
: '<span class="badge badge-used">停用</span>'}</td>
<td>${u.usage_count}</td>
<td>${u.total_chars}</td>
<td>${u.created_at}</td>
<td>${u.role !== 'admin'
? `<button class="btn-sm ${u.is_active ? 'btn-danger' : 'btn-primary'}"
onclick="toggleUser(${u.id}, ${u.is_active ? 0 : 1})">
${u.is_active ? '停用' : '启用'}
</button>`
: '-'}</td>
</tr>
`).join('');
}
async function toggleUser(id, newStatus) {
const action = newStatus ? '启用' : '停用';
if (!confirm(`确认${action}该用户?`)) return;
await fetch(`/api/admin/users/${id}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ is_active: newStatus })
});
loadUsers();
}
// ===== 使用记录 =====
async function loadLogs(page) {
page = page || 1;
currentLogPage = page;
const userId = document.getElementById('logUserFilter').value;
const dateFrom = document.getElementById('logDateFrom').value;
const dateTo = document.getElementById('logDateTo').value;
let url = `/api/admin/logs?page=${page}&per_page=50`;
if (userId) url += `&user_id=${userId}`;
if (dateFrom) url += `&date_from=${dateFrom}`;
if (dateTo) url += `&date_to=${dateTo}`;
const res = await fetch(url);
const data = await res.json();
document.getElementById('logTableBody').innerHTML = data.logs.map(log => `
<tr>
<td class="nowrap">${log.created_at}</td>
<td>${log.display_name}<br><small>${log.username}</small></td>
<td>${log.engine}</td>
<td>${log.text_length}</td>
<td class="text-cell">${escapeHtml(log.text_content)}</td>
</tr>
`).join('') || '<tr><td colspan="5" style="text-align:center;color:#999">暂无记录</td></tr>';
// 分页
const pag = document.getElementById('logPagination');
if (data.total_pages > 1) {
let html = '';
for (let i = 1; i <= data.total_pages; i++) {
html += `<button class="btn-sm ${i === page ? 'btn-primary' : ''}" onclick="loadLogs(${i})">${i}</button> `;
}
pag.innerHTML = html;
} else {
pag.innerHTML = '';
}
}
document.getElementById('filterLogsBtn').addEventListener('click', () => loadLogs(1));
// ===== 用量统计 =====
async function loadStats() {
const res = await fetch('/api/admin/stats');
const data = await res.json();
document.getElementById('statsSummary').innerHTML = `
<div class="stat-card"><h3>${data.totals.total_calls}</h3><p>总调用次数</p></div>
<div class="stat-card"><h3>${data.totals.total_chars}</h3><p>总合成字数</p></div>
<div class="stat-card"><h3>${data.totals.active_users}</h3><p>使用人数</p></div>
`;
document.getElementById('statsTableBody').innerHTML = data.user_stats.map(s => `
<tr>
<td>${s.username}</td>
<td>${s.display_name}</td>
<td>${s.call_count}</td>
<td>${s.total_chars}</td>
<td>${s.last_used}</td>
</tr>
`).join('') || '<tr><td colspan="5" style="text-align:center;color:#999">暂无数据</td></tr>';
}
function escapeHtml(str) {
const div = document.createElement('div');
div.textContent = str;
return div.innerHTML;
}
// ===== 退出 =====
document.getElementById('logoutBtn').addEventListener('click', async () => {
await fetch('/api/logout', { method: 'POST' });
window.location.href = '/login.html';
});
// ===== 初始化 =====
checkAdmin().then(ok => {
if (ok) {
loadInvites();
loadUsers();
loadLogs();
loadStats();
}
});
</script>
</body>
</html>
+33 -1
View File
@@ -358,7 +358,39 @@ elements.audioDisplay.addEventListener('click', () => {
if (state.generatedAudio && !state.isPlaying) { togglePlay(); }
});
function init() {
async function init() {
// 登录检测
try {
const res = await fetch('/api/me');
if (!res.ok) {
window.location.href = '/login.html';
return;
}
const data = await res.json();
const user = data.user;
// 在 header 右侧显示用户信息
const headerInfo = document.querySelector('.header-info');
headerInfo.innerHTML = `
<span class="engine-badge" id="engineBadge">蓝皓</span>
<span class="user-info">
${user.display_name}
${user.role === 'admin' ? '<a href="/admin.html" class="admin-link">管理后台</a>' : ''}
<a href="#" id="logoutLink" class="logout-link">退出</a>
</span>
`;
document.getElementById('logoutLink').addEventListener('click', async (e) => {
e.preventDefault();
await fetch('/api/logout', { method: 'POST' });
window.location.href = '/login.html';
});
} catch (e) {
window.location.href = '/login.html';
return;
}
updateCharCount();
updateSliderDisplay();
const savedHistory = localStorage.getItem('tts_history');
+135
View File
@@ -0,0 +1,135 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>登录 - 军事科技AI配音</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="auth-container">
<div class="auth-card">
<div class="auth-header">
<svg class="auth-logo" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<circle cx="12" cy="12" r="10"/>
<polygon points="10,8 16,12 10,16"/>
</svg>
<h1>军事科技 <span>AI配音</span></h1>
</div>
<!-- 登录表单 -->
<form id="loginForm" class="auth-form">
<h2>登录</h2>
<div class="form-group">
<label>用户名</label>
<input type="text" id="loginUsername" required autocomplete="username">
</div>
<div class="form-group">
<label>密码</label>
<input type="password" id="loginPassword" required autocomplete="current-password">
</div>
<button type="submit" class="btn btn-primary btn-full">登 录</button>
<p class="auth-switch">有邀请码?<a href="#" id="showRegister">点击注册</a></p>
<div class="auth-error" id="loginError"></div>
</form>
<!-- 注册表单 -->
<form id="registerForm" class="auth-form" style="display:none">
<h2>邀请码注册</h2>
<div class="form-group">
<label>邀请码</label>
<input type="text" id="regInviteCode" required placeholder="请输入管理员提供的邀请码">
</div>
<div class="form-group">
<label>用户名</label>
<input type="text" id="regUsername" required placeholder="自定义登录用户名" autocomplete="username">
</div>
<div class="form-group">
<label>密码</label>
<input type="password" id="regPassword" required placeholder="至少6位" autocomplete="new-password">
</div>
<div class="form-group">
<label>显示名称(选填)</label>
<input type="text" id="regDisplayName" placeholder="不填则使用邀请码绑定的姓名">
</div>
<button type="submit" class="btn btn-primary btn-full">注 册</button>
<p class="auth-switch"><a href="#" id="showLogin">返回登录</a></p>
<div class="auth-error" id="registerError"></div>
</form>
</div>
</div>
<script>
const loginForm = document.getElementById('loginForm');
const registerForm = document.getElementById('registerForm');
document.getElementById('showRegister').addEventListener('click', (e) => {
e.preventDefault();
loginForm.style.display = 'none';
registerForm.style.display = 'block';
});
document.getElementById('showLogin').addEventListener('click', (e) => {
e.preventDefault();
registerForm.style.display = 'none';
loginForm.style.display = 'block';
});
loginForm.addEventListener('submit', async (e) => {
e.preventDefault();
const errorEl = document.getElementById('loginError');
errorEl.textContent = '';
try {
const res = await fetch('/api/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
username: document.getElementById('loginUsername').value,
password: document.getElementById('loginPassword').value
})
});
const data = await res.json();
if (res.ok && data.success) {
window.location.href = '/';
} else {
errorEl.textContent = data.error || '登录失败';
}
} catch (err) {
errorEl.textContent = '网络错误,请重试';
}
});
registerForm.addEventListener('submit', async (e) => {
e.preventDefault();
const errorEl = document.getElementById('registerError');
errorEl.textContent = '';
try {
const res = await fetch('/api/register', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
invite_code: document.getElementById('regInviteCode').value,
username: document.getElementById('regUsername').value,
password: document.getElementById('regPassword').value,
display_name: document.getElementById('regDisplayName').value
})
});
const data = await res.json();
if (res.ok && data.success) {
alert(data.message + '\n请使用新账号登录');
registerForm.style.display = 'none';
loginForm.style.display = 'block';
} else {
errorEl.textContent = data.error || '注册失败';
}
} catch (err) {
errorEl.textContent = '网络错误,请重试';
}
});
// 如果已登录,直接跳主页
fetch('/api/me').then(res => {
if (res.ok) window.location.href = '/';
});
</script>
</body>
</html>
+342
View File
@@ -370,4 +370,346 @@ body {
@media (max-width: 768px) {
.toolbar { flex-direction: column; gap: 12px; }
.param-controls { grid-template-columns: 1fr; }
}
/* ========== 登录页 ========== */
.auth-container {
min-height: 100vh;
display: flex;
align-items: center;
justify-content: center;
background: linear-gradient(135deg, #0a0e1a 0%, #1a1f35 100%);
}
.auth-card {
background: #1e2438;
border-radius: 16px;
padding: 40px;
width: 100%;
max-width: 400px;
box-shadow: 0 20px 60px rgba(0, 0, 0, 0.5);
}
.auth-header {
text-align: center;
margin-bottom: 30px;
}
.auth-header h1 {
color: #fff;
font-size: 24px;
margin-top: 12px;
}
.auth-header h1 span {
color: #00d4aa;
}
.auth-logo {
width: 48px;
height: 48px;
color: #00d4aa;
}
.auth-form h2 {
color: #ccc;
font-size: 18px;
margin-bottom: 20px;
text-align: center;
}
.form-group {
margin-bottom: 16px;
}
.form-group label {
display: block;
color: #999;
font-size: 13px;
margin-bottom: 6px;
}
.form-group input {
width: 100%;
padding: 10px 14px;
background: #151929;
border: 1px solid #333;
border-radius: 8px;
color: #fff;
font-size: 14px;
outline: none;
box-sizing: border-box;
}
.form-group input:focus {
border-color: #00d4aa;
}
.btn-full {
width: 100%;
margin-top: 10px;
}
.auth-switch {
text-align: center;
margin-top: 16px;
color: #999;
font-size: 13px;
}
.auth-switch a {
color: #00d4aa;
text-decoration: none;
}
.auth-error {
color: #ff6b6b;
text-align: center;
margin-top: 12px;
font-size: 13px;
min-height: 20px;
}
/* ========== 用户信息 ========== */
.user-info {
display: inline-flex;
align-items: center;
gap: 12px;
color: #ccc;
font-size: 13px;
margin-left: 12px;
}
.admin-link, .logout-link {
color: #00d4aa;
text-decoration: none;
font-size: 12px;
}
.logout-link {
color: #999;
}
.admin-link:hover, .logout-link:hover {
text-decoration: underline;
}
/* ========== 管理后台 ========== */
.admin-container {
min-height: 100vh;
background: #0d1117;
color: #e6e6e6;
padding: 20px 30px;
}
.admin-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 20px;
padding-bottom: 16px;
border-bottom: 1px solid #2a2f3f;
}
.admin-header h1 {
font-size: 22px;
color: #fff;
}
.admin-nav {
display: flex;
gap: 10px;
}
.admin-tabs {
display: flex;
gap: 4px;
margin-bottom: 20px;
border-bottom: 2px solid #2a2f3f;
}
.tab-btn {
padding: 10px 20px;
background: transparent;
border: none;
color: #999;
cursor: pointer;
font-size: 14px;
border-bottom: 2px solid transparent;
margin-bottom: -2px;
}
.tab-btn.active {
color: #00d4aa;
border-bottom-color: #00d4aa;
}
.tab-panel {
display: none;
}
.tab-panel.active {
display: block;
}
.panel-toolbar {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 16px;
flex-wrap: wrap;
gap: 10px;
}
.panel-toolbar h2 {
font-size: 18px;
color: #fff;
}
.invite-create {
display: flex;
gap: 10px;
}
.invite-create input {
padding: 8px 12px;
background: #151929;
border: 1px solid #333;
border-radius: 6px;
color: #fff;
font-size: 14px;
outline: none;
}
.invite-code {
background: #00d4aa22;
color: #00d4aa;
padding: 3px 8px;
border-radius: 4px;
font-size: 14px;
letter-spacing: 1px;
user-select: all;
}
.admin-table {
width: 100%;
border-collapse: collapse;
font-size: 13px;
}
.admin-table th {
background: #1a1f35;
color: #999;
padding: 10px 12px;
text-align: left;
font-weight: normal;
white-space: nowrap;
}
.admin-table td {
padding: 10px 12px;
border-bottom: 1px solid #1e2438;
vertical-align: top;
}
.admin-table tr:hover td {
background: #151929;
}
.text-cell {
max-width: 400px;
white-space: pre-wrap;
word-break: break-all;
font-size: 12px;
color: #ccc;
line-height: 1.5;
}
.nowrap {
white-space: nowrap;
}
.badge {
display: inline-block;
padding: 2px 8px;
border-radius: 10px;
font-size: 12px;
}
.badge-active {
background: #00d4aa22;
color: #00d4aa;
}
.badge-used {
background: #ff6b6b22;
color: #ff6b6b;
}
.btn-sm {
padding: 4px 10px;
border: none;
border-radius: 4px;
cursor: pointer;
font-size: 12px;
color: #fff;
background: #333;
}
.btn-sm.btn-primary {
background: #00d4aa;
color: #000;
}
.btn-sm.btn-danger {
background: #ff6b6b;
}
.log-filters {
display: flex;
gap: 10px;
align-items: center;
}
.log-filters select,
.log-filters input[type="date"] {
padding: 6px 10px;
background: #151929;
border: 1px solid #333;
border-radius: 6px;
color: #fff;
font-size: 13px;
outline: none;
}
.pagination {
margin-top: 16px;
display: flex;
gap: 4px;
}
.stats-summary {
display: flex;
gap: 20px;
margin-bottom: 24px;
}
.stat-card {
background: #1a1f35;
border-radius: 12px;
padding: 20px 30px;
text-align: center;
flex: 1;
}
.stat-card h3 {
font-size: 32px;
color: #00d4aa;
margin: 0;
}
.stat-card p {
color: #999;
margin: 8px 0 0;
font-size: 13px;
}