-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
542 lines (475 loc) · 21.1 KB
/
Copy pathserver.js
File metadata and controls
542 lines (475 loc) · 21.1 KB
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
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
import express from 'express';
import multer from 'multer';
import cors from 'cors';
import path from 'path';
import fs from 'fs';
import { fileURLToPath } from 'url';
import sqlite3 from 'sqlite3';
import jwt from 'jsonwebtoken';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const app = express();
const port = 3001;
const JWT_SECRET = 'fawang_secret_key_123'; // In prod, use env var
app.use(cors());
app.use(express.json({ limit: '10mb' }));
// Ensure directories
const uploadsDir = path.join(__dirname, 'public', 'uploads');
if (!fs.existsSync(uploadsDir)) fs.mkdirSync(uploadsDir, { recursive: true });
app.use('/uploads', express.static(uploadsDir));
// --- DATABASE INIT ---
const db = new sqlite3.Database(path.join(__dirname, 'blog.db'));
db.serialize(() => {
// Users Table
db.run(`CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT UNIQUE,
password TEXT,
role TEXT DEFAULT 'user',
nickname TEXT,
avatarUrl TEXT,
bio TEXT,
status TEXT DEFAULT 'pending',
reg_ip TEXT,
reg_reason TEXT
)`);
// Ensure columns exist for older DBs
db.run(`ALTER TABLE users ADD COLUMN reg_ip TEXT`, (err) => {});
db.run(`ALTER TABLE users ADD COLUMN reg_reason TEXT`, (err) => {});
db.run(`ALTER TABLE users ADD COLUMN status TEXT DEFAULT 'pending'`, (err) => {});
// Articles Table
db.run(`CREATE TABLE IF NOT EXISTS articles (
id TEXT PRIMARY KEY,
title TEXT,
category TEXT,
tag TEXT,
thumbnailUrl TEXT,
excerpt TEXT,
content TEXT,
date TEXT,
views INTEGER DEFAULT 0
)`);
db.run(`ALTER TABLE articles ADD COLUMN views INTEGER DEFAULT 0`, (err) => {});
// Comments Table
db.run(`CREATE TABLE IF NOT EXISTS comments (
id INTEGER PRIMARY KEY AUTOINCREMENT,
article_id TEXT,
author TEXT,
avatarUrl TEXT,
content TEXT,
date TEXT,
FOREIGN KEY(article_id) REFERENCES articles(id)
)`);
// Config Table (Key-Value)
db.run(`CREATE TABLE IF NOT EXISTS config (
key TEXT PRIMARY KEY,
value TEXT
)`);
// Assets Table
db.run(`CREATE TABLE IF NOT EXISTS assets (
id INTEGER PRIMARY KEY AUTOINCREMENT,
url TEXT,
date TEXT
)`);
// Messages Table (Chat)
db.run(`CREATE TABLE IF NOT EXISTS messages (
id INTEGER PRIMARY KEY AUTOINCREMENT,
sender_id INTEGER,
receiver_id INTEGER, -- NULL for global chat
content TEXT,
timestamp TEXT,
type TEXT DEFAULT 'private', -- 'private' or 'global'
FOREIGN KEY(sender_id) REFERENCES users(id),
FOREIGN KEY(receiver_id) REFERENCES users(id)
)`);
// Seed default admin and config if empty
db.get("SELECT COUNT(*) as count FROM users", (err, row) => {
if (row && row.count === 0) {
db.run(`INSERT INTO users (username, password, role, nickname, avatarUrl, bio, status) VALUES ('admin', '123', 'admin', '法王', 'https://api.dicebear.com/7.x/adventurer/svg?seed=Fawang', '痴迷于安全技术的小白帽...', 'approved')`);
} else {
// Ensure admin is approved if already exists
db.run(`UPDATE users SET status = 'approved' WHERE username = 'admin'`);
}
});
db.get("SELECT COUNT(*) as count FROM config", (err, row) => {
if (row && row.count === 0) {
const defaultCfg = {
siteTitle: "法王 ‘s blog",
avatarUrl: "https://api.dicebear.com/7.x/adventurer/svg?seed=Fawang",
authorName: "法王",
authorRole: "[ WHITE_HAT_SEC ]",
authorDesc: "痴迷于安全技术的小白帽...\\n\\n\"孩儿立志出乡关,学不成名誓不还。\"",
announcement: "记录自己技术增长过程的博客~\\n孩儿立志出乡关,学不成名誓不还。",
bannerImageUrl: "",
bannerSubtitle: "Life is a coding, I will debug it.",
// About Page Configs
about_banner_1_img: "/uploads/about_banner_1.png",
about_banner_2_img: "/uploads/about_banner_2.png",
about_banner_3_img: "/uploads/about_banner_3.png",
about_mascot: "/uploads/mascot.png",
about_identity_title: "你好,我是 Pakchuii",
about_identity_desc: "痴迷于安全技术的小白帽...\"孩儿立志出乡关,学不成名誓不还。\"",
about_profile_name: "Pakchuii",
about_profile_bio: "痴迷于安全技术的小白帽...\\n\"孩儿立志出乡关,学不成名誓不还...\"",
about_carousel_1_img: "/uploads/carousel_1.png",
about_carousel_1_title: "PROJECT: NEURAL_NET_v2",
about_carousel_1_desc: "基于神经网络的实时数据可视化阵列。采用了最新的高密度点云渲染技术。",
about_carousel_2_img: "/uploads/carousel_2.png",
about_carousel_2_title: "CORE_SYNC // 核心同步",
about_carousel_2_desc: "系统多维度数据流同步中心。确保所有子系统在毫秒级延迟内达成一致。",
about_carousel_3_img: "/uploads/about_banner.png",
about_carousel_3_title: "DASHBOARD_v3 // 视角切换",
about_carousel_3_desc: "正在全屏扫描系统架构... 身份识别正常。欢迎回来,Pakchuii。",
about_visual_1_img: "/uploads/about_card_1.png",
about_visual_2_img: "/uploads/about_card_2.png",
home_transition_bg: "",
faviconUrl: ""
};
for (const [k, v] of Object.entries(defaultCfg)) {
db.run(`INSERT INTO config (key, value) VALUES (?, ?)`, [k, v]);
}
}
});
});
// --- MIDDLEWARE ---
const authenticate = (req, res, next) => {
const token = req.headers.authorization?.split(' ')[1];
if (!token) return res.status(401).json({ error: 'Unauthorized' });
jwt.verify(token, JWT_SECRET, (err, decoded) => {
if (err) return res.status(401).json({ error: 'Invalid token' });
req.user = decoded;
next();
});
};
// --- AUTH API ---
app.post('/api/auth/register', (req, res) => {
const { username, password, reason } = req.body;
if (!username || !password) return res.status(400).json({ error: 'Missing fields' });
const ip = req.headers['x-forwarded-for'] || req.socket.remoteAddress;
db.get("SELECT COUNT(*) as count FROM users WHERE reg_ip = ? AND status = 'pending'", [ip], (err, row) => {
if (row && row.count > 0) return res.status(429).json({ error: '您已有账号正在审核中,请勿重复注册。' });
db.get("SELECT COUNT(*) as count FROM users", (err, row) => {
const status = (row && row.count === 0) ? 'approved' : 'pending';
const role = (row && row.count === 0) ? 'admin' : 'user';
const randomId = Math.floor(100000 + Math.random() * 900000);
db.run(`INSERT INTO users (id, username, password, role, status, reg_ip, reg_reason) VALUES (?, ?, ?, ?, ?, ?, ?)`,
[randomId, username, password, role, status, ip, reason || ''], function(err) {
if (err) return res.status(400).json({ error: '用户名已存在或 ID 冲突,请重试。' });
res.json({ success: true, status, id: randomId });
});
});
});
});
app.post('/api/auth/login', (req, res) => {
const { username, password } = req.body;
db.get(`SELECT * FROM users WHERE username = ? AND password = ?`, [username, password], (err, user) => {
if (!user) return res.status(401).json({ error: 'Invalid credentials' });
if (user.status !== 'approved') return res.status(403).json({ error: 'Account pending approval' });
const token = jwt.sign({ id: user.id, username: user.username, role: user.role }, JWT_SECRET, { expiresIn: '7d' });
res.json({ success: true, token, user: { id: user.id, username: user.username, role: user.role, nickname: user.nickname, avatarUrl: user.avatarUrl, bio: user.bio } });
});
});
app.get('/api/users/profile', authenticate, (req, res) => {
db.get(`SELECT id, username, role, nickname, avatarUrl, bio FROM users WHERE id = ?`, [req.user.id], (err, user) => {
if (err || !user) return res.status(404).json({ error: 'User not found' });
res.json(user);
});
});
// --- ADMIN USER MANAGEMENT ---
app.get('/api/admin/users', authenticate, (req, res) => {
if (req.user.role !== 'admin') return res.status(403).json({ error: 'Forbidden' });
db.all(`SELECT id, username, role, nickname, avatarUrl, bio, status, reg_ip, reg_reason FROM users`, (err, users) => {
if (err) return res.status(500).json({ error: err.message });
res.json(users);
});
});
app.put('/api/admin/users/:id/status', authenticate, (req, res) => {
if (req.user.role !== 'admin') return res.status(403).json({ error: 'Forbidden' });
const { status } = req.body;
db.run(`UPDATE users SET status = ? WHERE id = ?`, [status, req.params.id], (err) => {
if (err) return res.status(500).json({ error: err.message });
res.json({ success: true });
});
});
app.delete('/api/admin/users/:id', authenticate, (req, res) => {
if (req.user.role !== 'admin') return res.status(403).json({ error: 'Forbidden' });
// 1. Find user to get avatar path
db.get(`SELECT avatarUrl FROM users WHERE id = ?`, [req.params.id], (err, user) => {
if (user && user.avatarUrl && user.avatarUrl.includes('/uploads/')) {
const relativePath = user.avatarUrl.split('/uploads/')[1];
const filePath = path.join(uploadsDir, relativePath);
if (fs.existsSync(filePath)) {
try { fs.unlinkSync(filePath); } catch(e) {}
}
}
// 2. Delete from DB
db.run(`DELETE FROM users WHERE id = ?`, [req.params.id], (err) => {
if (err) return res.status(500).json({ error: err.message });
res.json({ success: true });
});
});
});
app.put('/api/users/profile', authenticate, (req, res) => {
const { nickname, avatarUrl, bio } = req.body;
// 1. Get current avatar to check for cleanup
db.get(`SELECT avatarUrl FROM users WHERE username = ?`, [req.user.username], (err, row) => {
const oldAvatar = row ? row.avatarUrl : null;
// 2. If avatar changed and old one was local upload, delete it
if (oldAvatar && oldAvatar !== avatarUrl && oldAvatar.includes('/uploads/')) {
const parts = oldAvatar.split('/uploads/');
const relativePath = parts[parts.length - 1];
const filePath = path.join(uploadsDir, relativePath);
if (fs.existsSync(filePath)) {
try { fs.unlinkSync(filePath); } catch (e) { console.error("Failed to delete old avatar:", e); }
}
}
// 3. Update DB
db.run(`UPDATE users SET nickname = ?, avatarUrl = ?, bio = ? WHERE username = ?`,
[nickname, avatarUrl, bio, req.user.username], (err) => {
if (err) return res.status(500).json({ error: err.message });
res.json({ success: true });
});
});
});
// --- CONFIG API ---
app.get('/api/config', (req, res) => {
db.all(`SELECT * FROM config`, (err, rows) => {
const config = {};
rows.forEach(r => config[r.key] = r.value);
res.json(config);
});
});
app.post('/api/config', authenticate, (req, res) => {
if (req.user.role !== 'admin') return res.status(403).json({ error: 'Forbidden' });
const config = req.body;
db.serialize(() => {
const stmt = db.prepare(`REPLACE INTO config (key, value) VALUES (?, ?)`);
for (const [k, v] of Object.entries(config)) stmt.run(k, v);
stmt.finalize();
});
res.json({ success: true });
});
// --- ARTICLES API ---
app.get('/api/articles', (req, res) => {
db.all(`SELECT * FROM articles ORDER BY date DESC`, (err, articles) => {
if (err) return res.status(500).json({ error: err.message });
db.all(`SELECT * FROM comments`, (err, comments) => {
const articlesWithComments = articles.map((a) => ({
...a,
comments: comments.filter((c) => c.article_id === a.id)
}));
res.json(articlesWithComments);
});
});
});
app.post('/api/articles', authenticate, (req, res) => {
if (req.user.role !== 'admin') return res.status(403).json({ error: 'Forbidden' });
const { id, title, category, tag, thumbnailUrl, excerpt, content, date } = req.body;
db.run(`REPLACE INTO articles (id, title, category, tag, thumbnailUrl, excerpt, content, date) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
[id, title, category, tag, thumbnailUrl, excerpt, content, date], (err) => {
if (err) return res.status(500).json({ error: err.message });
res.json({ success: true });
});
});
app.delete('/api/articles/:id', authenticate, (req, res) => {
if (req.user.role !== 'admin') return res.status(403).json({ error: 'Forbidden' });
db.run(`DELETE FROM articles WHERE id = ?`, [req.params.id], (err) => {
if (err) return res.status(500).json({ error: err.message });
db.run(`DELETE FROM comments WHERE article_id = ?`, [req.params.id]); // Cascade delete
res.json({ success: true });
});
});
app.post('/api/articles/:id/comments', authenticate, (req, res) => {
const { author, avatarUrl, content, date } = req.body;
const commentDate = date || new Date().toISOString();
db.run(`INSERT INTO comments (article_id, author, avatarUrl, content, date) VALUES (?, ?, ?, ?, ?)`,
[req.params.id, author, avatarUrl, content, commentDate], (err) => {
if (err) return res.status(500).json({ error: err.message });
res.json({ success: true });
});
});
app.post('/api/articles/:id/view', (req, res) => {
db.run(`UPDATE articles SET views = views + 1 WHERE id = ?`, [req.params.id], (err) => {
if (err) return res.status(500).json({ error: err.message });
res.json({ success: true });
});
});
// --- ASSETS API ---
const assetsDir = path.join(uploadsDir, 'assets');
const usersDir = path.join(uploadsDir, 'users');
if (!fs.existsSync(assetsDir)) fs.mkdirSync(assetsDir, { recursive: true });
if (!fs.existsSync(usersDir)) fs.mkdirSync(usersDir, { recursive: true });
const upload = multer({
storage: multer.diskStorage({
destination: (req, file, cb) => {
const type = req.query.type;
if (type === 'user') cb(null, usersDir);
else cb(null, assetsDir);
},
filename: (req, file, cb) => {
// Sanitize: replace spaces and problematic chars with underscores
const safeName = file.originalname.replace(/\s+/g, '_').replace(/[\[\]]/g, '');
cb(null, Date.now() + '-' + safeName);
}
})
});
app.post('/api/upload', upload.single('file'), (req, res) => {
if (!req.file) return res.status(400).json({ error: 'No file' });
const host = req.get('host') || `localhost:${port}`;
const protocol = req.protocol === 'https' || req.headers['x-forwarded-proto'] === 'https' ? 'https' : 'http';
const type = req.query.type;
const folder = type === 'user' ? 'users' : 'assets';
// Use relative path to avoid localhost/CORS issues
const encodedFilename = encodeURIComponent(req.file.filename);
const fileUrl = `/uploads/${folder}/${encodedFilename}`;
if (type !== 'user') {
db.run(`INSERT INTO assets (url, date) VALUES (?, ?)`, [fileUrl, new Date().toISOString()]);
}
res.json({ success: true, url: fileUrl });
});
app.get('/api/assets', (req, res) => {
const host = req.get('host') || `localhost:${port}`;
const protocol = req.protocol === 'https' || req.headers['x-forwarded-proto'] === 'https' ? 'https' : 'http';
fs.readdir(assetsDir, (err, files) => {
if (err) return res.status(500).json({ error: 'Failed to read directory' });
// Sort files by modified time descending
const sortedFiles = files
.map(fileName => ({
name: fileName,
time: fs.statSync(path.join(assetsDir, fileName)).mtime.getTime()
}))
.sort((a, b) => b.time - a.time)
.map(file => `/uploads/assets/${file.name}`);
res.json(sortedFiles);
});
});
app.delete('/api/assets/:filename', authenticate, (req, res) => {
if (req.user.role !== 'admin') return res.status(403).json({ error: 'Forbidden' });
const filename = req.params.filename;
// Basic security check to prevent directory traversal
if (filename.includes('..') || filename.includes('/') || filename.includes('\\')) {
return res.status(400).json({ error: 'Invalid filename' });
}
const filePath = path.join(assetsDir, filename);
if (fs.existsSync(filePath)) {
fs.unlinkSync(filePath);
res.json({ success: true });
} else {
res.status(404).json({ error: 'File not found' });
}
});
// --- CHAT API ---
app.get('/api/chat/users', authenticate, (req, res) => {
db.all(`SELECT id, username, nickname, avatarUrl, bio FROM users WHERE status = 'approved' AND id != ?`, [req.user.id], (err, users) => {
if (err) return res.status(500).json({ error: err.message });
res.json(users);
});
});
app.get('/api/chat/global', authenticate, (req, res) => {
db.all(`SELECT m.*, u.username as sender_name, u.avatarUrl as sender_avatar, u.nickname as sender_nickname
FROM messages m
JOIN users u ON m.sender_id = u.id
WHERE m.type = 'global'
ORDER BY m.timestamp ASC LIMIT 100`, (err, rows) => {
if (err) return res.status(500).json({ error: err.message });
res.json(rows);
});
});
app.post('/api/chat/global', authenticate, (req, res) => {
const { content } = req.body;
if (!content) return res.status(400).json({ error: 'Empty content' });
const timestamp = new Date().toISOString();
db.run(`INSERT INTO messages (sender_id, content, timestamp, type) VALUES (?, ?, ?, 'global')`,
[req.user.id, content, timestamp], (err) => {
if (err) return res.status(500).json({ error: err.message });
res.json({ success: true });
});
});
app.get('/api/chat/private/:userId', authenticate, (req, res) => {
const targetId = req.params.userId;
db.all(`SELECT m.*, u.username as sender_name, u.avatarUrl as sender_avatar, u.nickname as sender_nickname
FROM messages m
JOIN users u ON m.sender_id = u.id
WHERE m.type = 'private' AND (
(m.sender_id = ? AND m.receiver_id = ?) OR (m.sender_id = ? AND m.receiver_id = ?)
)
ORDER BY m.timestamp ASC`, [req.user.id, targetId, targetId, req.user.id], (err, rows) => {
if (err) return res.status(500).json({ error: err.message });
res.json(rows);
});
});
app.post('/api/chat/private/:userId', authenticate, (req, res) => {
const targetId = req.params.userId;
const { content } = req.body;
if (!content) return res.status(400).json({ error: 'Empty content' });
const timestamp = new Date().toISOString();
db.run(`INSERT INTO messages (sender_id, receiver_id, content, timestamp, type) VALUES (?, ?, ?, ?, 'private')`,
[req.user.id, targetId, content, timestamp], (err) => {
if (err) return res.status(500).json({ error: err.message });
res.json({ success: true });
});
});
app.get('/api/chat/updates', authenticate, (req, res) => {
const since = req.query.since || '1970-01-01T00:00:00Z';
const results = { globalCount: 0, privateCounts: {} };
db.serialize(() => {
// Count global (exclude self)
db.get(`SELECT COUNT(*) as count FROM messages WHERE type = 'global' AND timestamp > ? AND sender_id != ?`, [since, req.user.id], (err, row) => {
if (row) results.globalCount = row.count;
// Count private sent to me
db.all(`SELECT sender_id, COUNT(*) as count FROM messages
WHERE type = 'private' AND receiver_id = ? AND timestamp > ?
GROUP BY sender_id`, [req.user.id, since], (err, rows) => {
if (rows) {
rows.forEach(r => results.privateCounts[r.sender_id] = r.count);
}
res.json(results);
});
});
});
});
app.delete('/api/admin/chat', authenticate, (req, res) => {
if (req.user.role !== 'admin') return res.status(403).json({ error: 'Forbidden' });
const { type, userId, targetUserId, startDate, endDate } = req.query;
let query = `DELETE FROM messages WHERE type = ?`;
let params = [type === 'global' ? 'global' : 'private'];
if (type === 'global') {
if (startDate) { query += ` AND timestamp >= ?`; params.push(startDate); }
if (endDate) { query += ` AND timestamp <= ?`; params.push(endDate); }
} else if (type === 'private') {
if (userId && targetUserId) {
query += ` AND ((sender_id = ? AND receiver_id = ?) OR (sender_id = ? AND receiver_id = ?))`;
params.push(userId, targetUserId, targetUserId, userId);
} else if (userId) {
query += ` AND (sender_id = ? OR receiver_id = ?)`;
params.push(userId, userId);
}
if (startDate) { query += ` AND timestamp >= ?`; params.push(startDate); }
if (endDate) { query += ` AND timestamp <= ?`; params.push(endDate); }
} else if (type === 'all_private') {
query = `DELETE FROM messages WHERE type = 'private'`;
params = [];
if (startDate) { query += ` AND timestamp >= ?`; params.push(startDate); }
if (endDate) { query += ` AND timestamp <= ?`; params.push(endDate); }
}
db.run(query, params, function(err) {
if (err) return res.status(500).json({ error: err.message });
res.json({ success: true, count: this.changes, message: `${this.changes} messages deleted` });
});
});
// --- SERVE FRONTEND ---
const distDir = path.join(__dirname, 'dist');
if (fs.existsSync(distDir)) {
app.use(express.static(distDir));
// SPA Fallback: Handle all other GET requests by serving index.html
app.use((req, res, next) => {
if (req.method === 'GET' && !req.path.startsWith('/api')) {
res.sendFile(path.join(distDir, 'index.html'));
} else {
next();
}
});
}
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});