ADD file via upload

main
phgkfux43 4 months ago
parent c20ed86aa6
commit a47d083e68

@ -0,0 +1,37 @@
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();
};
};
Loading…
Cancel
Save