From a47d083e68f5232fe4b69f7a28f1bcc46ad62b1d Mon Sep 17 00:00:00 2001 From: phgkfux43 <3469266505@qq.com> Date: Sat, 26 Apr 2025 22:38:36 +0800 Subject: [PATCH] ADD file via upload --- auth1.js | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 auth1.js 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