Camas is a OO design minimal React authorization library.
- TypeScript friendly
- Zero dependencies
- React Hooks
- Scalable
- Easy to test
- Only 500 Bytes after gzip
Installation
Use npm:
$ npm install camas --save
Use yarn:
$ yarn add camas
Policies
Camas is focused around the notion of policy classes. I suggest that you put these classes in src/policies
. This is a simple example that allows updating a post if the user is an admin, or if the post is unpublished:
As you can see, this is just a plain JavaScript class.
Usually you can set up a base class to inherit from:
Context provider
; ;
Camas will pass context
to the policy class when initializing it.
Consume policy
Using hook
; ;
Using component
; ;
Testing
Since polices are just plain classes, testing your polices can be very easy.
Here is a simple example with jest:
; ;
API
Provider
Props
context
- Camas passesconetxt
to the policy class when initializing it.
<Provider conetxt= user: currentUser > <App /></Provider>
Authorize
Props
with
- Policy class.if
- Check function for the policy, it accepts the policy instance as it's first argument.fallback
- Fallback element when policy check now pass.
<Authorize with=PostPolicy if= policy fallback=<div>You are not allow to view these posts</div>> <PostList /></Authorize>
usePolicy(...policies)
The usePolicy
hook receive policies class as it's arguments and return instances of them.
const postPolicy = ;
withPolicies(policies)
A HOC injects policy instance to class component.
@Component { const posts postPolicy = thisprops; return <div> <ul> posts </ul> </div> ; }
authorize(policy, check, fallback)
A HOC to apply policy to the component.
@Component { return ... }
License
MIT