Skip to content

Instantly share code, notes, and snippets.

@ruffle1986
Created April 26, 2018 15:47
Show Gist options
  • Select an option

  • Save ruffle1986/ae00e56ec468c5d4a73dc06021f5c460 to your computer and use it in GitHub Desktop.

Select an option

Save ruffle1986/ae00e56ec468c5d4a73dc06021f5c460 to your computer and use it in GitHub Desktop.
acl
const permissionMap = [
'canEditBilling',
'canSeeEveryArticle',
'editArticle',
'readArticle',
'canQuack'
];
roles = {
admin: {
canEditBilling: true,
canSeeEveryArticle: true,
editArticle: true,
readArticle: true
},
member: {
canSeeEveryArticle: true
},
viewer: {},
collaborator: {
/* canSeeEveryArticle: false */ // 👈 we can set it explicitly, but if it's not there it means false
},
copywriter: {
editArticle: true,
readArticle: true,
},
jessica: {
canDoWhateverMichaelWantsHerToDo: true
},
duck: {
canQuack: true,
readArticle: false,
}
};
const precedence = [
'admin',
'member',
'viewer',
'collaborator',
'copywriter',
'jessica',
'duck',
];
const Norbi = {
id: 1,
roles: ['duck', 'admin'],
};
const Robi = {
id: 2,
roles: ['member'],
};
const Michael = {
id: 3
};
const Article = {
id: 1,
title: 'The beauty of role management',
members: [1, 2],
}
// const user = Robi;
// const user = Norbi;
const user = Michael;
const article = Article;
function hasPermission(permission, user) {
// collect the final permission pack
const permissions = precedence.reverse().reduce((acc, p) => {
if (user.roles && user.roles.includes(p)) {
return Object.assign(acc, roles[p]);
}
return acc;
}, {});
return Boolean(permissions[permission]);
}
const sample = 'canQuack';
console.log(sample, hasPermission(sample, user));
@oroce
Copy link
Copy Markdown

oroce commented Apr 27, 2018

There are couple of great modules in npm which are covering attribute and role based acl, they could be used as inspiration:

@ruffle1986
Copy link
Copy Markdown
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment