Universal Permissions
Super easy to use javascript can
-style permission management library. Not relying on prototypes — share same permissions across client and server.
Usage
/* permissions.js */ const can set remove = definitions;
Definitions
Definitions can be passed inside an object to Permissions
constructor, or/and can be set/removed dynamically.
For example, you can use a separate module with multiple exports, and then import it as shown above:
/* definitions.js */ const post = viewerid === postauthorId see: true; const comment = viewerid === commentauthorId && !commentblocked delete: commentedit viewerid;
Here exported objects correspond to permission type
, keys such as 'edit', 'delete', etc. correspond to permission action
, and properties correspond to permission definition
.
As you can see, definition can be of any type, but if it's a function, it will recieve viewer
, and entity
objects as params.
Make sure to always return something from functional definition, otherwise action will be always unpermitted.
For some reason, you may want to set/delete/replace definitions during runtime:
; ; // 'edit' replaced ;
can
Then anywhere you want, you can find out whether you can perform an action on given object calling can
:
const viewer = id: 1 ;const comment = authorId: 1 text: 'Hello' ; // true // false // false // true
Last argument can be an object of shape { type: entity }
or a string, representing type. It is your responsibility to pass proper entity to functional definitions. For example, this will, of course, return false
for definitions defined above:
const viewer = id: 1 ;const post = authorId: 1 ; // false // will throw because of // unknown type 'authorId'
can
example
Client-side Not the best style of doing things, but you can get the idea:
const viewer = store;
can
example
Server-side One can imagine such Express setup:
; let app = ; /* Here should be used some auth middleware,* providing req.user, ex. passport */ const getComment = { Comment ;}; const ifCan = { return { if return ; resstatus403; }} /* We update only if we CAN, otherwise we see an error */app;
API
Coming soon.
Contributing
MIT license, you are welcome.