Marcin
Marcin

Reputation: 447

Node JS and Access Control

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?

Upvotes: 0

Views: 2016

Answers (1)

Oluwafemi Sule
Oluwafemi Sule

Reputation: 38942

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.

Upvotes: 3

Related Questions