server.js 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  1. const express = require('express');
  2. const fs = require('fs').promises;
  3. const path = require('path');
  4. const bodyParser = require('body-parser');
  5. const session = require('express-session');
  6. const bcrypt = require('bcrypt');
  7. const crypto = require('crypto');
  8. const logger = require('morgan'); // 引入 morgan 作为日志工具
  9. const app = express();
  10. app.use(express.json());
  11. app.use(express.static('web'));
  12. app.use(bodyParser.urlencoded({ extended: true }));
  13. app.use(session({
  14. secret: 'OhTq3faqSKoxbV%NJV',
  15. resave: false,
  16. saveUninitialized: true,
  17. cookie: { secure: false } // 设置为true如果使用HTTPS
  18. }));
  19. app.use(logger('dev')); // 使用 morgan 记录请求日志
  20. app.get('/admin', (req, res) => {
  21. res.sendFile(path.join(__dirname, 'web', 'admin.html'));
  22. });
  23. const CONFIG_FILE = path.join(__dirname, 'config.json');
  24. const USERS_FILE = path.join(__dirname, 'users.json');
  25. // 读取配置
  26. async function readConfig() {
  27. try {
  28. const data = await fs.readFile(CONFIG_FILE, 'utf8');
  29. // 确保 data 不为空或不完整
  30. if (!data.trim()) {
  31. console.warn('Config file is empty, returning default config');
  32. return {
  33. logo: '',
  34. menuItems: [],
  35. adImages: []
  36. };
  37. }
  38. console.log('Config read successfully');
  39. return JSON.parse(data);
  40. } catch (error) {
  41. console.error('Failed to read config:', error);
  42. if (error.code === 'ENOENT') {
  43. return {
  44. logo: '',
  45. menuItems: [],
  46. adImages: []
  47. };
  48. }
  49. throw error;
  50. }
  51. }
  52. // 写入配置
  53. async function writeConfig(config) {
  54. try {
  55. await fs.writeFile(CONFIG_FILE, JSON.stringify(config, null, 2), 'utf8');
  56. console.log('Config saved successfully');
  57. } catch (error) {
  58. console.error('Failed to save config:', error);
  59. throw error;
  60. }
  61. }
  62. // 读取用户
  63. async function readUsers() {
  64. try {
  65. const data = await fs.readFile(USERS_FILE, 'utf8');
  66. return JSON.parse(data);
  67. } catch (error) {
  68. if (error.code === 'ENOENT') {
  69. console.warn('Users file does not exist, creating default user');
  70. const defaultUser = { username: 'root', password: bcrypt.hashSync('admin', 10) };
  71. await writeUsers([defaultUser]);
  72. return { users: [defaultUser] };
  73. }
  74. throw error;
  75. }
  76. }
  77. // 写入用户
  78. async function writeUsers(users) {
  79. await fs.writeFile(USERS_FILE, JSON.stringify({ users }, null, 2), 'utf8');
  80. }
  81. // 登录验证
  82. app.post('/api/login', async (req, res) => {
  83. const { username, password, captcha } = req.body;
  84. console.log(`Received login request for user: ${username}`); // 打印登录请求的用户名
  85. if (req.session.captcha !== parseInt(captcha)) {
  86. console.log(`Captcha verification failed for user: ${username}`); // 打印验证码验证失败
  87. return res.status(401).json({ error: '验证码错误' });
  88. }
  89. const users = await readUsers();
  90. const user = users.users.find(u => u.username === username);
  91. if (!user) {
  92. console.log(`User ${username} not found`); // 打印用户未找到
  93. return res.status(401).json({ error: '用户名或密码错误' });
  94. }
  95. console.log(`User ${username} found, comparing passwords`); // 打印用户找到,开始比较密码
  96. if (bcrypt.compareSync(password, user.password)) {
  97. console.log(`User ${username} logged in successfully`); // 打印登录成功
  98. req.session.user = user;
  99. res.json({ success: true });
  100. } else {
  101. console.log(`Login failed for user: ${username}, password mismatch`); // 打印密码不匹配
  102. res.status(401).json({ error: '用户名或密码错误' });
  103. }
  104. });
  105. // 修改密码
  106. app.post('/api/change-password', async (req, res) => {
  107. if (!req.session.user) {
  108. return res.status(401).json({ error: 'Not logged in' });
  109. }
  110. const { currentPassword, newPassword } = req.body;
  111. if (!/^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,16}$/.test(newPassword)) {
  112. return res.status(400).json({ error: 'Password must be 8-16 characters long and contain at least one letter and one number' });
  113. }
  114. const users = await readUsers();
  115. const user = users.users.find(u => u.username === req.session.user.username);
  116. if (user && bcrypt.compareSync(currentPassword, user.password)) {
  117. user.password = bcrypt.hashSync(newPassword, 10);
  118. await writeUsers(users.users);
  119. res.json({ success: true });
  120. } else {
  121. res.status(401).json({ error: 'Invalid current password' });
  122. }
  123. });
  124. // 需要登录验证的中间件
  125. function requireLogin(req, res, next) {
  126. if (req.session.user) {
  127. next();
  128. } else {
  129. res.status(401).json({ error: 'Not logged in' });
  130. }
  131. }
  132. // API 端点:获取配置
  133. app.get('/api/config', async (req, res) => {
  134. try {
  135. const config = await readConfig();
  136. res.json(config);
  137. } catch (error) {
  138. res.status(500).json({ error: 'Failed to read config' });
  139. }
  140. });
  141. // API 端点:保存配置
  142. app.post('/api/config', requireLogin, async (req, res) => {
  143. try {
  144. const currentConfig = await readConfig();
  145. const newConfig = { ...currentConfig, ...req.body };
  146. await writeConfig(newConfig);
  147. res.json({ success: true });
  148. } catch (error) {
  149. res.status(500).json({ error: 'Failed to save config' });
  150. }
  151. });
  152. // API 端点:检查会话状态
  153. app.get('/api/check-session', (req, res) => {
  154. if (req.session.user) {
  155. res.json({ success: true });
  156. } else {
  157. res.status(401).json({ error: 'Not logged in' });
  158. }
  159. });
  160. // API 端点:生成验证码
  161. app.get('/api/captcha', (req, res) => {
  162. const num1 = Math.floor(Math.random() * 10);
  163. const num2 = Math.floor(Math.random() * 10);
  164. const captcha = `${num1} + ${num2} = ?`;
  165. req.session.captcha = num1 + num2;
  166. res.json({ captcha });
  167. });
  168. // 启动服务器
  169. const PORT = process.env.PORT || 3000;
  170. app.listen(PORT, () => {
  171. console.log(`Server is running on http://localhost:${PORT}`);
  172. });