feat: 管理面板(登录认证+触发AI分析+统计+CLI改密码)
This commit is contained in:
@@ -0,0 +1,11 @@
|
||||
# 同花顺金融数据 API 密钥
|
||||
fuyao_apikey=sk-fuyao-xxxx
|
||||
|
||||
# AI 分析配置
|
||||
AI_API_BASE=https://your-api-base/v1
|
||||
AI_API_KEY=sk-your-api-key
|
||||
AI_MODEL=deepseek-v4-flash
|
||||
|
||||
|
||||
# 管理面板密码(默认 !auvauv,建议修改)
|
||||
ADMIN_PASSWORD=!auvauv
|
||||
@@ -30,6 +30,7 @@ Thumbs.db
|
||||
# Node.js / JavaScript / TypeScript
|
||||
node_modules/
|
||||
dist/
|
||||
!dist/admin.html
|
||||
build/
|
||||
.next/
|
||||
.nuxt/
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
#!/usr/bin/env python3
|
||||
"""管理密码设置工具
|
||||
|
||||
用法:
|
||||
python3 admin_cli.py # 首次设置密码
|
||||
python3 admin_cli.py <新密码> # 修改密码
|
||||
python3 admin_cli.py --check # 检查是否已设置密码
|
||||
"""
|
||||
import sys
|
||||
import os
|
||||
|
||||
# 添加 backend 目录到 path
|
||||
sys.path.insert(0, os.path.dirname(__file__))
|
||||
|
||||
from services.admin_auth import is_configured, set_password
|
||||
|
||||
|
||||
def main():
|
||||
if len(sys.argv) > 1 and sys.argv[1] == "--check":
|
||||
if is_configured():
|
||||
print("✅ 管理密码已设置")
|
||||
else:
|
||||
print("⚠️ 管理密码未设置,请运行: python3 admin_cli.py")
|
||||
return
|
||||
|
||||
if len(sys.argv) > 1:
|
||||
new_password = sys.argv[1]
|
||||
else:
|
||||
import getpass
|
||||
if is_configured():
|
||||
print("修改管理密码")
|
||||
else:
|
||||
print("设置管理密码")
|
||||
new_password = getpass.getpass("请输入密码: ")
|
||||
confirm = getpass.getpass("请再次输入密码: ")
|
||||
if new_password != confirm:
|
||||
print("❌ 两次输入不一致")
|
||||
sys.exit(1)
|
||||
|
||||
if len(new_password) < 4:
|
||||
print("❌ 密码至少4位")
|
||||
sys.exit(1)
|
||||
|
||||
set_password(new_password)
|
||||
print(f"✅ 管理密码已{'更新' if is_configured() else '设置'}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Vendored
+275
@@ -0,0 +1,275 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>AUV 管理面板</title>
|
||||
<style>
|
||||
*{margin:0;padding:0;box-sizing:border-box}
|
||||
body{font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,sans-serif;background:#0f172a;color:#e2e8f0;min-height:100vh}
|
||||
.login-wrap{display:flex;align-items:center;justify-content:center;min-height:100vh;padding:20px}
|
||||
.login-box{background:#1e293b;border-radius:12px;padding:40px;width:100%;max-width:400px;box-shadow:0 4px 24px rgba(0,0,0,.3)}
|
||||
.login-box h1{text-align:center;font-size:24px;margin-bottom:8px;color:#38bdf8}
|
||||
.login-box p{text-align:center;color:#94a3b8;margin-bottom:24px;font-size:14px}
|
||||
.form-group{margin-bottom:16px}
|
||||
.form-group label{display:block;font-size:13px;color:#94a3b8;margin-bottom:6px}
|
||||
.form-group input{width:100%;padding:10px 14px;border:1px solid #334155;border-radius:8px;background:#0f172a;color:#e2e8f0;font-size:15px;outline:none;transition:border .2s}
|
||||
.form-group input:focus{border-color:#38bdf8}
|
||||
.btn{display:inline-flex;align-items:center;justify-content:center;padding:10px 20px;border:none;border-radius:8px;font-size:14px;font-weight:500;cursor:pointer;transition:all .2s;width:100%}
|
||||
.btn-primary{background:#38bdf8;color:#0f172a}.btn-primary:hover{background:#7dd3fc}
|
||||
.btn-danger{background:#ef4444;color:#fff}.btn-danger:hover{background:#f87171}
|
||||
.btn-sm{padding:6px 14px;width:auto;font-size:13px}
|
||||
.btn:disabled{opacity:.5;cursor:not-allowed}
|
||||
.error{color:#f87171;font-size:13px;margin-top:8px;text-align:center}
|
||||
|
||||
/* Dashboard */
|
||||
.dashboard{display:none;max-width:960px;margin:0 auto;padding:24px}
|
||||
.topbar{display:flex;justify-content:space-between;align-items:center;margin-bottom:24px;padding-bottom:16px;border-bottom:1px solid #1e293b}
|
||||
.topbar h1{font-size:20px;color:#38bdf8}
|
||||
.topbar .actions{display:flex;gap:8px;align-items:center}
|
||||
.stats-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(180px,1fr));gap:12px;margin-bottom:24px}
|
||||
.stat-card{background:#1e293b;border-radius:10px;padding:16px}
|
||||
.stat-card .label{font-size:12px;color:#94a3b8;margin-bottom:4px}
|
||||
.stat-card .value{font-size:24px;font-weight:600;color:#f8fafc}
|
||||
.section{background:#1e293b;border-radius:10px;padding:20px;margin-bottom:20px}
|
||||
.section h2{font-size:16px;color:#cbd5e1;margin-bottom:16px;display:flex;align-items:center;gap:8px}
|
||||
.section h2 .icon{font-size:18px}
|
||||
table{width:100%;border-collapse:collapse}
|
||||
th{text-align:left;font-size:12px;color:#64748b;padding:8px 12px;border-bottom:1px solid #334155}
|
||||
td{padding:8px 12px;font-size:13px;border-bottom:1px solid #1e293b;color:#cbd5e1}
|
||||
tr:hover td{background:rgba(56,189,248,.05)}
|
||||
.badge{display:inline-block;padding:2px 8px;border-radius:4px;font-size:11px;font-weight:500}
|
||||
.badge-blue{background:rgba(56,189,248,.15);color:#38bdf8}
|
||||
.badge-green{background:rgba(34,197,94,.15);color:#22c55e}
|
||||
.trigger-result{margin-top:12px;padding:12px;border-radius:8px;font-size:13px;display:none}
|
||||
.trigger-result.success{display:block;background:rgba(34,197,94,.1);border:1px solid #22c55e;color:#22c55e}
|
||||
.trigger-result.error{display:block;background:rgba(239,68,68,.1);border:1px solid #ef4444;color:#f87171}
|
||||
.loading{opacity:.6;pointer-events:none}
|
||||
.spinner{display:inline-block;width:14px;height:14px;border:2px solid transparent;border-top-color:currentColor;border-radius:50%;animation:spin .6s linear infinite;margin-right:6px}
|
||||
@keyframes spin{to{transform:rotate(360deg)}}
|
||||
.toast{position:fixed;bottom:24px;right:24px;padding:12px 20px;border-radius:8px;font-size:13px;z-index:9999;animation:fadeIn .3s}
|
||||
@keyframes fadeIn{from{opacity:0;transform:translateY(8px)}to{opacity:1;transform:translateY(0)}}
|
||||
.toast-ok{background:#166534;color:#bbf7d0}
|
||||
.toast-err{background:#991b1b;color:#fecaca}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<!-- Login -->
|
||||
<div class="login-wrap" id="loginWrap">
|
||||
<div class="login-box">
|
||||
<h1>AUV 管理面板</h1>
|
||||
<p>A股走势追踪系统</p>
|
||||
<div class="form-group">
|
||||
<label>管理密码</label>
|
||||
<input type="password" id="pwdInput" placeholder="输入密码" autofocus>
|
||||
</div>
|
||||
<div id="loginError" class="error" style="display:none"></div>
|
||||
<button class="btn btn-primary" id="loginBtn" onclick="doLogin()">登 录</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Dashboard -->
|
||||
<div class="dashboard" id="dashWrap">
|
||||
<div class="topbar">
|
||||
<h1>AUV 管理面板</h1>
|
||||
<div class="actions">
|
||||
<button class="btn btn-primary btn-sm" onclick="doTrigger()" id="triggerBtn">
|
||||
<span id="triggerSpinner" class="spinner" style="display:none"></span>
|
||||
触发 AI 分析
|
||||
</button>
|
||||
<button class="btn btn-sm" style="background:#334155;color:#e2e8f0" onclick="showChangePwd()">改密码</button>
|
||||
<button class="btn btn-sm" style="background:#334155;color:#e2e8f0" onclick="doLogout()">退出</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="stats-grid" id="statsGrid"></div>
|
||||
|
||||
<div id="triggerResult" class="trigger-result"></div>
|
||||
|
||||
<div class="section">
|
||||
<h2><span class="icon">📊</span> 分析报告</h2>
|
||||
<table>
|
||||
<thead><tr><th>日期</th><th>标题</th><th>模型</th><th>Tokens</th><th>创建时间</th><th>操作</th></tr></thead>
|
||||
<tbody id="reportsBody"></tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<div class="section">
|
||||
<h2><span class="icon">📈</span> 近期报告</h2>
|
||||
<table>
|
||||
<thead><tr><th>日期</th><th>标题</th><th>Tokens</th></tr></thead>
|
||||
<tbody id="recentBody"></tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Change Password Modal -->
|
||||
<div id="pwdModal" style="display:none;position:fixed;inset:0;background:rgba(0,0,0,.6);z-index:100;display:none;align-items:center;justify-content:center">
|
||||
<div style="background:#1e293b;border-radius:12px;padding:24px;width:360px">
|
||||
<h3 style="margin-bottom:16px;font-size:16px">修改密码</h3>
|
||||
<div class="form-group"><label>原密码</label><input type="password" id="oldPwd"></div>
|
||||
<div class="form-group"><label>新密码</label><input type="password" id="newPwd"></div>
|
||||
<div id="pwdError" class="error" style="display:none"></div>
|
||||
<div style="display:flex;gap:8px;margin-top:16px">
|
||||
<button class="btn btn-primary btn-sm" style="flex:1" onclick="doChangePwd()">确认</button>
|
||||
<button class="btn btn-sm" style="flex:1;background:#334155;color:#e2e8f0" onclick="hideChangePwd()">取消</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
const API = location.origin;
|
||||
let token = localStorage.getItem('admin_token');
|
||||
|
||||
// Init
|
||||
if (token) showDashboard();
|
||||
else document.getElementById('pwdInput').focus();
|
||||
|
||||
document.getElementById('pwdInput').addEventListener('keydown', e => { if (e.key === 'Enter') doLogin() });
|
||||
|
||||
async function api(method, path, body) {
|
||||
const opts = { method, headers: { 'Content-Type': 'application/json', 'X-Admin-Token': token } };
|
||||
if (body) opts.body = JSON.stringify(body);
|
||||
const r = await fetch(API + path, opts);
|
||||
const j = await r.json();
|
||||
if (!r.ok) throw new Error(j.detail || '请求失败');
|
||||
return j.data;
|
||||
}
|
||||
|
||||
function toast(msg, ok) {
|
||||
const d = document.createElement('div');
|
||||
d.className = 'toast ' + (ok ? 'toast-ok' : 'toast-err');
|
||||
d.textContent = msg;
|
||||
document.body.appendChild(d);
|
||||
setTimeout(() => d.remove(), 3000);
|
||||
}
|
||||
|
||||
async function doLogin() {
|
||||
const pwd = document.getElementById('pwdInput').value;
|
||||
if (!pwd) return;
|
||||
const errEl = document.getElementById('loginError');
|
||||
try {
|
||||
const data = await api('POST', '/api/admin/login', { password: pwd });
|
||||
token = data.token;
|
||||
localStorage.setItem('admin_token', token);
|
||||
errEl.style.display = 'none';
|
||||
showDashboard();
|
||||
} catch (e) {
|
||||
errEl.textContent = e.message;
|
||||
errEl.style.display = 'block';
|
||||
}
|
||||
}
|
||||
|
||||
function doLogout() {
|
||||
api('POST', '/api/admin/logout').catch(() => {});
|
||||
token = null;
|
||||
localStorage.removeItem('admin_token');
|
||||
document.getElementById('dashWrap').style.display = 'none';
|
||||
document.getElementById('loginWrap').style.display = 'flex';
|
||||
document.getElementById('pwdInput').value = '';
|
||||
}
|
||||
|
||||
async function showDashboard() {
|
||||
document.getElementById('loginWrap').style.display = 'none';
|
||||
document.getElementById('dashWrap').style.display = 'block';
|
||||
try {
|
||||
const stats = await api('GET', '/api/admin/stats');
|
||||
renderStats(stats);
|
||||
renderReports(stats.recentReports || []);
|
||||
// load full list
|
||||
const reports = await api('GET', '/api/admin/reports');
|
||||
renderAllReports(reports);
|
||||
} catch (e) {
|
||||
if (e.message.includes('401') || e.message.includes('未登录')) doLogout();
|
||||
}
|
||||
}
|
||||
|
||||
function renderStats(s) {
|
||||
const grid = document.getElementById('statsGrid');
|
||||
grid.innerHTML = `
|
||||
<div class="stat-card"><div class="label">分析报告</div><div class="value">${s.reportCount}</div></div>
|
||||
<div class="stat-card"><div class="label">总 Tokens</div><div class="value">${s.totalTokens?.toLocaleString() || 0}</div></div>
|
||||
<div class="stat-card"><div class="label">股票集合</div><div class="value">${s.collectionCount}</div></div>
|
||||
<div class="stat-card"><div class="label">关注股票</div><div class="value">${s.stockCount}</div></div>
|
||||
<div class="stat-card"><div class="label">分享链接</div><div class="value">${s.shareLinkCount}</div></div>
|
||||
<div class="stat-card"><div class="label">核心股天数</div><div class="value">${s.coreStockDays}</div></div>
|
||||
`;
|
||||
}
|
||||
|
||||
function renderReports(list) {
|
||||
document.getElementById('recentBody').innerHTML = list.map(r =>
|
||||
`<tr><td>${r.trade_date}</td><td>${r.title || '-'}</td><td>${r.tokens_used || 0}</td></tr>`
|
||||
).join('') || '<tr><td colspan="3" style="color:#64748b;text-align:center">暂无数据</td></tr>';
|
||||
}
|
||||
|
||||
function renderAllReports(list) {
|
||||
document.getElementById('reportsBody').innerHTML = list.map(r =>
|
||||
`<tr>
|
||||
<td>${r.trade_date}</td>
|
||||
<td>${r.title || '-'}</td>
|
||||
<td><span class="badge badge-blue">${r.model || '-'}</span></td>
|
||||
<td>${r.tokens_used || 0}</td>
|
||||
<td>${r.created_at || '-'}</td>
|
||||
<td><button class="btn btn-danger btn-sm" style="padding:4px 10px;font-size:12px" onclick="deleteReport(${r.id})">删除</button></td>
|
||||
</tr>`
|
||||
).join('') || '<tr><td colspan="6" style="color:#64748b;text-align:center">暂无报告</td></tr>';
|
||||
}
|
||||
|
||||
async function doTrigger() {
|
||||
const btn = document.getElementById('triggerBtn');
|
||||
const spinner = document.getElementById('triggerSpinner');
|
||||
const result = document.getElementById('triggerResult');
|
||||
btn.disabled = true;
|
||||
spinner.style.display = 'inline-block';
|
||||
result.className = 'trigger-result';
|
||||
result.style.display = 'none';
|
||||
try {
|
||||
const data = await api('POST', '/api/admin/trigger-analysis');
|
||||
result.className = 'trigger-result success';
|
||||
result.innerHTML = `✅ 分析完成 — Tokens: ${data.tokens_used} | 工具: ${(data.tools_used || []).length} 次调用`;
|
||||
result.style.display = 'block';
|
||||
showDashboard(); // refresh
|
||||
} catch (e) {
|
||||
result.className = 'trigger-result error';
|
||||
result.innerHTML = `❌ ${e.message}`;
|
||||
result.style.display = 'block';
|
||||
} finally {
|
||||
btn.disabled = false;
|
||||
spinner.style.display = 'none';
|
||||
}
|
||||
}
|
||||
|
||||
async function deleteReport(id) {
|
||||
if (!confirm('确定删除该报告?')) return;
|
||||
try {
|
||||
await api('DELETE', '/api/admin/reports/' + id);
|
||||
toast('已删除', true);
|
||||
showDashboard();
|
||||
} catch (e) { toast(e.message, false); }
|
||||
}
|
||||
|
||||
function showChangePwd() {
|
||||
document.getElementById('pwdModal').style.display = 'flex';
|
||||
document.getElementById('oldPwd').value = '';
|
||||
document.getElementById('newPwd').value = '';
|
||||
document.getElementById('pwdError').style.display = 'none';
|
||||
}
|
||||
function hideChangePwd() { document.getElementById('pwdModal').style.display = 'none'; }
|
||||
|
||||
async function doChangePwd() {
|
||||
const oldp = document.getElementById('oldPwd').value;
|
||||
const newp = document.getElementById('newPwd').value;
|
||||
const errEl = document.getElementById('pwdError');
|
||||
try {
|
||||
await api('POST', '/api/admin/change-password', { old_password: oldp, new_password: newp });
|
||||
hideChangePwd();
|
||||
toast('密码已更新', true);
|
||||
} catch (e) {
|
||||
errEl.textContent = e.message;
|
||||
errEl.style.display = 'block';
|
||||
}
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
+18
-1
@@ -7,16 +7,23 @@ from contextlib import asynccontextmanager
|
||||
from dotenv import load_dotenv
|
||||
|
||||
from database import init_db
|
||||
from routes import stock, collections, shares, themes, core_stocks, fuyao, market_dashboard, ai_analysis
|
||||
from routes import stock, collections, shares, themes, core_stocks, fuyao, market_dashboard, ai_analysis, admin
|
||||
from services.daily_collector import collector_loop, cache_cleanup_loop
|
||||
from services.ai_collector import ai_analysis_loop
|
||||
from services.admin_auth import is_configured, set_password
|
||||
|
||||
load_dotenv()
|
||||
|
||||
DEFAULT_ADMIN_PASSWORD = os.getenv("ADMIN_PASSWORD", "!auvauv")
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
init_db()
|
||||
# 首次启动自动设置默认管理密码
|
||||
if not is_configured():
|
||||
set_password(DEFAULT_ADMIN_PASSWORD)
|
||||
print(f"[admin] 已设置默认管理密码,请尽快修改: python3 admin_cli.py")
|
||||
collector_task = asyncio.create_task(collector_loop())
|
||||
cache_cleanup_task = asyncio.create_task(cache_cleanup_loop())
|
||||
ai_analysis_task = asyncio.create_task(ai_analysis_loop())
|
||||
@@ -50,6 +57,7 @@ app.include_router(core_stocks.router, prefix="/api/core-stocks")
|
||||
app.include_router(fuyao.router, prefix="/api/v2")
|
||||
app.include_router(market_dashboard.router, prefix="/api")
|
||||
app.include_router(ai_analysis.router, prefix="/api")
|
||||
app.include_router(admin.router, prefix="/api")
|
||||
|
||||
# 生产模式:后端同时托管前端静态文件
|
||||
# catch-all 路由在 API 路由之后注册,所以 API 优先级更高
|
||||
@@ -58,6 +66,15 @@ dist_path = os.path.join(os.path.dirname(__file__), "dist")
|
||||
# HTML 不缓存:保证 index.html 永远最新(引用的资源文件名带 hash,可长缓存)
|
||||
_NO_CACHE_HTML = {"Cache-Control": "no-cache, no-store, must-revalidate"}
|
||||
|
||||
# 管理面板:/admin → admin.html(在 SPA catch-all 之前)
|
||||
ADMIN_HTML = os.path.join(dist_path, "admin.html")
|
||||
|
||||
@app.get("/admin")
|
||||
async def serve_admin():
|
||||
if os.path.isfile(ADMIN_HTML):
|
||||
return FileResponse(ADMIN_HTML, media_type="text/html", headers=_NO_CACHE_HTML)
|
||||
return JSONResponse({"detail": "Admin panel not found"}, status_code=404)
|
||||
|
||||
if os.path.isdir(dist_path):
|
||||
@app.get("/{full_path:path}")
|
||||
async def serve_spa(full_path: str):
|
||||
|
||||
@@ -0,0 +1,168 @@
|
||||
"""管理面板路由(/api/admin)
|
||||
|
||||
提供:
|
||||
- 登录认证(密码 + token)
|
||||
- 触发 AI 分析
|
||||
- 浏览统计
|
||||
- 报告管理
|
||||
"""
|
||||
|
||||
import json
|
||||
import time
|
||||
from datetime import datetime, timezone, timedelta
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Request
|
||||
from fastapi.responses import JSONResponse
|
||||
from pydantic import BaseModel
|
||||
|
||||
from services import admin_auth
|
||||
from database import get_connection, dict_from_row
|
||||
|
||||
_CST = timezone(timedelta(hours=8))
|
||||
_NO_CACHE_HEADERS = {"Cache-Control": "no-store, no-cache, must-revalidate, max-age=0"}
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
def _require_auth(request: Request) -> str:
|
||||
"""从 header 或 cookie 提取 token 并验证"""
|
||||
token = request.headers.get("X-Admin-Token", "")
|
||||
if not token:
|
||||
# fallback: 从 cookie 读
|
||||
token = request.cookies.get("admin_token", "")
|
||||
if not admin_auth.verify_token(token):
|
||||
raise HTTPException(status_code=401, detail="未登录或登录已过期")
|
||||
return token
|
||||
|
||||
|
||||
class LoginRequest(BaseModel):
|
||||
password: str
|
||||
|
||||
|
||||
@router.post("/admin/login", summary="管理员登录")
|
||||
async def admin_login(body: LoginRequest):
|
||||
if not admin_auth.is_configured():
|
||||
# 自动设置默认密码
|
||||
import os
|
||||
default_pw = os.getenv("ADMIN_PASSWORD", "!auvauv")
|
||||
admin_auth.set_password(default_pw)
|
||||
if not admin_auth.verify_password(body.password):
|
||||
raise HTTPException(status_code=401, detail="密码错误")
|
||||
token = admin_auth.create_token()
|
||||
return JSONResponse({"data": {"token": token, "expiresIn": admin_auth.TOKEN_TTL}})
|
||||
|
||||
|
||||
@router.post("/admin/logout", summary="管理员登出")
|
||||
async def admin_logout(request: Request):
|
||||
token = request.headers.get("X-Admin-Token", "") or request.cookies.get("admin_token", "")
|
||||
admin_auth.revoke_token(token)
|
||||
return JSONResponse({"data": "ok"})
|
||||
|
||||
|
||||
class ChangePasswordRequest(BaseModel):
|
||||
old_password: str
|
||||
new_password: str
|
||||
|
||||
|
||||
@router.post("/admin/change-password", summary="修改管理密码")
|
||||
async def admin_change_password(body: ChangePasswordRequest, request: Request):
|
||||
_require_auth(request)
|
||||
if not admin_auth.verify_password(body.old_password):
|
||||
raise HTTPException(status_code=401, detail="原密码错误")
|
||||
if len(body.new_password) < 4:
|
||||
raise HTTPException(status_code=400, detail="密码至少4位")
|
||||
admin_auth.set_password(body.new_password)
|
||||
return JSONResponse({"data": "密码已更新"})
|
||||
|
||||
|
||||
@router.get("/admin/stats", summary="管理面板统计数据")
|
||||
async def admin_stats(request: Request):
|
||||
_require_auth(request)
|
||||
conn = get_connection()
|
||||
try:
|
||||
stats = {}
|
||||
|
||||
# 报告总数
|
||||
row = conn.execute("SELECT COUNT(*) as cnt FROM ai_reports").fetchone()
|
||||
stats["reportCount"] = row["cnt"]
|
||||
|
||||
# 总 tokens
|
||||
row = conn.execute("SELECT COALESCE(SUM(tokens_used), 0) as total FROM ai_reports").fetchone()
|
||||
stats["totalTokens"] = row["total"]
|
||||
|
||||
# 最新报告
|
||||
row = conn.execute(
|
||||
"SELECT trade_date, title FROM ai_reports ORDER BY trade_date DESC LIMIT 1"
|
||||
).fetchone()
|
||||
stats["latestReport"] = dict_from_row(row) if row else None
|
||||
|
||||
# 集合数
|
||||
row = conn.execute("SELECT COUNT(*) as cnt FROM stock_collections").fetchone()
|
||||
stats["collectionCount"] = row["cnt"]
|
||||
|
||||
# 关注股票数
|
||||
row = conn.execute("SELECT COUNT(*) as cnt FROM collection_stocks").fetchone()
|
||||
stats["stockCount"] = row["cnt"]
|
||||
|
||||
# 分享链接数
|
||||
row = conn.execute("SELECT COUNT(*) as cnt FROM share_links").fetchone()
|
||||
stats["shareLinkCount"] = row["cnt"]
|
||||
|
||||
# 核心股天数
|
||||
row = conn.execute(
|
||||
"SELECT COUNT(DISTINCT trade_date) as cnt FROM daily_core_stocks"
|
||||
).fetchone()
|
||||
stats["coreStockDays"] = row["cnt"]
|
||||
|
||||
# 近7天报告
|
||||
rows = conn.execute(
|
||||
"SELECT trade_date, title, tokens_used, created_at FROM ai_reports "
|
||||
"ORDER BY trade_date DESC LIMIT 7"
|
||||
).fetchall()
|
||||
stats["recentReports"] = [dict_from_row(r) for r in rows]
|
||||
|
||||
return JSONResponse({"data": stats}, headers=_NO_CACHE_HEADERS)
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
@router.post("/admin/trigger-analysis", summary="触发 AI 分析")
|
||||
async def admin_trigger_analysis(request: Request):
|
||||
_require_auth(request)
|
||||
now = datetime.now(_CST)
|
||||
trade_date = now.strftime("%Y-%m-%d")
|
||||
|
||||
from services.ai_service import collect_ai_analysis
|
||||
result = await collect_ai_analysis(trade_date)
|
||||
return JSONResponse({"data": result})
|
||||
|
||||
|
||||
@router.get("/admin/reports", summary="报告列表(管理用)")
|
||||
async def admin_list_reports(request: Request):
|
||||
_require_auth(request)
|
||||
conn = get_connection()
|
||||
try:
|
||||
rows = conn.execute(
|
||||
"SELECT id, trade_date, report_type, title, summary, tools_used, model, tokens_used, created_at "
|
||||
"FROM ai_reports ORDER BY trade_date DESC, id DESC LIMIT 50"
|
||||
).fetchall()
|
||||
items = []
|
||||
for r in rows:
|
||||
item = dict_from_row(r)
|
||||
item["toolsUsed"] = json.loads(item.pop("tools_used") or "[]")
|
||||
items.append(item)
|
||||
return JSONResponse({"data": items}, headers=_NO_CACHE_HEADERS)
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
@router.delete("/admin/reports/{report_id}", summary="删除报告")
|
||||
async def admin_delete_report(report_id: int, request: Request):
|
||||
_require_auth(request)
|
||||
conn = get_connection()
|
||||
try:
|
||||
conn.execute("DELETE FROM ai_reports WHERE id = ?", (report_id,))
|
||||
conn.commit()
|
||||
return JSONResponse({"data": "已删除"})
|
||||
finally:
|
||||
conn.close()
|
||||
@@ -0,0 +1,75 @@
|
||||
"""管理员认证模块
|
||||
|
||||
密码存储:data/admin.json
|
||||
- password_hash: sha256 哈希
|
||||
- salt: 随机盐
|
||||
"""
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import secrets
|
||||
import time
|
||||
|
||||
DATA_DIR = os.path.join(os.path.dirname(os.path.dirname(__file__)), "data")
|
||||
ADMIN_FILE = os.path.join(DATA_DIR, "admin.json")
|
||||
|
||||
# 登录 token 有效期 24 小时
|
||||
TOKEN_TTL = 86400
|
||||
|
||||
# 内存中的活跃 token: {token: expire_ts}
|
||||
_active_tokens: dict[str, float] = {}
|
||||
|
||||
|
||||
def _hash_password(password: str, salt: str) -> str:
|
||||
return hashlib.sha256(f"{salt}:{password}".encode()).hexdigest()
|
||||
|
||||
|
||||
def is_configured() -> bool:
|
||||
return os.path.exists(ADMIN_FILE)
|
||||
|
||||
|
||||
def set_password(password: str) -> None:
|
||||
"""设置或更新管理员密码"""
|
||||
os.makedirs(DATA_DIR, exist_ok=True)
|
||||
salt = secrets.token_hex(16)
|
||||
data = {
|
||||
"password_hash": _hash_password(password, salt),
|
||||
"salt": salt,
|
||||
"updated_at": int(time.time()),
|
||||
}
|
||||
with open(ADMIN_FILE, "w") as f:
|
||||
json.dump(data, f, indent=2)
|
||||
|
||||
|
||||
def verify_password(password: str) -> bool:
|
||||
"""验证密码是否正确"""
|
||||
if not is_configured():
|
||||
return False
|
||||
with open(ADMIN_FILE) as f:
|
||||
data = json.load(f)
|
||||
return _hash_password(password, data["salt"]) == data["password_hash"]
|
||||
|
||||
|
||||
def create_token() -> str:
|
||||
"""创建登录 token"""
|
||||
token = secrets.token_urlsafe(32)
|
||||
_active_tokens[token] = time.time() + TOKEN_TTL
|
||||
return token
|
||||
|
||||
|
||||
def verify_token(token: str) -> bool:
|
||||
"""验证 token 是否有效"""
|
||||
if not token:
|
||||
return False
|
||||
expire = _active_tokens.get(token)
|
||||
if expire is None:
|
||||
return False
|
||||
if time.time() > expire:
|
||||
del _active_tokens[token]
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def revoke_token(token: str) -> None:
|
||||
"""吊销 token"""
|
||||
_active_tokens.pop(token, None)
|
||||
Reference in New Issue
Block a user