Created
April 26, 2018 15:47
-
-
Save ruffle1986/ae00e56ec468c5d4a73dc06021f5c460 to your computer and use it in GitHub Desktop.
acl
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
There are couple of great modules in npm which are covering attribute and role based acl, they could be used as inspiration:
resource
andactions
)