0

I followed CanCanCan's configuration instructions for Rails Admin. I get the error message below:

CanCan::AccessDenied in RailsAdmin::MainController#dashboard

You are not authorized to access this page.

Extracted source (around line #180):

178      if cannot?(action, subject, *args)
179        message ||= unauthorized_message(action, subject)
180        raise AccessDenied.new(message, action, subject, args)
181      end
182      subject
183    end 

ability.rb:

class Ability
  include CanCan::Ability


  def initialize(user)
    user ||= User.new # guest user (not logged in)
    can :read, :all
    can :manage, Article, user_id: user.id
    return unless user.admin_role?
    can :access, :rails_admin
    can :read, :dashboard
    can :manage, :all
  end
end

rails_admin.rb:

RailsAdmin.config do |config|
  ## == CancanCan ==
  config.authorize_with :cancancan

  config.actions do
    dashboard                     # mandatory
    index                         # mandatory
    new
    export
    bulk_delete
    show
    edit
    delete
    show_in_app
  end
end

Gemfile includes these:

gem 'cancancan'
gem 'rails_admin', '~> 2.0', '>= 2.0.2'

Permissions seem to be working OK everywhere else though. There are 2 possible roles for a user: admin or user. On my admin account, I'm recognized as an admin and can do things users cannot. For example:

app/views/articles/index.html.erb:

<% if can? :update, article %><td><%= link_to 'Edit', edit_article_path(article) %></td> <% end %>

The "Edit" option only shows up for the user who created the article OR an admin. This works as expected.

Corey
  • 139
  • 1
  • 2
  • 11

1 Answers1

1

In config/initializers/rails_admin.rb, removing config.authorize_with :cancancan and adding the code below seemed to solve the problem. Users with the admin_role can visit /admin, but others cannot. I'm still not sure why cancancan was not playing nicely, however this is now working as expected.

rails_admin.rb:

#config.authorize_with :cancancan

  config.parent_controller = "::ApplicationController"

  config.authorize_with do
    if !current_user || !current_user.admin_role?
      redirect_to(main_app.root_path, alert: "You are not permitted to view this page")
    end
  end

Thanks to philtr

As a note I am using Rails 6.0.2.2; Rails Admin 2.0.2; Cancancan 3.1.0; and I am NOT using Clearance.

Corey
  • 139
  • 1
  • 2
  • 11