Know more about gem CanCanCan in Ruby On Rails- Part 1

Tram Ho

1. General introduction

  • CanCanCan is a decentralized library for Ruby and Ruby on Rails, which limits the resources that a certain user is allowed to access.
  • All permissions can be specified in one or more capable files and are not duplicated on the controller, view and query DB, keeping the authorization logic in one place for easy maintenance and testing.

2. Abilities in Database

What if you or the client want to change permissions without having to re-deploy the App? In that case, it’s best to store the right logic in the database: it’s easy to use database records when defining capabilities.

In CanCanCan the actions are shown as follows:

3. Ability for Other User

What if you wanted to define a User permission other than current_user ? Let’s say I want to see if another user has the right to see the loan or not
some_user.ability.can? :update, @borrowing

Add the ability method to the User model:

Use delegate to be able to call directly from User :

The results will be as follows:

Finally, if you want to see which object current_user has access to then it’s best to override the mothod current_ability in the ApplicationController.

The results will be tested as follows:

4. Ability Precedence

An ability rule will overwrite the previous ability rule. Suppose the Admin has full control over Borrowing, but cannot delete them.

The important thing is cannot :destroy, Borrowing after the line can :manage, Borrowing . Thus, cannot :destroy will be overridden by can :manage .

Adding can does not override the previous rule.

can? :read will always return true if user_id = even if Borrowing has creation time less than 2021

5. Accessing request data

What if you need to modify permissions based on something outside of the User object? Let’s say you want to blacklist certain IP addresses from comment creation. The IP address is accessible via request.remote_ip but the Ability class does not have access to this address. The simple way to modify what you pass to the Ability object is by overriding the current_ability method in the ApplicationController.

This concept can also be applied to Session or Cookie.

6. Authorization for Namespaced Controllers

By default in the CanCanCan gem is permissions based on the user and object defined in the load_resource. But if you have a SearchController and Admin :: SearchController, you can use some other approach.
In this case, just override the current_ability method in the ApplicationController to include the controller namespace, and create a class Ability knows what to do with it.

Another way is to use another Ability class on this controller:


Through this article, I hope to help you understand more about CanCanCan gem.
References [( )]

Share the news now

Source : Viblo