authMiddleware.js 941 B

1234567891011121314151617181920212223242526272829303132333435363738
  1. import jwt from 'jsonwebtoken';
  2. import pool from '../config/db.js';
  3. const protect = async (req, res, next) => {
  4. let token;
  5. if (
  6. req.headers.authorization &&
  7. req.headers.authorization.startsWith('Bearer')
  8. ) {
  9. try {
  10. // 从 Bearer token 获取令牌
  11. token = req.headers.authorization.split(' ')[1];
  12. // 验证令牌
  13. const decoded = jwt.verify(token, process.env.JWT_SECRET);
  14. // 获取用户信息
  15. const [rows] = await pool.query('SELECT id, email FROM users WHERE id = ?', [decoded.id]);
  16. if (rows.length > 0) {
  17. req.user = rows[0];
  18. next();
  19. } else {
  20. res.status(401).json({ message: '未找到用户' });
  21. }
  22. } catch (error) {
  23. console.error(error);
  24. res.status(401).json({ message: '未授权,令牌失败' });
  25. }
  26. }
  27. if (!token) {
  28. res.status(401).json({ message: '未授权,没有令牌' });
  29. }
  30. };
  31. export { protect };