Skip to content

Advanced access control scenarios

MMore edited this page May 24, 2011 · 2 revisions

Custom actions and action groups

For some scenarios you might have even more advanced needs than what is covered by User types, roles, permits and licenses.Cancan comes with the concept of custom actions and aliases for actions built in. We will here see how we can use these to further customize and our access control logic.

In the cancan Ability class

    # alias_action :update, :destroy, :to => :modify
    # can :modify, Comment

Imagine we have a case where on a page, we want to ensure that only users who have the right to administrate a project can see a certain part of the page. Further, within this block, only users who can publish the project should be able to click the publish button and only users who can maintain a project are allowed to edit or delete it.

To implement this logic we can simply define an :admin License that allow :publish and/or :maintain actions (custom defined actions) to be applied on certain kinds of objects (Classes). The Ability class can then be enhanced with a custom action alias for :administrate. This means any user who has the permission to :administrate an object also has permission to :publish and :maintain that object. In this way, :administrate becomes a kind of action group.

  Ability.alias_action :administrate, :to => [:publish, :maintain]

A Role can be granted this license through a Role Permit and a User can be granted the role which the permit applies to. Then apply the following access logic:

can? :administrate, Project do ... can? :publish, Project do

publish section

end

can? :maintain, Project do

maintenance section

end

end