问题
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