Granted
An object agnostic authorization layer for javascript. Features both a promise (recommended) and callback api for checking permissions.
account; user;
Introduction:
Sometimes granting access between different objects gets hairy. You have edge cases and lots of ways that permissions can work and things end up being quite a mess.
Granted looks to simplify all of that, taking inspiration from projects like can can in ruby, it defines a few simple methods on an object, allowing us to reliably determine whether one object can perform an action on another.
Let's look at a simple example, say we have three objects, SuperUser
, User
and Document
.
We want a document to be managed by any SuperUser
, but only to a User
if they have
a "role" of "admin", or if they own the account. How would we do that?
First, we would define the granted permissions on the Account
:
var doc = owner_id: 2 title: 'My Secret Account'; // Allow any "authenticated" user to read the document.doc; // Allow SuperUsers to do anything to the document.doc; // Allow Users to do anything to the document if they'redoc; // Allow anyone to read the metadata about an document, unless the// object contains an is_robot flag.doc;
Now, we can elsewhere call the can
method on the object we're checking
permissions on:
// Assumes `granted` has been mixed-in to each constructorvar su = ;var authed = authenticated: true;var user = id: 2;var visitor = ;var robot = is_robot: true; su su authed visitor // or: visitor;
API:
.grants([Constructor | predicate], name, predicate)
Grants the permission specified by name
, (or permissions, if name
is an array)
if the predicate
returns true, resolves with a successful promise, or