首页 > 解决方案 > 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匹配

标签: node.jsexpressknex.jsbookshelf.js

解决方案


推荐阅读