Created
April 29, 2021 12:21
-
-
Save gm50x/f8012467d03cce503e2111a6f0598ceb to your computer and use it in GitHub Desktop.
Permission Grid Example (Draft)
This file contains 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 log = console.log | |
const sg = { | |
admin: 'admin', | |
authors: 'authors', | |
guests: 'guests' | |
} | |
const users = [ | |
{ id: 'johndoe', email: 'johndoe@nobody.com', groups: [sg.admin, sg.authors] }, | |
{ id: 'janedoe', email: 'janedoe@nobody.com', groups: [sg.authors] } | |
] | |
const posts = [ | |
{ id: 1, title: 'one', body: 'body one', ownerId: 'johndoe', status: 'published' }, | |
{ id: 2, title: 'two', body: 'body two', ownerId: 'janedoe', status: 'published' }, | |
{ id: 3, title: 'three', body: 'body three', ownerId: 'johndoe', status: 'published' }, | |
{ id: 4, title: 'four', body: 'body four', ownerId: 'janedoe', status: 'published' }, | |
{ id: 5, title: 'five', body: 'body five', ownerId: 'janedoe', status: 'draft' }, | |
] | |
const userIsAdmin = user => user.groups.includes(sg.admin) | |
const userIsAuthor = user => user.groups.includes(sg.authors) | |
const userIsOwner = key => (user, resource) => resource[key] === user.id | |
const canDeletePosts = (user, post) => { | |
const userIsAdminOrOwner = userIsAdmin(user) || userIsOwner('ownerId')(user, post) | |
const postIsNotYetPublished = post.status !== 'published' | |
return userIsAdminOrOwner && postIsNotYetPublished | |
} | |
const allowAll = () => true | |
const denyAll = () => false | |
const permissionGrid = { | |
users: { | |
create: [userIsAdmin], | |
read: [ | |
userIsAdmin, | |
userIsOwner('id') | |
], | |
update: [ | |
userIsAdmin, | |
userIsOwner('id') | |
], | |
delete: [denyAll] | |
}, | |
posts: { | |
create: [ | |
userIsAdmin, | |
userIsAuthor, | |
], | |
read: [allowAll], | |
update: [ | |
userIsAdmin, | |
userIsOwner('ownerId') | |
], | |
delete: [canDeletePosts] | |
} | |
} | |
const validator = (user, action, resource, resourcePermissions) => | |
resourcePermissions[action] | |
.some(rule => rule(user, resource)) | |
const main = () => { | |
const user = [...users].shift() | |
// const user = [...users].pop() | |
posts.forEach(post => console.log(validator(user, 'delete', post, permissionGrid.posts))) | |
// console.log(validator(user, 'create', { id: 6, title: 'post six', body: 'body six' }, config.posts)) | |
// console.log(validator(user, 'create', { id: 6, title: 'post six', body: 'body six' }, config.posts)) | |
} | |
if (require.main === module) { | |
main() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
nossa, parece bem mais clean.
valeu ter compartilhado isso Getúlio!