-
Notifications
You must be signed in to change notification settings - Fork 2.3k
CanCan
Rails Admin is fully compatible with CanCan, an authorization framework to limit which actions a user can perform on each model.
If you haven't already, setup CanCan by adding it to your Gemfile and running the bundle
command.
gem "cancan"
Next, run the generator to create an Ability class. This is where authorization rules are defined.
rails g cancan:ability
To use it with Rails Admin, add this to an initializer.
# in config/initializers/rails_admin.rb
RailsAdmin.config do |config|
config.authorize_with :cancan
end
At this point, all authorization will fail and no one will be able to access the admin pages. To grant access, add this to Ability#initialize
.
can :access, :rails_admin
Then, you will need to grant access on each of the models. Here's a complete example of an Ability
class which defines different permissions depending upon the user's role.
class Ability
include CanCan::Ability
def initialize(user)
can :read, :all # allow everyone to read everything
if user && user.admin?
can :access, :rails_admin # only allow admin users to access Rails Admin
if user.role? :superadmin
can :manage, :all # allow superadmins to do anything
elsif user.role? :manager
can :manage, [User, Product] # allow managers to do anything to products and users
elsif user.role? :sales
can :update, Product, :hidden => false # allow sales to only update visible products
end
end
end
end
How you define the user roles is completely up to you. See the CanCan Documentation for more information.
If the user authorization fails, a CanCan::AccessDenied exception will be raised. You can catch this and modify its behavior in the ApplicationController.
class ApplicationController < ActionController::Base
rescue_from CanCan::AccessDenied do |exception|
redirect_to main_app.root_path, :alert => exception.message
end
end
remove check_authorization
from app/controllers/application_controller.rb, use load_and_authorize_resource
on every controllers instead.
If you are developing for Rails Admin, you can run the CanCan specs by setting the AUTHORIZATION_ADAPTER=cancan
env variable. Like this.
AUTHORIZATION_ADAPTER=cancan bundle
AUTHORIZATION_ADAPTER=cancan rake