节点JS和访问控制

时间:2018-04-29 11:56:47

标签: node.js express access privileges organization

在我的项目中,我正在使用RBAC Access Control。我在里面创建了带有index.js的访问控制目录,我正在创建“grantsObject”

'use strict'

const AccessControl = require('accesscontrol');

let grantsObject = {
    admin: {
        // Extends user and can delete and update any video or post

        video: {
            'create:any': ['*'],
            'read:any': ['*'],
            'update:any': ['*'], // Admin privilege
            'delete:any': ['*']  // Admin privilege
        },
        post: {
            'create:any': ['*'],
            'read:any': ['*'],
            'update:any': ['*'], // Admin privilege
            'delete:any': ['*']  // Admin privilege
        }

    },
    user: {
        video: {
            'create:any': ['*'],
            'read:any': ['*']
        },
        post: {
            'create:any': ['*'],
            'read:any': ['*']
        }
    }
};

const ac = new AccessControl(grantsObject);

module.exports = ac;

后来在路线上我需要这个对象

var ac = require('../config/access-control');

检查权限:

const permission = ac.can(req.user.userRole).readAny('post');
if (!permission.granted) {
    return res.status(403).end();
}

一切正常,但我的问题是关于“grantsObject”。我想有更好的代码组织。在我的项目中,我有很多角色,代码变得重复。

Admin具有一种继承性,只是扩展了用户权限。有没有办法避免在管理对象中复制用户权限?

1 个答案:

答案 0 :(得分:1)

您可能希望先声明用户权限,然后声明扩展用户权限的管理员权限。 例如

// Node.js v9.4.0
const user = {
    video: {
        'create:any': ['*'],
        'read:any': ['*']
    },
    post: {
        'create:any': ['*'],
        'read:any': ['*']
    }
}

const admin = {
    video: {
        ...user.video,
        'update:any': ['*'],
        'delete:any': ['*']
        }
    ,
    post: {
        ...user.post,
        'update:any': ['*'],
        'delete:any': ['*']
    }
}

const grantsObject = {
    admin,
    user,
};

以上示例假定用户和管理员共享同一资源的相同权限。