A minimal authorization policy builder which defines if a viewer can perform an action on an entity. The Policy can be defined in a declarative manner and can be consumed at various layers of any application.
yarn add auth-policy
// create a new policyconst userPolicy = ;// register concernuserPolicy;// verify authorizationuserPolicy;
|viewer||The user for whom the authorization is being verified.|
|action||A string which defines the action to be performed by the viewer.|
|entity||The object against which the action is to be performed.|
|value||The value associated with the action.|
Every policy has multiple concerns, each of which maps to an action performed by the viewer and defines if the viewer is authorized to perfom that certain action. Concerns are added to a policy using the
;const userPolicy = ;// registering a single concern// associated action = ':read'userPolicy;// registering multiple concerns with same authorization policy// associated actions = ':update', ':delete'userPolicy;
Any policy can have multiple child policies which can be included using the
include function. It is recommended to have a single root level policy and nest all the other entity level policies inside it.
A policy can be included in two ways, either by passing a prebuilt instance of
Policy or using a callback function which receives a fresh instance of
Policy in the argument that can be used to define the concerns inside the function. Policies can be deeply nested as much as you need.
;const postPolicy = ;// associated action = ':read'postPolicy;const policy = ;// including a prebuilt policy// available actions = 'post:read'policy;// using a callback function to define a new policy// accociated actions = 'user:read', 'user:email:update', 'user:phone_number:update'policy;
Once the policy is defined we can simply use the
can function chain to verify the access to the viewer for a certain action.
;const policy = ;policy;const viewer = id: 1 ;const organiser = id: 2 ;const invite = user_id: 1 organiser_id: 2 status: 'Requested' ;policy; // trueconst updatedValue = status: 'Accepted' ;/* pass value using `having` function if* there is any value associated with the action. */policy // falsepolicy // true