您可以做的是在他们登录时将该字段添加到 JWT 有效负载中,然后创建一个中间件函数来检查该字段作为路由的第二个参数...
假设这是您的架构User.js:
const userSchema = new mongoose.Schema({
name: {
type: String,
required: true,
minlength: 5,
maxlength: 50
},
email: {
type: String,
required: true,
minlength: 5,
maxlength: 255,
unique: true
},
password: {
type: String,
required: true,
minlength: 5,
maxlength: 1024
},
isAdmin: Boolean
});
这是您生成 JWT 令牌的地方:
userSchema.methods.generateAuthToken = function() {
return jwt.sign({ _id: this._id, isAdmin: this.isAdmin }, config.get('jwtPrivateKey'));
}
这里是检查 isAdmin 是否为真的中间件:
module.exports = function (req, res, next) {
if (!req.user.isAdmin) return res.status(403).send('Access denied.');
next();
}
然后你可以将它作为路由处理程序的第二个参数...所以对于 PUT 它将是这样的:
router.put('/:id', [auth, isAdmin, any other middleware...], async (req, res) => {
// handle the route...
});