添加管理页面
This commit is contained in:
parent
637d3e93b4
commit
aec78ec37a
162
backend/app/api/admin.py
Normal file
162
backend/app/api/admin.py
Normal file
@ -0,0 +1,162 @@
|
||||
"""
|
||||
后台管理API
|
||||
"""
|
||||
from fastapi import APIRouter, HTTPException, Depends, Request
|
||||
from typing import Optional
|
||||
from app.models.database import User
|
||||
from app.services.db_service import db_service
|
||||
from app.utils.logger import logger
|
||||
|
||||
router = APIRouter(prefix="/api/admin", tags=["后台管理"])
|
||||
|
||||
# 管理密码
|
||||
ADMIN_PASSWORD = "223388"
|
||||
|
||||
|
||||
def verify_admin_password(password: str):
|
||||
"""验证管理密码"""
|
||||
if password != ADMIN_PASSWORD:
|
||||
raise HTTPException(status_code=403, detail="密码错误")
|
||||
|
||||
|
||||
@router.post("/verify")
|
||||
async def verify_password(password: str):
|
||||
"""
|
||||
验证管理密码
|
||||
|
||||
Args:
|
||||
password: 管理密码
|
||||
|
||||
Returns:
|
||||
验证结果
|
||||
"""
|
||||
try:
|
||||
verify_admin_password(password)
|
||||
return {"success": True, "message": "验证成功"}
|
||||
except HTTPException:
|
||||
return {"success": False, "message": "密码错误"}
|
||||
|
||||
|
||||
@router.get("/users")
|
||||
async def get_users(
|
||||
password: str,
|
||||
page: int = 1,
|
||||
page_size: int = 20,
|
||||
search: Optional[str] = None
|
||||
):
|
||||
"""
|
||||
获取用户列表
|
||||
|
||||
Args:
|
||||
password: 管理密码
|
||||
page: 页码
|
||||
page_size: 每页数量
|
||||
search: 搜索关键词(手机号)
|
||||
|
||||
Returns:
|
||||
用户列表
|
||||
"""
|
||||
try:
|
||||
verify_admin_password(password)
|
||||
|
||||
db = db_service.get_session()
|
||||
try:
|
||||
# 构建查询
|
||||
query = db.query(User)
|
||||
|
||||
# 搜索过滤
|
||||
if search:
|
||||
query = query.filter(User.phone.like(f"%{search}%"))
|
||||
|
||||
# 总数
|
||||
total = query.count()
|
||||
|
||||
# 分页
|
||||
users = query.order_by(User.created_at.desc()).offset(
|
||||
(page - 1) * page_size
|
||||
).limit(page_size).all()
|
||||
|
||||
# 格式化返回数据
|
||||
user_list = []
|
||||
for user in users:
|
||||
user_list.append({
|
||||
"id": user.id,
|
||||
"phone": user.phone,
|
||||
"created_at": user.created_at.isoformat() if user.created_at else None,
|
||||
"last_login_at": user.last_login_at.isoformat() if user.last_login_at else None,
|
||||
"is_active": user.is_active
|
||||
})
|
||||
|
||||
return {
|
||||
"success": True,
|
||||
"data": {
|
||||
"users": user_list,
|
||||
"total": total,
|
||||
"page": page,
|
||||
"page_size": page_size,
|
||||
"total_pages": (total + page_size - 1) // page_size
|
||||
}
|
||||
}
|
||||
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
except HTTPException as e:
|
||||
raise e
|
||||
except Exception as e:
|
||||
logger.error(f"获取用户列表失败: {e}")
|
||||
raise HTTPException(status_code=500, detail="获取用户列表失败")
|
||||
|
||||
|
||||
@router.get("/stats")
|
||||
async def get_stats(password: str):
|
||||
"""
|
||||
获取统计数据
|
||||
|
||||
Args:
|
||||
password: 管理密码
|
||||
|
||||
Returns:
|
||||
统计数据
|
||||
"""
|
||||
try:
|
||||
verify_admin_password(password)
|
||||
|
||||
db = db_service.get_session()
|
||||
try:
|
||||
from app.models.database import Conversation, Message
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
# 用户总数
|
||||
total_users = db.query(User).count()
|
||||
|
||||
# 活跃用户(7天内登录)
|
||||
seven_days_ago = datetime.utcnow() - timedelta(days=7)
|
||||
active_users = db.query(User).filter(
|
||||
User.last_login_at >= seven_days_ago
|
||||
).count()
|
||||
|
||||
# 对话总数
|
||||
total_conversations = db.query(Conversation).count()
|
||||
|
||||
# 消息总数
|
||||
total_messages = db.query(Message).count()
|
||||
|
||||
return {
|
||||
"success": True,
|
||||
"data": {
|
||||
"total_users": total_users,
|
||||
"active_users": active_users,
|
||||
"total_conversations": total_conversations,
|
||||
"total_messages": total_messages
|
||||
}
|
||||
}
|
||||
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
except HTTPException as e:
|
||||
raise e
|
||||
except Exception as e:
|
||||
logger.error(f"获取统计数据失败: {e}")
|
||||
raise HTTPException(status_code=500, detail="获取统计数据失败")
|
||||
@ -7,7 +7,7 @@ from fastapi.staticfiles import StaticFiles
|
||||
from fastapi.responses import FileResponse
|
||||
from app.config import get_settings
|
||||
from app.utils.logger import logger
|
||||
from app.api import chat, stock, skills, llm, auth
|
||||
from app.api import chat, stock, skills, llm, auth, admin
|
||||
import os
|
||||
|
||||
# 创建FastAPI应用
|
||||
@ -29,6 +29,7 @@ app.add_middleware(
|
||||
|
||||
# 注册路由
|
||||
app.include_router(auth.router, tags=["认证"])
|
||||
app.include_router(admin.router, tags=["后台管理"])
|
||||
app.include_router(chat.router, prefix="/api/chat", tags=["对话"])
|
||||
app.include_router(stock.router, prefix="/api/stock", tags=["股票数据"])
|
||||
app.include_router(skills.router, prefix="/api/skills", tags=["技能管理"])
|
||||
|
||||
517
frontend/admin.html
Normal file
517
frontend/admin.html
Normal file
@ -0,0 +1,517 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>后台管理 - Tradus</title>
|
||||
<link rel="stylesheet" href="/static/css/style.css">
|
||||
<style>
|
||||
.admin-page {
|
||||
min-height: 100vh;
|
||||
background: var(--bg-primary);
|
||||
padding: 20px;
|
||||
}
|
||||
|
||||
.admin-container {
|
||||
max-width: 1400px;
|
||||
margin: 0 auto;
|
||||
}
|
||||
|
||||
.admin-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
margin-bottom: 40px;
|
||||
padding-bottom: 20px;
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
|
||||
.admin-title {
|
||||
font-size: 24px;
|
||||
font-weight: 300;
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.stats-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
|
||||
gap: 20px;
|
||||
margin-bottom: 40px;
|
||||
}
|
||||
|
||||
.stat-card {
|
||||
background: var(--bg-secondary);
|
||||
border: 1px solid var(--border-bright);
|
||||
border-radius: 4px;
|
||||
padding: 24px;
|
||||
}
|
||||
|
||||
.stat-label {
|
||||
font-size: 13px;
|
||||
color: var(--text-secondary);
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
.stat-value {
|
||||
font-size: 32px;
|
||||
font-weight: 300;
|
||||
color: var(--accent);
|
||||
}
|
||||
|
||||
.section-title {
|
||||
font-size: 18px;
|
||||
font-weight: 300;
|
||||
color: var(--text-primary);
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
.search-bar {
|
||||
display: flex;
|
||||
gap: 12px;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
.search-input {
|
||||
flex: 1;
|
||||
padding: 12px 16px;
|
||||
background: var(--bg-secondary);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 2px;
|
||||
color: var(--text-primary);
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.search-input:focus {
|
||||
outline: none;
|
||||
border-color: var(--accent);
|
||||
}
|
||||
|
||||
.search-btn {
|
||||
padding: 12px 24px;
|
||||
background: var(--accent);
|
||||
border: none;
|
||||
border-radius: 2px;
|
||||
color: var(--bg-primary);
|
||||
font-size: 14px;
|
||||
cursor: pointer;
|
||||
transition: all 0.2s;
|
||||
}
|
||||
|
||||
.search-btn:hover {
|
||||
box-shadow: 0 0 16px var(--accent-dim);
|
||||
}
|
||||
|
||||
.users-table {
|
||||
width: 100%;
|
||||
background: var(--bg-secondary);
|
||||
border: 1px solid var(--border-bright);
|
||||
border-radius: 4px;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.users-table table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
}
|
||||
|
||||
.users-table th {
|
||||
background: var(--bg-primary);
|
||||
padding: 16px;
|
||||
text-align: left;
|
||||
font-size: 13px;
|
||||
font-weight: 500;
|
||||
color: var(--text-secondary);
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
|
||||
.users-table td {
|
||||
padding: 16px;
|
||||
font-size: 14px;
|
||||
color: var(--text-primary);
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
|
||||
.users-table tr:last-child td {
|
||||
border-bottom: none;
|
||||
}
|
||||
|
||||
.users-table tr:hover {
|
||||
background: var(--bg-primary);
|
||||
}
|
||||
|
||||
.status-badge {
|
||||
display: inline-block;
|
||||
padding: 4px 12px;
|
||||
border-radius: 2px;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.status-active {
|
||||
background: rgba(0, 255, 128, 0.1);
|
||||
color: #00ff80;
|
||||
border: 1px solid rgba(0, 255, 128, 0.3);
|
||||
}
|
||||
|
||||
.status-inactive {
|
||||
background: rgba(255, 0, 64, 0.1);
|
||||
color: #ff0040;
|
||||
border: 1px solid rgba(255, 0, 64, 0.3);
|
||||
}
|
||||
|
||||
.pagination {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
margin-top: 20px;
|
||||
}
|
||||
|
||||
.pagination button {
|
||||
padding: 8px 16px;
|
||||
background: var(--bg-secondary);
|
||||
border: 1px solid var(--border-bright);
|
||||
border-radius: 2px;
|
||||
color: var(--text-primary);
|
||||
font-size: 14px;
|
||||
cursor: pointer;
|
||||
transition: all 0.2s;
|
||||
}
|
||||
|
||||
.pagination button:hover:not(:disabled) {
|
||||
border-color: var(--accent);
|
||||
color: var(--accent);
|
||||
}
|
||||
|
||||
.pagination button:disabled {
|
||||
opacity: 0.3;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
.pagination .page-info {
|
||||
color: var(--text-secondary);
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.login-overlay {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
background: rgba(0, 0, 0, 0.9);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
z-index: 1000;
|
||||
}
|
||||
|
||||
.login-box {
|
||||
width: 100%;
|
||||
max-width: 400px;
|
||||
padding: 40px;
|
||||
background: var(--bg-secondary);
|
||||
border: 1px solid var(--border-bright);
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
.login-box h2 {
|
||||
font-size: 24px;
|
||||
font-weight: 300;
|
||||
color: var(--text-primary);
|
||||
margin-bottom: 24px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.login-box input {
|
||||
width: 100%;
|
||||
padding: 12px 16px;
|
||||
background: var(--bg-primary);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 2px;
|
||||
color: var(--text-primary);
|
||||
font-size: 14px;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
.login-box input:focus {
|
||||
outline: none;
|
||||
border-color: var(--accent);
|
||||
}
|
||||
|
||||
.login-box button {
|
||||
width: 100%;
|
||||
padding: 14px;
|
||||
background: var(--accent);
|
||||
border: none;
|
||||
border-radius: 2px;
|
||||
color: var(--bg-primary);
|
||||
font-size: 14px;
|
||||
font-weight: 500;
|
||||
cursor: pointer;
|
||||
transition: all 0.2s;
|
||||
}
|
||||
|
||||
.login-box button:hover {
|
||||
box-shadow: 0 0 16px var(--accent-dim);
|
||||
}
|
||||
|
||||
.error-message {
|
||||
padding: 12px;
|
||||
background: rgba(255, 0, 64, 0.1);
|
||||
border: 1px solid rgba(255, 0, 64, 0.3);
|
||||
border-radius: 2px;
|
||||
color: #ff0040;
|
||||
font-size: 13px;
|
||||
text-align: center;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app">
|
||||
<!-- 登录遮罩 -->
|
||||
<div v-if="!authenticated" class="login-overlay">
|
||||
<div class="login-box">
|
||||
<h2>后台管理</h2>
|
||||
<div v-if="errorMessage" class="error-message">
|
||||
{{ errorMessage }}
|
||||
</div>
|
||||
<input
|
||||
type="password"
|
||||
v-model="password"
|
||||
placeholder="请输入管理密码"
|
||||
@keyup.enter="login"
|
||||
>
|
||||
<button @click="login">登录</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 管理页面 -->
|
||||
<div v-if="authenticated" class="admin-page">
|
||||
<div class="admin-container">
|
||||
<div class="admin-header">
|
||||
<h1 class="admin-title">后台管理</h1>
|
||||
<button class="search-btn" @click="logout">退出</button>
|
||||
</div>
|
||||
|
||||
<!-- 统计卡片 -->
|
||||
<div class="stats-grid">
|
||||
<div class="stat-card">
|
||||
<div class="stat-label">用户总数</div>
|
||||
<div class="stat-value">{{ stats.total_users }}</div>
|
||||
</div>
|
||||
<div class="stat-card">
|
||||
<div class="stat-label">活跃用户(7天)</div>
|
||||
<div class="stat-value">{{ stats.active_users }}</div>
|
||||
</div>
|
||||
<div class="stat-card">
|
||||
<div class="stat-label">对话总数</div>
|
||||
<div class="stat-value">{{ stats.total_conversations }}</div>
|
||||
</div>
|
||||
<div class="stat-card">
|
||||
<div class="stat-label">消息总数</div>
|
||||
<div class="stat-value">{{ stats.total_messages }}</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 用户列表 -->
|
||||
<h2 class="section-title">用户管理</h2>
|
||||
|
||||
<div class="search-bar">
|
||||
<input
|
||||
type="text"
|
||||
class="search-input"
|
||||
v-model="searchKeyword"
|
||||
placeholder="搜索手机号..."
|
||||
@keyup.enter="searchUsers"
|
||||
>
|
||||
<button class="search-btn" @click="searchUsers">搜索</button>
|
||||
</div>
|
||||
|
||||
<div class="users-table">
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>ID</th>
|
||||
<th>手机号</th>
|
||||
<th>注册时间</th>
|
||||
<th>最后登录</th>
|
||||
<th>状态</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-for="user in users" :key="user.id">
|
||||
<td>{{ user.id }}</td>
|
||||
<td>{{ user.phone }}</td>
|
||||
<td>{{ formatDate(user.created_at) }}</td>
|
||||
<td>{{ formatDate(user.last_login_at) }}</td>
|
||||
<td>
|
||||
<span :class="['status-badge', user.is_active ? 'status-active' : 'status-inactive']">
|
||||
{{ user.is_active ? '正常' : '禁用' }}
|
||||
</span>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<div class="pagination">
|
||||
<button @click="prevPage" :disabled="currentPage <= 1">上一页</button>
|
||||
<span class="page-info">第 {{ currentPage }} / {{ totalPages }} 页</span>
|
||||
<button @click="nextPage" :disabled="currentPage >= totalPages">下一页</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
|
||||
<script>
|
||||
const { createApp } = Vue;
|
||||
|
||||
createApp({
|
||||
data() {
|
||||
return {
|
||||
authenticated: false,
|
||||
password: '',
|
||||
errorMessage: '',
|
||||
adminPassword: '',
|
||||
stats: {
|
||||
total_users: 0,
|
||||
active_users: 0,
|
||||
total_conversations: 0,
|
||||
total_messages: 0
|
||||
},
|
||||
users: [],
|
||||
searchKeyword: '',
|
||||
currentPage: 1,
|
||||
pageSize: 20,
|
||||
totalPages: 1,
|
||||
total: 0
|
||||
};
|
||||
},
|
||||
mounted() {
|
||||
// 检查是否已登录
|
||||
const savedPassword = sessionStorage.getItem('admin_password');
|
||||
if (savedPassword) {
|
||||
this.adminPassword = savedPassword;
|
||||
this.authenticated = true;
|
||||
this.loadData();
|
||||
}
|
||||
},
|
||||
methods: {
|
||||
async login() {
|
||||
if (!this.password) {
|
||||
this.errorMessage = '请输入密码';
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch(`/api/admin/verify?password=${this.password}`, {
|
||||
method: 'POST'
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
if (data.success) {
|
||||
this.adminPassword = this.password;
|
||||
sessionStorage.setItem('admin_password', this.password);
|
||||
this.authenticated = true;
|
||||
this.errorMessage = '';
|
||||
this.loadData();
|
||||
} else {
|
||||
this.errorMessage = '密码错误';
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('登录失败:', error);
|
||||
this.errorMessage = '登录失败,请稍后重试';
|
||||
}
|
||||
},
|
||||
|
||||
logout() {
|
||||
sessionStorage.removeItem('admin_password');
|
||||
this.authenticated = false;
|
||||
this.adminPassword = '';
|
||||
this.password = '';
|
||||
},
|
||||
|
||||
async loadData() {
|
||||
await Promise.all([
|
||||
this.loadStats(),
|
||||
this.loadUsers()
|
||||
]);
|
||||
},
|
||||
|
||||
async loadStats() {
|
||||
try {
|
||||
const response = await fetch(`/api/admin/stats?password=${this.adminPassword}`);
|
||||
const data = await response.json();
|
||||
|
||||
if (data.success) {
|
||||
this.stats = data.data;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('加载统计数据失败:', error);
|
||||
}
|
||||
},
|
||||
|
||||
async loadUsers() {
|
||||
try {
|
||||
let url = `/api/admin/users?password=${this.adminPassword}&page=${this.currentPage}&page_size=${this.pageSize}`;
|
||||
|
||||
if (this.searchKeyword) {
|
||||
url += `&search=${encodeURIComponent(this.searchKeyword)}`;
|
||||
}
|
||||
|
||||
const response = await fetch(url);
|
||||
const data = await response.json();
|
||||
|
||||
if (data.success) {
|
||||
this.users = data.data.users;
|
||||
this.total = data.data.total;
|
||||
this.totalPages = data.data.total_pages;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('加载用户列表失败:', error);
|
||||
}
|
||||
},
|
||||
|
||||
searchUsers() {
|
||||
this.currentPage = 1;
|
||||
this.loadUsers();
|
||||
},
|
||||
|
||||
prevPage() {
|
||||
if (this.currentPage > 1) {
|
||||
this.currentPage--;
|
||||
this.loadUsers();
|
||||
}
|
||||
},
|
||||
|
||||
nextPage() {
|
||||
if (this.currentPage < this.totalPages) {
|
||||
this.currentPage++;
|
||||
this.loadUsers();
|
||||
}
|
||||
},
|
||||
|
||||
formatDate(dateString) {
|
||||
if (!dateString) return '-';
|
||||
|
||||
// 直接解析 ISO 格式的时间字符串,不做时区转换
|
||||
// 假设服务器返回的是 UTC 时间,我们将其视为本地时间显示
|
||||
const date = new Date(dateString + 'Z'); // 添加 Z 表示 UTC
|
||||
|
||||
// 获取各个时间部分
|
||||
const year = date.getFullYear();
|
||||
const month = String(date.getMonth() + 1).padStart(2, '0');
|
||||
const day = String(date.getDate()).padStart(2, '0');
|
||||
const hours = String(date.getHours()).padStart(2, '0');
|
||||
const minutes = String(date.getMinutes()).padStart(2, '0');
|
||||
|
||||
return `${year}-${month}-${day} ${hours}:${minutes}`;
|
||||
}
|
||||
}
|
||||
}).mount('#app');
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
Loading…
Reference in New Issue
Block a user