Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails_admin with cancan not catching access denied exception for redirect

I am using rails 5, rails_admin, devise and cancancan.

Everything works correctly, but when there is access denied, it shows a 'You are not authorized to access this page' error screen.

I want to redirect to root_path, I've been searching and I only found that I have to write in app/controllers/application_controller.rb this code:

class ApplicationController < ActionController::Base    
    rescue_from CanCan::AccessDenied do |exception|
        redirect_to root_path, :alert => exception.message
    end
end

And I did, but I am still in the error message when not authorised. It does not redirect.

I think the rest of the code must be ok, because it works, but not redirecting to anywhere.

#config/initializers/rails_admin.rb
config.authorize_with :cancan
config.current_user_method(&:current_user)

.

#app/models/ability.rb
class Ability
    include CanCan::Ability

    def initialize(user)

    user ||= User.new # guest user (not logged in)
    if user.admin
        can :access, :rails_admin       # only allow admin users to access Rails Admin
        can :dashboard           
        can :manage, :all
    else
        can :read, :all                   # allow everyone to read everything
    end
  end
end

I saw more people asking the same, but all of them are without answers. I found one with 3 answers, but I don't understand the accepted solution because it really do not explain any solution: Cancan + Devise rescue_from not catching exception

like image 675
user6945851 Avatar asked Nov 02 '16 18:11

user6945851


1 Answers

It looks like ApplicationController isn't actually a parent of RailsAdmin::MainController by default. So, when RailsAdmin::MainController throws the CanCan::AccessDenied exception, it never actually touches ApplicationController, and the rescue block never kicks in.

You can explicitly declare ApplicationController as the parent for RailsAdmin::MainController in the rails_admin.rb config block with

config.parent_controller = 'ApplicationController' 
like image 174
Coleman Collins Avatar answered Oct 27 '22 14:10

Coleman Collins