node.js - Node.js Bookshelf.js Knex 关系问题
问题描述
我真的迷路了,希望得到一些帮助,这让我很困惑。
我的数据库结构如下:
表 -> 用户(有一个 role_id )
表 -> 角色(有 role_id、role_name )
根据用户的 role_id,我想使用 role_id 进行身份验证。
这是我的路线:
router.get('/.isadmin', jwtAuth, authorizedRoles('admin'), function(req, res) {
const { id, orgId, role_id } = req.user.attributes;
res.json({
success: true,
id,
orgId,
roleId: role_id
})
});
这是我的策略:
passport.use(new JwtStrategy(opts, function(jwt_payload, done) {
// User.where('id', jwt_payload.id).fetch({withRelated: 'roles'})
console.log('jwt_payload', jwt_payload)
User.where('id', jwt_payload.id).fetch({withRelated: 'roles'})
.then(user => user ? done(null, user) : done(null, false))
.catch(err => done(err, false));
}));
这是我的用户模型:
const Role = require('./role');
module.exports = bookshelf.Model.extend({
tableName: 'user',
roles() {
return this.hasMany(Role, 'role_id')
},
这是我的榜样:
module.exports = bookshelf.Model.extend({
tableName: 'roles'
});
这是我的 authorizedRoles() 函数(未完成)。我遇到的问题是我希望能够传入authorizedRoles('admin') 并且在逻辑上如果经过身份验证的用户具有role_id = 2 它应该与表匹配-> 角色条目与role_id = 2 & 匹配与role_name = "行政”
module.exports = function(...authorizedRoles) {
return function (req, res, next) {
const user = req.user.attributes;
const currentUserRole = req.user.attributes.role_id;
const validRoles = req.roles;
// const currentUserRoles = validRoles.find(currentUserRole);
const test = req.user.related('roles');
const currentUserRoles = req.user.related('roles').models.map(role => {
debugger;
// return role.attributes.role_id === currentUserRole;
return role.attributes.role_id
});
if (!_.intersection(currentUserRoles, authorizedRoles).length) {
res.status(403);
res.send('Not permitted');
return;
}
next();
}
};
对于我的问题:
req.user.related('roles').models.map(role => {
只返回一个角色,它与用户表中的用户 ID 和表角色中的 role_id 匹配。它应该与table(users) role_id -> table(roles) role_id匹配
解决方案
推荐阅读
- flutter - 在 Flutter 中更改 Rive 2 动画
- javascript - v8引擎是先填满调用栈再运行代码吗?还是一进入函数就运行代码
- amazon-web-services - 为什么 CloudFormation 对某些列表类型需要 Quantity?
- mongodb - 使用在 Docker 上运行的导出器和 Prometheus 监控 MongoDB
- python - 在 Python 中学习随机函数
- c++ - 使用 std::move 优化向量构建
- python - 将数据集绘制到折线图
- javascript - 无法在 JavaScript 上正确重用函数
- html - HTML / Wordpress 图像高度/宽度问题
- doctrine-orm - v10 更新失败,MYSQLI_SERVER_PUBLIC_KEY