server.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  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. const DOCUMENTATION_DIR = path.join(__dirname, 'documentation');
  41. const DOCUMENTATION_FILE = path.join(__dirname, 'documentation.md');
  42. // 读取配置
  43. async function readConfig() {
  44. try {
  45. const data = await fs.readFile(CONFIG_FILE, 'utf8');
  46. // 确保 data 不为空或不完整
  47. if (!data.trim()) {
  48. console.warn('Config file is empty, returning default config');
  49. return {
  50. logo: '',
  51. menuItems: [],
  52. adImages: []
  53. };
  54. }
  55. console.log('Config read successfully');
  56. return JSON.parse(data);
  57. } catch (error) {
  58. console.error('Failed to read config:', error);
  59. if (error.code === 'ENOENT') {
  60. return {
  61. logo: '',
  62. menuItems: [],
  63. adImages: []
  64. };
  65. }
  66. throw error;
  67. }
  68. }
  69. // 写入配置
  70. async function writeConfig(config) {
  71. try {
  72. await fs.writeFile(CONFIG_FILE, JSON.stringify(config, null, 2), 'utf8');
  73. console.log('Config saved successfully');
  74. } catch (error) {
  75. console.error('Failed to save config:', error);
  76. throw error;
  77. }
  78. }
  79. // 读取用户
  80. async function readUsers() {
  81. try {
  82. const data = await fs.readFile(USERS_FILE, 'utf8');
  83. return JSON.parse(data);
  84. } catch (error) {
  85. if (error.code === 'ENOENT') {
  86. console.warn('Users file does not exist, creating default user');
  87. const defaultUser = { username: 'root', password: bcrypt.hashSync('admin', 10) };
  88. await writeUsers([defaultUser]);
  89. return { users: [defaultUser] };
  90. }
  91. throw error;
  92. }
  93. }
  94. // 写入用户
  95. async function writeUsers(users) {
  96. await fs.writeFile(USERS_FILE, JSON.stringify({ users }, null, 2), 'utf8');
  97. }
  98. // 确保 documentation 目录存在
  99. async function ensureDocumentationDir() {
  100. try {
  101. await fs.access(DOCUMENTATION_DIR);
  102. } catch (error) {
  103. if (error.code === 'ENOENT') {
  104. await fs.mkdir(DOCUMENTATION_DIR);
  105. } else {
  106. throw error;
  107. }
  108. }
  109. }
  110. // 读取文档
  111. async function readDocumentation() {
  112. try {
  113. await ensureDocumentationDir();
  114. const files = await fs.readdir(DOCUMENTATION_DIR);
  115. console.log('Files in documentation directory:', files); // 添加日志
  116. const documents = await Promise.all(files.map(async file => {
  117. const filePath = path.join(DOCUMENTATION_DIR, file);
  118. const content = await fs.readFile(filePath, 'utf8');
  119. const doc = JSON.parse(content);
  120. return {
  121. id: path.parse(file).name,
  122. title: doc.title,
  123. content: doc.content,
  124. published: doc.published
  125. };
  126. }));
  127. const publishedDocuments = documents.filter(doc => doc.published);
  128. console.log('Published documents:', publishedDocuments); // 添加日志
  129. return publishedDocuments;
  130. } catch (error) {
  131. console.error('Error reading documentation:', error);
  132. throw error;
  133. }
  134. }
  135. // 写入文档
  136. async function writeDocumentation(content) {
  137. await fs.writeFile(DOCUMENTATION_FILE, content, 'utf8');
  138. }
  139. // 登录验证
  140. app.post('/api/login', async (req, res) => {
  141. const { username, password, captcha } = req.body;
  142. console.log(`Received login request for user: ${username}`); // 打印登录请求的用户名
  143. if (req.session.captcha !== parseInt(captcha)) {
  144. console.log(`Captcha verification failed for user: ${username}`); // 打印验证码验证失败
  145. return res.status(401).json({ error: '验证码错误' });
  146. }
  147. const users = await readUsers();
  148. const user = users.users.find(u => u.username === username);
  149. if (!user) {
  150. console.log(`User ${username} not found`); // 打印用户未找到
  151. return res.status(401).json({ error: '用户名或密码错误' });
  152. }
  153. console.log(`User ${username} found, comparing passwords`); // 打印用户找到,开始比较密码
  154. if (bcrypt.compareSync(password, user.password)) {
  155. console.log(`User ${username} logged in successfully`); // 打印登录成功
  156. req.session.user = user;
  157. res.json({ success: true });
  158. } else {
  159. console.log(`Login failed for user: ${username}, password mismatch`); // 打印密码不匹配
  160. res.status(401).json({ error: '用户名或密码错误' });
  161. }
  162. });
  163. // 修改密码
  164. app.post('/api/change-password', async (req, res) => {
  165. if (!req.session.user) {
  166. return res.status(401).json({ error: 'Not logged in' });
  167. }
  168. const { currentPassword, newPassword } = req.body;
  169. const passwordRegex = /^(?=.*[A-Za-z])(?=.*\d)(?=.*[.,\-_+=()[\]{}|\\;:'"<>?/@$!%*#?&])[A-Za-z\d.,\-_+=()[\]{}|\\;:'"<>?/@$!%*#?&]{8,16}$/;
  170. if (!passwordRegex.test(newPassword)) {
  171. 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' });
  172. }
  173. const users = await readUsers();
  174. const user = users.users.find(u => u.username === req.session.user.username);
  175. if (user && bcrypt.compareSync(currentPassword, user.password)) {
  176. user.password = bcrypt.hashSync(newPassword, 10);
  177. await writeUsers(users.users);
  178. res.json({ success: true });
  179. } else {
  180. res.status(401).json({ error: 'Invalid current password' });
  181. }
  182. });
  183. // 需要登录验证的中间件
  184. function requireLogin(req, res, next) {
  185. if (req.session.user) {
  186. next();
  187. } else {
  188. res.status(401).json({ error: 'Not logged in' });
  189. }
  190. }
  191. // API 端点:获取配置
  192. app.get('/api/config', async (req, res) => {
  193. try {
  194. const config = await readConfig();
  195. res.json(config);
  196. } catch (error) {
  197. res.status(500).json({ error: 'Failed to read config' });
  198. }
  199. });
  200. // API 端点:保存配置
  201. app.post('/api/config', requireLogin, async (req, res) => {
  202. try {
  203. const currentConfig = await readConfig();
  204. const newConfig = { ...currentConfig, ...req.body };
  205. await writeConfig(newConfig);
  206. res.json({ success: true });
  207. } catch (error) {
  208. res.status(500).json({ error: 'Failed to save config' });
  209. }
  210. });
  211. // API 端点:检查会话状态
  212. app.get('/api/check-session', (req, res) => {
  213. if (req.session.user) {
  214. res.json({ success: true });
  215. } else {
  216. res.status(401).json({ error: 'Not logged in' });
  217. }
  218. });
  219. // API 端点:生成验证码
  220. app.get('/api/captcha', (req, res) => {
  221. const num1 = Math.floor(Math.random() * 10);
  222. const num2 = Math.floor(Math.random() * 10);
  223. const captcha = `${num1} + ${num2} = ?`;
  224. req.session.captcha = num1 + num2;
  225. res.json({ captcha });
  226. });
  227. // API端点:获取文档列表
  228. app.get('/api/documentation-list', requireLogin, async (req, res) => {
  229. try {
  230. const files = await fs.readdir(DOCUMENTATION_DIR);
  231. const documents = await Promise.all(files.map(async file => {
  232. const content = await fs.readFile(path.join(DOCUMENTATION_DIR, file), 'utf8');
  233. const doc = JSON.parse(content);
  234. return { id: path.parse(file).name, ...doc };
  235. }));
  236. res.json(documents);
  237. } catch (error) {
  238. res.status(500).json({ error: '读取文档列表失败' });
  239. }
  240. });
  241. // API端点:保存文档
  242. app.post('/api/documentation', requireLogin, async (req, res) => {
  243. try {
  244. const { id, title, content } = req.body;
  245. const docId = id || Date.now().toString();
  246. const docPath = path.join(DOCUMENTATION_DIR, `${docId}.json`);
  247. await fs.writeFile(docPath, JSON.stringify({ title, content, published: false }));
  248. res.json({ success: true });
  249. } catch (error) {
  250. res.status(500).json({ error: '保存文档失败' });
  251. }
  252. });
  253. // API端点:删除文档
  254. app.delete('/api/documentation/:id', requireLogin, async (req, res) => {
  255. try {
  256. const docPath = path.join(DOCUMENTATION_DIR, `${req.params.id}.json`);
  257. await fs.unlink(docPath);
  258. res.json({ success: true });
  259. } catch (error) {
  260. res.status(500).json({ error: '删除文档失败' });
  261. }
  262. });
  263. // API端点:切换文档发布状态
  264. app.post('/api/documentation/:id/toggle-publish', requireLogin, async (req, res) => {
  265. try {
  266. const docPath = path.join(DOCUMENTATION_DIR, `${req.params.id}.json`);
  267. const content = await fs.readFile(docPath, 'utf8');
  268. const doc = JSON.parse(content);
  269. doc.published = !doc.published;
  270. await fs.writeFile(docPath, JSON.stringify(doc));
  271. res.json({ success: true });
  272. } catch (error) {
  273. res.status(500).json({ error: '更改发布状态失败' });
  274. }
  275. });
  276. // API端点:获取文档
  277. app.get('/api/documentation', async (req, res) => {
  278. try {
  279. const documents = await readDocumentation();
  280. console.log('Sending documents:', documents); // 添加日志
  281. res.json(documents);
  282. } catch (error) {
  283. console.error('Error in /api/documentation:', error);
  284. res.status(500).json({ error: '读取文档失败', details: error.message });
  285. }
  286. });
  287. // API端点:保存文档
  288. app.post('/api/documentation', requireLogin, async (req, res) => {
  289. try {
  290. const { content } = req.body;
  291. await writeDocumentation(content);
  292. res.json({ success: true });
  293. } catch (error) {
  294. res.status(500).json({ error: '保存文档失败' });
  295. }
  296. });
  297. // 获取文档列表函数
  298. async function getDocumentList() {
  299. try {
  300. await ensureDocumentationDir();
  301. const files = await fs.readdir(DOCUMENTATION_DIR);
  302. console.log('Files in documentation directory:', files);
  303. const documents = await Promise.all(files.map(async file => {
  304. try {
  305. const filePath = path.join(DOCUMENTATION_DIR, file);
  306. const content = await fs.readFile(filePath, 'utf8');
  307. return {
  308. id: path.parse(file).name,
  309. title: path.parse(file).name, // 使用文件名作为标题
  310. content: content,
  311. published: true // 假设所有文档都是已发布的
  312. };
  313. } catch (fileError) {
  314. console.error(`Error reading file ${file}:`, fileError);
  315. return null;
  316. }
  317. }));
  318. const validDocuments = documents.filter(doc => doc !== null);
  319. console.log('Valid documents:', validDocuments);
  320. return validDocuments;
  321. } catch (error) {
  322. console.error('Error reading document list:', error);
  323. throw error; // 重新抛出错误,让上层函数处理
  324. }
  325. }
  326. app.get('/api/documentation-list', async (req, res) => {
  327. try {
  328. const documents = await getDocumentList();
  329. res.json(documents);
  330. } catch (error) {
  331. console.error('Error in /api/documentation-list:', error);
  332. res.status(500).json({
  333. error: '读取文档列表失败',
  334. details: error.message,
  335. stack: error.stack
  336. });
  337. }
  338. });
  339. app.get('/api/documentation/:id', async (req, res) => {
  340. try {
  341. const docId = req.params.id;
  342. console.log('Fetching document with id:', docId); // 添加日志
  343. const docPath = path.join(DOCUMENTATION_DIR, `${docId}.json`);
  344. const content = await fs.readFile(docPath, 'utf8');
  345. const doc = JSON.parse(content);
  346. console.log('Sending document:', doc); // 添加日志
  347. res.json(doc);
  348. } catch (error) {
  349. console.error('Error reading document:', error);
  350. res.status(500).json({ error: '读取文档失败', details: error.message });
  351. }
  352. });
  353. // 启动服务器
  354. const PORT = process.env.PORT || 3000;
  355. app.listen(PORT, () => {
  356. console.log(`Server is running on http://localhost:${PORT}`);
  357. });