gem "cancancan", '~> 1.12.0'
rails g cancan:ability
RailsAdmin.config do |config|
config.authorize_with :cancan
config.current_user_method { current_admin_user }
end
# in application_controller.rb
helper_method :current_admin_user
before_filter :current_admin_user
rescue_from CanCan::AccessDenied do |exception|
redirect_to main_app.new_admin_authorization_path, :alert => exception.message
end
# used for admin-side auth
def current_admin_user
@current_admin_user ||= AdminUser.find_by(id: session[:admin_user_id])
end
Setup :access enum on AdminUser model
rails g migration AddAccessToAdminUsers access:integer
add_column :admin_users, :access, :integer, null: false, default: 0
# in admin_users
enum access: { read: 0, write: 1, admin: 2 }
Update AdminUser seed accordingly giving access: 2 where appropriate
class Ability
include CanCan::Ability
def initialize(user)
return if user.blank?
if user
can :read, :all
can :access, :rails_admin # grant access to rails_admin
can :dashboard # grant access to the dashboard
end
if user.write?
can :manage, :all
end
if user.admin?
can :manage, :all
end
# can :read, :all # allow everyone to read everything
# if user && user.admin?
# can :access, :rails_admin # only allow admin users to access Rails Admin
# can :dashboard # allow access to dashboard
# 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
# # Always performed
# can :access, :rails_admin # needed to access RailsAdmin
#
# # Performed checks for `root` level actions:
# can :dashboard # dashboard access
#
# # Performed checks for `collection` scoped actions:
# can :index, Model # included in :read
# can :new, Model # included in :create
# can :export, Model
# can :history, Model # for HistoryIndex
# can :destroy, Model # for BulkDelete
#
# # Performed checks for `member` scoped actions:
# can :show, Model, object # included in :read
# can :edit, Model, object # included in :update
# can :destroy, Model, object # for Delete
# can :history, Model, object # for HistoryShow
# can :show_in_app, Model, object
end
end