const express = require('express'); const router = express.Router(); const { pool } = require('../config/db'); const bcrypt = require('bcryptjs'); const jwt = require('jsonwebtoken'); // 用户登录 router.post('/login', async (req, res) => { try { const { username, password } = req.body; // 查询用户 const [users] = await pool.query( 'SELECT * FROM users WHERE username = ?', [username] ); if (users.length === 0) { return res.status(401).json({ error: 'Invalid credentials' }); } const user = users[0]; // 验证密码 const isMatch = await bcrypt.compare(password, user.password_hash); if (!isMatch) { return res.status(401).json({ error: 'Invalid credentials' }); } // 生成JWT const token = jwt.sign( { id: user.id, role: user.role }, process.env.JWT_SECRET, { expiresIn: '8h' } ); res.json({ token, user: { id: user.id, username: user.username, role: user.role, fullName: user.full_name } }); } catch (error) { console.error('Login error:', error); res.status(500).json({ error: 'Server error' }); } }); // 获取当前用户信息 router.get('/me', async (req, res) => { try { const token = req.headers.authorization?.split(' ')[1]; if (!token) { return res.status(401).json({ error: 'Not authenticated' }); } const decoded = jwt.verify(token, process.env.JWT_SECRET); const [users] = await pool.query( 'SELECT id, username, email, full_name, role FROM users WHERE id = ?', [decoded.id] ); if (users.length === 0) { return res.status(404).json({ error: 'User not found' }); } res.json(users[0]); } catch (error) { console.error('Get me error:', error); res.status(500).json({ error: 'Server error' }); } }); module.exports = router;