File size: 20,919 Bytes
b7560a4 bb8a633 0b3288e 985ffab 0b3288e b7560a4 bb8a633 2f630e2 0b3288e 2f630e2 0b3288e 2f630e2 0b3288e 2f630e2 40dd9a0 b7560a4 40dd9a0 b7560a4 40dd9a0 bb8a633 b7560a4 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 |
import express from 'express';
import cors from 'cors';
import helmet from 'helmet';
import rateLimit from 'express-rate-limit';
import dotenv from 'dotenv';
import path from 'path';
import { fileURLToPath } from 'url';
import authRoutes from './routes/auth.js';
import pptRoutes from './routes/ppt.js';
import publicRoutes from './routes/public.js';
import { authenticateToken } from './middleware/auth.js';
import { errorHandler } from './middleware/errorHandler.js';
dotenv.config();
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const app = express();
const PORT = process.env.PORT || 7860; // 修改为7860端口
// 安全中间件
app.use(helmet({
contentSecurityPolicy: false, // 为了兼容前端静态文件
}));
// 限流中间件
const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15分钟
max: 100, // 每个IP每15分钟最多100个请求
message: 'Too many requests from this IP, please try again later.'
});
app.use('/api', limiter);
// CORS配置
app.use(cors({
origin: process.env.FRONTEND_URL || '*',
credentials: true
}));
app.use(express.json({ limit: '50mb' }));
app.use(express.urlencoded({ extended: true, limit: '50mb' }));
// 提供前端静态文件
app.use(express.static(path.join(__dirname, '../../frontend/dist')));
// 提供数据文件
app.use('/data', express.static(path.join(__dirname, '../../frontend/public/mocks')));
// 直接提供测试页面路由
app.get('/test.html', (req, res) => {
try {
// 检查文件是否存在
const testFilePath = path.join(__dirname, '../../test.html');
console.log('Looking for test.html at:', testFilePath);
// 发送测试页面
res.sendFile(testFilePath, (err) => {
if (err) {
console.error('Error serving test.html:', err);
// 如果文件不存在,返回一个简单的测试页面
res.send(`
<!DOCTYPE html>
<html>
<head><title>Test Page</title></head>
<body>
<h1>PPTist API Test</h1>
<p>Test file not found at: ${testFilePath}</p>
<button onclick="fetch('/api/health').then(r=>r.json()).then(d=>alert(JSON.stringify(d)))">Test Health</button>
</body>
</html>
`);
}
});
} catch (error) {
console.error('Test page error:', error);
res.status(500).send('Test page error: ' + error.message);
}
});
// 添加内置测试页面端点
app.get('/test', (req, res) => {
res.send(`
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>PPTist API 测试页面</title>
<style>
body { font-family: Arial, sans-serif; padding: 20px; background: #f5f5f5; }
.container { max-width: 800px; margin: 0 auto; background: white; padding: 30px; border-radius: 10px; }
h1 { color: #333; text-align: center; margin-bottom: 30px; }
.test-section { margin: 20px 0; padding: 15px; background: #f9f9f9; border-radius: 5px; }
.test-button { background: #5b9bd5; color: white; border: none; padding: 10px 20px; margin: 5px; border-radius: 5px; cursor: pointer; }
.test-button:hover { background: #4a8bc2; }
.result { margin: 10px 0; padding: 10px; background: #e8e8e8; border-radius: 3px; font-family: monospace; font-size: 12px; }
.success { background: #d4edda; color: #155724; }
.error { background: #f8d7da; color: #721c24; }
.login-form { margin: 15px 0; }
.login-form input { padding: 8px; margin: 5px; border: 1px solid #ddd; border-radius: 3px; }
</style>
</head>
<body>
<div class="container">
<h1>🚀 PPTist API 测试控制台</h1>
<div class="test-section">
<h3>🔗 基础连接测试</h3>
<button class="test-button" onclick="testHealth()">健康检查</button>
<button class="test-button" onclick="testGitHubStatus()">GitHub状态</button>
<button class="test-button" onclick="testGitHubConnection()">GitHub连接</button>
<div id="basic-results"></div>
</div>
<div class="test-section">
<h3>🔐 用户认证测试</h3>
<div class="login-form">
<input type="text" id="username" placeholder="用户名" value="PS01">
<input type="password" id="password" placeholder="密码" value="admin_cybercity2025">
<button class="test-button" onclick="testLogin()">登录</button>
<button class="test-button" onclick="clearToken()">清除Token</button>
</div>
<div id="token-info">当前Token: 未登录</div>
<button class="test-button" onclick="testVerifyToken()">验证Token</button>
<div id="auth-results"></div>
</div>
<div class="test-section">
<h3>📄 PPT管理测试</h3>
<button class="test-button" onclick="testPPTRoute()">PPT路由测试</button>
<button class="test-button" onclick="testPPTList()">获取PPT列表</button>
<button class="test-button" onclick="testCreatePPT()">创建PPT</button>
<button class="test-button" onclick="testSavePPT()">保存PPT</button>
<div id="ppt-results"></div>
</div>
<div class="test-section">
<h3>🌐 公共分享测试</h3>
<button class="test-button" onclick="testGenerateShareLink()">生成分享链接</button>
<div id="share-results"></div>
</div>
</div>
<script>
let currentToken = localStorage.getItem('pptist_test_token') || '';
let testPptId = '';
function updateTokenDisplay() {
const display = document.getElementById('token-info');
if (currentToken) {
display.textContent = '当前Token: ' + currentToken.substring(0, 20) + '...';
} else {
display.textContent = '当前Token: 未登录';
}
}
function clearToken() {
currentToken = '';
localStorage.removeItem('pptist_test_token');
updateTokenDisplay();
addResult('auth-results', '✅ Token已清除', 'success');
}
function addResult(containerId, message, type = '') {
const container = document.getElementById(containerId);
const div = document.createElement('div');
div.className = 'result ' + type;
div.textContent = '[' + new Date().toLocaleTimeString() + '] ' + message;
container.appendChild(div);
}
async function testHealth() {
try {
const response = await fetch('/api/health');
const data = await response.json();
addResult('basic-results', '✅ 健康检查成功: ' + JSON.stringify(data), 'success');
} catch (error) {
addResult('basic-results', '❌ 健康检查失败: ' + error.message, 'error');
}
}
async function testGitHubStatus() {
try {
const response = await fetch('/api/github/status');
const data = await response.json();
addResult('basic-results', '✅ GitHub状态: ' + JSON.stringify(data, null, 2), 'success');
} catch (error) {
addResult('basic-results', '❌ GitHub状态失败: ' + error.message, 'error');
}
}
async function testGitHubConnection() {
try {
const response = await fetch('/api/github/test');
const data = await response.json();
addResult('basic-results', '✅ GitHub连接测试: ' + JSON.stringify(data, null, 2), 'success');
} catch (error) {
addResult('basic-results', '❌ GitHub连接失败: ' + error.message, 'error');
}
}
async function testLogin() {
const username = document.getElementById('username').value;
const password = document.getElementById('password').value;
try {
const response = await fetch('/api/auth/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username, password })
});
const data = await response.json();
if (response.ok && data.token) {
currentToken = data.token;
localStorage.setItem('pptist_test_token', currentToken);
updateTokenDisplay();
addResult('auth-results', '✅ 登录成功: ' + data.user.username + ' (' + data.user.role + ')', 'success');
} else {
addResult('auth-results', '❌ 登录失败: ' + (data.error || '未知错误'), 'error');
}
} catch (error) {
addResult('auth-results', '❌ 登录请求失败: ' + error.message, 'error');
}
}
async function testVerifyToken() {
if (!currentToken) {
addResult('auth-results', '❌ 请先登录', 'error');
return;
}
try {
const response = await fetch('/api/auth/verify', {
headers: { 'Authorization': 'Bearer ' + currentToken }
});
const data = await response.json();
if (response.ok) {
addResult('auth-results', '✅ Token验证成功: ' + JSON.stringify(data), 'success');
} else {
addResult('auth-results', '❌ Token验证失败: ' + data.error, 'error');
}
} catch (error) {
addResult('auth-results', '❌ Token验证请求失败: ' + error.message, 'error');
}
}
async function testPPTRoute() {
try {
const response = await fetch('/api/ppt/test');
const data = await response.json();
addResult('ppt-results', '✅ PPT路由测试成功: ' + JSON.stringify(data), 'success');
} catch (error) {
addResult('ppt-results', '❌ PPT路由测试失败: ' + error.message, 'error');
}
}
async function testPPTList() {
if (!currentToken) {
addResult('ppt-results', '❌ 请先登录', 'error');
return;
}
try {
const response = await fetch('/api/ppt/list', {
headers: { 'Authorization': 'Bearer ' + currentToken }
});
const data = await response.json();
if (response.ok) {
addResult('ppt-results', '✅ PPT列表获取成功: ' + JSON.stringify(data), 'success');
} else {
addResult('ppt-results', '❌ PPT列表获取失败: ' + data.error, 'error');
}
} catch (error) {
addResult('ppt-results', '❌ PPT列表请求失败: ' + error.message, 'error');
}
}
async function testCreatePPT() {
if (!currentToken) {
addResult('ppt-results', '❌ 请先登录', 'error');
return;
}
try {
const response = await fetch('/api/ppt/create', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + currentToken
},
body: JSON.stringify({ title: '测试PPT - ' + new Date().toLocaleString() })
});
const data = await response.json();
if (response.ok && data.pptId) {
testPptId = data.pptId;
addResult('ppt-results', '✅ PPT创建成功: ' + testPptId, 'success');
} else {
addResult('ppt-results', '❌ PPT创建失败: ' + (data.error || '未知错误'), 'error');
}
} catch (error) {
addResult('ppt-results', '❌ PPT创建请求失败: ' + error.message, 'error');
}
}
async function testSavePPT() {
if (!currentToken) {
addResult('ppt-results', '❌ 请先登录', 'error');
return;
}
if (!testPptId) {
addResult('ppt-results', '❌ 请先创建PPT', 'error');
return;
}
const pptData = {
pptId: testPptId,
title: '测试PPT - 已保存',
slides: [{ id: 'slide-1', elements: [], background: { type: 'solid', color: '#ffffff' } }],
theme: { backgroundColor: '#ffffff', themeColor: '#5b9bd5' }
};
try {
const response = await fetch('/api/ppt/save', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + currentToken
},
body: JSON.stringify(pptData)
});
const data = await response.json();
if (response.ok) {
addResult('ppt-results', '✅ PPT保存成功: ' + JSON.stringify(data), 'success');
} else {
addResult('ppt-results', '❌ PPT保存失败: ' + (data.error || '未知错误'), 'error');
}
} catch (error) {
addResult('ppt-results', '❌ PPT保存请求失败: ' + error.message, 'error');
}
}
async function testGenerateShareLink() {
if (!testPptId) {
addResult('share-results', '❌ 请先创建并保存PPT', 'error');
return;
}
try {
const response = await fetch('/api/public/generate-share-link', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ userId: 'PS01', pptId: testPptId, slideIndex: 0 })
});
const data = await response.json();
if (response.ok) {
addResult('share-results', '✅ 分享链接生成成功: ' + JSON.stringify(data, null, 2), 'success');
} else {
addResult('share-results', '❌ 分享链接生成失败: ' + (data.error || '未知错误'), 'error');
}
} catch (error) {
addResult('share-results', '❌ 分享链接生成请求失败: ' + error.message, 'error');
}
}
// 初始化
updateTokenDisplay();
</script>
</body>
</html>
`);
});
// API路由
console.log('Registering API routes...');
// 健康检查 - 需要在其他路由之前
app.get('/api/health', (req, res) => {
res.json({ status: 'ok', timestamp: new Date().toISOString() });
});
// GitHub连接状态检查
app.get('/api/github/status', async (req, res) => {
try {
const { default: githubService } = await import('./services/githubService.js');
const validation = await githubService.validateConnection();
res.json({
github: validation,
environment: {
tokenConfigured: !!process.env.GITHUB_TOKEN,
tokenPreview: process.env.GITHUB_TOKEN ? `${process.env.GITHUB_TOKEN.substring(0, 8)}...` : 'Not set',
reposConfigured: !!process.env.GITHUB_REPOS,
reposList: process.env.GITHUB_REPOS ? process.env.GITHUB_REPOS.split(',') : [],
nodeEnv: process.env.NODE_ENV
}
});
} catch (error) {
res.status(500).json({
error: error.message,
stack: error.stack
});
}
});
// 添加GitHub测试路由
app.get('/api/github/test', async (req, res) => {
try {
console.log('=== GitHub Connection Test ===');
console.log('GITHUB_TOKEN exists:', !!process.env.GITHUB_TOKEN);
console.log('GITHUB_REPOS:', process.env.GITHUB_REPOS);
const { default: githubService } = await import('./services/githubService.js');
// 测试基本配置
const config = {
hasToken: !!githubService.token,
useMemoryStorage: githubService.useMemoryStorage,
repositories: githubService.repositories,
apiUrl: githubService.apiUrl
};
console.log('GitHub Service Config:', config);
// 如果有token,测试连接
let connectionTest = null;
if (githubService.token) {
console.log('Testing GitHub API connection...');
connectionTest = await githubService.validateConnection();
console.log('Connection test result:', connectionTest);
}
res.json({
timestamp: new Date().toISOString(),
config,
connectionTest,
environment: {
tokenLength: process.env.GITHUB_TOKEN ? process.env.GITHUB_TOKEN.length : 0,
nodeEnv: process.env.NODE_ENV
}
});
} catch (error) {
console.error('GitHub test error:', error);
res.status(500).json({
error: error.message,
stack: process.env.NODE_ENV === 'development' ? error.stack : undefined
});
}
});
// 添加路由注册日志
console.log('Importing route modules...');
console.log('Auth routes imported:', !!authRoutes);
console.log('PPT routes imported:', !!pptRoutes);
console.log('Public routes imported:', !!publicRoutes);
// 认证相关路由(不需要认证)
app.use('/api/auth', authRoutes);
// 公共访问路由(不需要认证)
app.use('/api/public', publicRoutes);
// 添加测试路由来验证 PPT 路由是否工作(不需要认证)
app.get('/api/ppt/test', (req, res) => {
res.json({ message: 'PPT routes are working', timestamp: new Date().toISOString() });
});
// PPT管理路由(需要认证)
app.use('/api/ppt', (req, res, next) => {
console.log(`PPT route accessed: ${req.method} ${req.path}`);
next();
}, authenticateToken, pptRoutes);
console.log('All routes registered successfully');
// 添加调试中间件 - 处理未匹配的API路由
app.use('/api/*', (req, res) => {
console.log(`Unmatched API route: ${req.method} ${req.path}`);
res.status(404).json({ error: 'API route not found', path: req.path });
});
// 前端路由处理 - 必须在API路由之后
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, '../../frontend/dist/index.html'));
});
// 错误处理中间件
app.use(errorHandler);
app.listen(PORT, '0.0.0.0', () => {
console.log(`Server is running on port ${PORT}`);
console.log(`Environment: ${process.env.NODE_ENV || 'development'}`);
}); |