- Notifications
You must be signed in to change notification settings - Fork277
CASL is an isomorphic authorization JavaScript library which restricts what resources a given user is allowed to access
License
stalniy/casl
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
CASL (pronounced /ˈkæsəl/, likecastle) is an isomorphic authorization JavaScript library which restricts what resources a given user is allowed to access. It's designed to be incrementally adoptable and can easily scale between a simple claim based and fully featured subject and attribute based authorization. It makes it easy to manage and share permissions across UI components, API services, and database queries.
Heavily inspired bycancan.
- Versatile
An incrementally adoptable and can easily scale between a simple claim based and fully featured subject and attribute based authorization. - Isomorphic
Can be used on frontend and backend and complementary packages make integration with major Frontend Frameworks and Backend ORMs effortless - TypeSafe
Written in TypeScript, what makes your apps safer and developer experience more enjoyable - Tree shakable
The core is only 6KB mingzipped and can be even smaller! - Declarative
Thanks to declarative rules, you can serialize and share permissions between UI and API or microservices
Project | Status | Description | Supported envinronemnts |
---|---|---|---|
@casl/ability | CASL's core package | nodejs 8+ and ES5 compatible browsers (IE 9+) | |
@casl/mongoose | integration withMongoose | nodejs 8+ | |
@casl/prisma | integration withPrisma | nodejs 12+ | |
@casl/angular | integration withAngular | IE 9+ | |
@casl/react | integration withReact | IE 9+ | |
@casl/vue | integration withVue | IE 11+ (usesWeakMap ) | |
@casl/aurelia | integration withAurelia | IE 11+ (usesWeakMap ) |
A lot of detailed information about CASL, integrations and examples can be found indocumentation.
Ask it insupport chat or onstackoverflow. Please don't ask questions in issues, the issue list of this repo isexclusively for bug reports and feature requests. Questions in the issue list may be closed immediately without answers.
CASL operates on the abilities level, that is what a user can actually do in the application. An ability itself depends on the 4 parameters (last 3 are optional):
- User Action
Describes what user can actually do in the app. User action is a word (usually a verb) which depends on the business logic (e.g.,prolong
,read
). Very often it will be a list of words from CRUD -create
,read
,update
anddelete
. - Subject
The subject or subject type which you want to check user action on. Usually this is a business (or domain) entity name (e.g.,Subscription
,BlogPost
,User
). - Conditions
An object or function which restricts user action only to matched subjects. This is useful when you need to give a permission on resources created by a user (e.g., to allow user to update and delete ownBlogPost
) - Fields
Can be used to restrict user action only to matched subject's fields (e.g., to allow moderator to updatehidden
field ofBlogPost
but not updatedescription
ortitle
)
Using CASL you can describe abilities using regular and inverted rules. Let's see how
Note: all the examples below will be written in TypeScript but CASL can be used in similar way in ES6+ and Nodejs environments.
Lets defineAbility
for a blog website where visitors:
- can read blog posts
- can manage (i.e., do anything) own posts
- cannot delete a post if it was created more than a day ago
import{AbilityBuilder,createMongoAbility}from'@casl/ability'import{User}from'../models';// application specific interfaces/** *@param user contains details about logged in user: its id, name, email, etc */functiondefineAbilitiesFor(user:User){const{ can, cannot, build}=newAbilityBuilder(createMongoAbility);// can read blog postscan('read','BlogPost');// can manage (i.e., do anything) own postscan('manage','BlogPost',{author:user.id});// cannot delete a post if it was created more than a day agocannot('delete','BlogPost',{createdAt:{$lt:Date.now()-24*60*60*1000}});returnbuild();});
Do you see how easily business requirements were translated into CASL's rules?
Note: you can use class instead of string as a subject type (e.g.,can('read', BlogPost)
)
And yes,Ability
class allow you to use some MongoDB operators to define conditions. Don't worry if you don't know MongoDB, it's not required and explained in details inDefining Abilities
Later on you can check abilities by usingcan
andcannot
methods ofAbility
instance.
// in the same file as aboveimport{ForbiddenError}from'@casl/ability';constuser=getLoggedInUser();// app specific functionconstability=defineAbilitiesFor(user);classBlogPost{// business entityconstructor(props){Object.assign(this,props);}}// true if ability allows to read at least one Postability.can('read','BlogPost');// the same asability.can('read',BlogPost);// true, if user is the author of the blog postability.can('manage',newBlogPost({author:user.id}));// true if there is no ability to read this particular blog postconstONE_DAY=24*60*60*1000;constpostCreatedNow=newBlogPost({createdAt:newDate()});constpostCreatedAWeekAgo=newBlogPost({createdAt:newDate(Date.now()-7*ONE_DAY)});// can delete if it's created less than a day agoability.can('delete',postCreatedNow);// trueability.can('delete',postCreatedAWeekAgo);// false// you can even throw an error if there is a missed abilityForbiddenError.from(ability).throwUnlessCan('delete',postCreatedAWeekAgo);
Of course, you are not restricted to use only class instances in order to check permissions on objects. SeeIntroduction for the detailed explanation.
CASL has a complementary package@casl/mongoose which provides easy integration with MongoDB andmongoose.
import{accessibleRecordsPlugin}from'@casl/mongoose';importmongoosefrom'mongoose';mongoose.plugin(accessibleRecordsPlugin);constuser=getUserLoggedInUser();// app specific functionconstability=defineAbilitiesFor(user);constBlogPost=mongoose.model('BlogPost',mongoose.Schema({title:String,author:mongoose.Types.ObjectId,content:String,createdAt:Date,hidden:{type:Boolean,default:false}}))// returns mongoose Query, so you can chain it with other conditionsconstposts=awaitBlogPost.accessibleBy(ability).where({hidden:false});// you can also call it on existing query to enforce permissionsconsthiddenPosts=awaitBlogPost.find({hidden:true}).accessibleBy(ability);// you can even pass the action as a 2nd parameter. By default action is "read"constupdatablePosts=awaitBlogPost.accessibleBy(ability,'update');
SeeDatabase integration for details.
CASL is incrementally adoptable, that means you can start your project with simple claim (or action) based authorization and evolve it later, when your app functionality evolves.
CASL is composable, that means you can implement alternative conditions matching (e.g., based onjoi,ajv or pure functions) and field matching (e.g., to support alternative syntax in fields likeaddresses.*.street
oraddresses[0].street
) logic.
SeeAdvanced usage for details.
Looking for examples? CheckCASL examples repository.
Want to file a bug, contribute some code, or improve documentation? Excellent! Read up on guidelines forcontributing.
If you'd like to help us sustain our community and project, considerto become a financial contributor on Open Collective
This project exists thanks to all the people who contribute. [Contribute].
Become a financial contributor and help us sustain our community. [Contribute]
Support this project with your organization. Your logo will show up here with a link to your website. [Contribute]
Copyright (c) 2017-present, Sergii Stotskyi
About
CASL is an isomorphic authorization JavaScript library which restricts what resources a given user is allowed to access