const express = require('express'); const router = express.Router(); const { loginLib, stringToBuffer } = require('../modules/cleanup'); // 登录API路由 router.post('/login', (req, res) => { const { username, password } = req.body; if (!username || !password) { return res.status(400).json({ success: false, message: '用户名和密码不能为空' }); } try { if (!loginLib) { throw new Error('动态库未正确加载'); } const usernameData = stringToBuffer(username); const passwordData = stringToBuffer(password); try { const userId = loginLib.validateUser( usernameData.buffer, usernameData.length, passwordData.buffer, passwordData.length ); if (userId > 0) { try { const userInfoStr = loginLib.getUserInfo(userId); let userInfo; try { userInfo = JSON.parse(userInfoStr); res.json({ success: true, message: '登录成功', user: userInfo }); } finally { if (userInfoStr) { //loginLib.freeUserInfo(userInfoStr); } } } catch (userInfoError) { console.error('获取用户信息失败:', userInfoError); res.status(500).json({ success: false, message: '获取用户信息失败', error: userInfoError.message }); } } else { res.json({ success: false, message: '用户名或密码错误' }); } } catch (callError) { throw callError; } } catch (error) { console.error('登录处理过程出错:', error); res.status(500).json({ success: false, message: '服务器内部错误', error: error.message }); } }); // 注册用户API路由 router.post('/register', (req, res) => { const { username, password, userInfo } = req.body; if (!username || !password || !userInfo) { return res.status(400).json({ success: false, message: '用户名、密码和用户信息不能为空' }); } try { if (!loginLib) { throw new Error('动态库未正确加载'); } const usernameData = stringToBuffer(username); const passwordData = stringToBuffer(password); const userInfoData = stringToBuffer(JSON.stringify(userInfo)); try { const userId = loginLib.registerUser( usernameData.buffer, usernameData.length, passwordData.buffer, passwordData.length, userInfoData.buffer, userInfoData.length ); switch (userId) { case -1: res.status(500).json({ success: false, message: '注册失败:一般错误' }); break; case -2: res.status(400).json({ success: false, message: '用户名已存在' }); break; case -3: res.status(400).json({ success: false, message: '无效的用户信息格式' }); break; default: if (userId > 0) { res.json({ success: true, message: '注册成功', userId: userId }); } else { res.status(500).json({ success: false, message: '未知错误' }); } } } catch (callError) { throw callError; } } catch (error) { console.error('注册处理过程出错:', error); res.status(500).json({ success: false, message: '服务器内部错误', error: error.message }); } }); // 获取环境变量 router.get('/env', (req, res) => { const { name } = req.query; if (!name) { return res.status(400).json({ error: '缺少环境变量名称参数' }); } // 出于安全考虑,只允许查询特定的环境变量 const allowedEnvVars = ['XNCore', 'PATH']; if (!allowedEnvVars.includes(name)) { return res.status(403).json({ error: '不允许查询该环境变量' }); } const value = process.env[name] || ''; res.json({ name, value }); }); module.exports = router;