import jwt from 'jsonwebtoken'; import pool from '../config/db.js'; const protect = async (req, res, next) => { let token; if ( req.headers.authorization && req.headers.authorization.startsWith('Bearer') ) { try { // 从 Bearer token 获取令牌 token = req.headers.authorization.split(' ')[1]; // 验证令牌 const decoded = jwt.verify(token, process.env.JWT_SECRET); // 获取用户信息 const [rows] = await pool.query('SELECT id, email FROM users WHERE id = ?', [decoded.id]); if (rows.length > 0) { req.user = rows[0]; next(); } else { res.status(401).json({ message: '未找到用户' }); } } catch (error) { console.error(error); res.status(401).json({ message: '未授权,令牌失败' }); } } if (!token) { res.status(401).json({ message: '未授权,没有令牌' }); } }; export { protect };