Node JS and Access Control

喜夏-厌秋 提交于 2019-12-13 03:59:45

问题


In my project I'm using RBAC Access Control. I have created access-control directory with index.js inside, where I'm creating "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;

And later in route I'm requiring this object

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

To check privileges:

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

Everything is working fine, but my question is about "grantsObject". I would like to have better code organization. In my project I have many roles and code is becoming repetitive.

Admin has kind of inheritance and just extends user privileges. Is there any way to avoid coping user privileges inside admin object?


回答1:


You may want to declare the user permissions first and then declare admin permissions that extends user permissions. e.g.

// 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,
};

The above sample assumes that user and admin share same permissions for the same resource.



来源:https://stackoverflow.com/questions/50086317/node-js-and-access-control

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!