diff --git a/auth1.js b/auth1.js new file mode 100644 index 0000000..23a0702 --- /dev/null +++ b/auth1.js @@ -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(); + }; +}; \ No newline at end of file