You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

37 lines
1.0 KiB

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();
};
};