const jwt = require('jsonwebtoken'); const { jwtSecret } = require('../config'); const User = require('../models/User'); // 保护路由中间件 exports.protect = async (req, res, next) => { let token; if (req.headers.authorization && req.headers.authorization.startsWith('Bearer')) { token = req.headers.authorization.split(' ')[1]; } if (!token) { return res.status(401).json({ message: 'Not authorized, no token' }); } try { // 验证token const decoded = jwt.verify(token, jwtSecret); // 获取用户信息 req.user = await User.findById(decoded.id); next(); } catch (err) { res.status(401).json({ message: 'Not authorized, token failed' }); } }; // 角色授权中间件 exports.authorize = (...roles) => { return (req, res, next) => { if (!roles.includes(req.user.role)) { return res.status(403).json({ message: 'Not authorized to access this route' }); } next(); }; };