server.js 6.4 KB

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