Kaynağa Gözat

操作用户ID存入数据库

Taio_O 3 hafta önce
ebeveyn
işleme
8758c6aed8

+ 60 - 2
admin/controllers/userController.js

@@ -35,7 +35,7 @@ const loginUser = async (req, res) => {
         if (isMatch) {
             console.log('登录成功,生成token');
             const token = generateToken(user.id);
-            console.log('生成的token:', token);
+            // console.log('生成的token:', token);
             res.json({
                 _id: user.id,
                 username: user.username,
@@ -94,8 +94,66 @@ const getUserProfile = async (req, res) => {
     }
 };
 
+// @desc    获取用户信息
+// @route   GET /api/users/:id
+// @access  Private
+const getUserById = async (req, res) => {
+    try {
+        const user = await User.findById(req.params.id);
+        if (user) {
+            res.json({
+                id: user.id,
+                username: user.username,
+                contact: user.contact || '',
+                remark: user.remark || '',
+                role: user.role
+            });
+        } else {
+            res.status(404).json({ message: '用户不存在' });
+        }
+    } catch (error) {
+        console.error('获取用户信息失败:', error);
+        res.status(500).json({ message: '服务器错误' });
+    }
+};
+
+// @desc    更新用户信息
+// @route   PUT /api/users/:id
+// @access  Private
+const updateUser = async (req, res) => {
+    try {
+        const { contact, remark } = req.body;
+        const userId = req.params.id;
+
+        // 检查用户是否存在
+        const user = await User.findById(userId);
+        if (!user) {
+            return res.status(404).json({ message: '用户不存在' });
+        }
+
+        // 更新用户信息
+        await User.update(userId, {
+            contact,
+            remark
+        });
+
+        res.json({
+            success: true,
+            message: '用户信息更新成功'
+        });
+    } catch (error) {
+        console.error('更新用户信息失败:', error);
+        res.status(500).json({ 
+            success: false,
+            message: '服务器错误'
+        });
+    }
+};
+
 module.exports = {
     loginUser,
     updatePassword,
-    getUserProfile
+    getUserProfile,
+    getUserById,
+    updateUser
 }; 

+ 14 - 8
admin/index.js

@@ -135,10 +135,13 @@ bot.on('message', async (msg) => {
                 groupName: msg.chat.title || '未命名群组',
                 amount: amount,
                 type: 'deposit',
-                exchangeRate: exchangeRate, // 添加汇率字段
-                feeRate: feeRate // 添加费率字段
+                exchangeRate: exchangeRate,
+                feeRate: feeRate,
+                operatorId: msg.from.id
             };
 
+            console.log(transactionData);
+
             try {
                 const result = await Transaction.deposit(transactionData);
                 if (result.success) {
@@ -184,8 +187,9 @@ bot.on('message', async (msg) => {
                 groupName: msg.chat.title || '未命名群组',
                 amount: -amount,
                 type: 'deposit',
-                exchangeRate: exchangeRate, // 添加汇率字段
-                feeRate: feeRate // 添加费率字段
+                exchangeRate: exchangeRate,
+                feeRate: feeRate,
+                operatorId: msg.from.id
             };
 
             try {
@@ -233,8 +237,9 @@ bot.on('message', async (msg) => {
                 groupName: msg.chat.title || '未命名群组',
                 amount: amount,
                 type: 'withdrawal',
-                exchangeRate: exchangeRate, // 添加汇率字段
-                feeRate: feeRate // 添加费率字段
+                exchangeRate: exchangeRate,
+                feeRate: feeRate,
+                operatorId: msg.from.id
             };
 
             try {
@@ -282,8 +287,9 @@ bot.on('message', async (msg) => {
                 groupName: msg.chat.title || '未命名群组',
                 amount: -amount,
                 type: 'withdrawal',
-                exchangeRate: exchangeRate, // 添加汇率字段
-                feeRate: feeRate // 添加费率字段
+                exchangeRate: exchangeRate,
+                feeRate: feeRate,
+                operatorId: msg.from.id
             };
 
             try {

+ 43 - 0
admin/middleware/authMiddleware.js

@@ -0,0 +1,43 @@
+const jwt = require('jsonwebtoken');
+const User = require('../models/User');
+
+// 保护路由中间件
+const protect = async (req, res, next) => {
+    try {
+        let token;
+
+        // 从请求头中获取token
+        if (req.headers.authorization && req.headers.authorization.startsWith('Bearer')) {
+            token = req.headers.authorization.split(' ')[1];
+        }
+
+        if (!token) {
+            return res.status(401).json({ message: '未授权,请登录' });
+        }
+
+        try {
+            // 验证token
+            const decoded = jwt.verify(token, process.env.JWT_SECRET || 'your-secret-key');
+            
+            // 获取用户信息
+            const user = await User.findById(decoded.id);
+            if (!user) {
+                return res.status(401).json({ message: '用户不存在' });
+            }
+
+            // 将用户信息添加到请求对象中
+            req.user = user;
+            next();
+        } catch (error) {
+            console.error('Token验证失败:', error);
+            return res.status(401).json({ message: '无效的token' });
+        }
+    } catch (error) {
+        console.error('认证中间件错误:', error);
+        res.status(500).json({ message: '服务器错误' });
+    }
+};
+
+module.exports = {
+    protect
+}; 

+ 7 - 2
admin/models/Transaction.js

@@ -16,7 +16,7 @@ const createTransactionTable = async () => {
                     amount DECIMAL(10,2) NOT NULL,
                     time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                     remark VARCHAR(255) DEFAULT NULL COMMENT '备注',
-                    operator_id INT NOT NULL COMMENT '操作人ID',
+                    operator_id VARCHAR(50) NOT NULL COMMENT '操作人ID',
                     fee_rate DECIMAL(5,2) DEFAULT NULL COMMENT '费率',
                     exchange_rate DECIMAL(10,4) DEFAULT NULL COMMENT '汇率',
                     INDEX idx_group_time (group_id, time),
@@ -119,6 +119,11 @@ const Transaction = {
             const feeRate = transactionData.feeRate || defaultFeeRate;
             const exchangeRate = transactionData.exchangeRate || defaultExchangeRate;
 
+            // 使用群内操作人的ID作为operator_id
+            const operatorId = transactionData.operatorId || 1;
+
+            console.log(operatorId);
+
             const [result] = await pool.query(
                 'INSERT INTO transactions (group_id, group_name, type, amount, remark, operator_id, fee_rate, exchange_rate) VALUES (?, ?, ?, ?, ?, ?, ?, ?)',
                 [
@@ -127,7 +132,7 @@ const Transaction = {
                     transactionData.type,
                     transactionData.amount,
                     transactionData.remark || null,
-                    transactionData.operatorId,
+                    operatorId,  // 使用群内操作人的ID
                     feeRate,
                     exchangeRate
                 ]

+ 14 - 0
admin/models/User.js

@@ -98,6 +98,20 @@ const User = {
             console.error('密码比较失败:', error);
             throw error;
         }
+    },
+
+    // 更新用户信息
+    update: async (id, updateData) => {
+        try {
+            const [result] = await pool.query(
+                'UPDATE users SET contact = ?, remark = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?',
+                [updateData.contact, updateData.remark, id]
+            );
+            return result.affectedRows > 0;
+        } catch (error) {
+            console.error('更新用户信息失败:', error);
+            throw error;
+        }
     }
 };
 

+ 8 - 4
admin/routes/userRoutes.js

@@ -1,17 +1,21 @@
 const express = require('express');
 const router = express.Router();
+const { protect } = require('../middleware/authMiddleware');
 const {
     loginUser,
     updatePassword,
-    getUserProfile
+    getUserProfile,
+    getUserById,
+    updateUser
 } = require('../controllers/userController');
-const { auth } = require('../middleware/auth');
 
 // 公开路由
 router.post('/login', loginUser);
 
 // 需要认证的路由
-router.get('/profile', auth, getUserProfile);
-router.put('/password', auth, updatePassword);
+router.get('/profile', protect, getUserProfile);
+router.put('/password', protect, updatePassword);
+router.get('/:id', protect, getUserById);
+router.put('/:id', protect, updateUser);
 
 module.exports = router; 

+ 5 - 1
admin/views/transactions.html

@@ -352,7 +352,11 @@
                     <td>¥${Math.abs(parseFloat(transaction.amount)).toFixed(2)}</td>
                     <td>${transaction.fee_rate ? parseFloat(transaction.fee_rate).toFixed(2) + '%' : '-'}</td>
                     <td>${transaction.exchange_rate ? parseFloat(transaction.exchange_rate).toFixed(4) : '-'}</td>
-                    <td>${transaction.operator_name || '-'}</td>
+                    <td>
+                        <a href="https://t.me/c/${transaction.group_id}/${transaction.operator_id}" target="_blank" class="text-primary">
+                            ${transaction.operator_name || '未知用户'}
+                        </a>
+                    </td>
                     <td>${transaction.remark || '-'}</td>
                     <td>
                         <button class="btn btn-sm btn-danger" onclick="deleteTransaction(${transaction.id})">