4
votes

I'm using Active Admin's CanCan authorization adapter, along with Rolify, to manage authorization on an admin site. I have a model, company, that has_many :manuals, and another model, manuals, that has_many :parts.

If a user does not have access to read admin/manuals/1 and types it into the address bar, they are redirected properly and presented with the unauthorized message. However, if the user types in admin/manuals/1/parts they are not denied access. They are taken to that page, except all the parts are hidden from them. They should be getting redirected to the dashboard with an unauthorized message.

Here is my configuration. Thanks in advance for any advice you can offer.

config/routes.rb

ActiveAdmin.routes(self)

models/ability.rb

class Ability
  include CanCan::Ability

  def initialize(user)
    user ||= User.new

    can :read, ActiveAdmin::Page, :name => "Dashboard"

    if user.has_role? :admin
      can :manage, :all
    elsif user.has_role? :moderator
      can :manage, Part, :manual => { :company_id => user.company_id }
    else
      can :read, Part, :manual => { :company_id => user.company_id }
    end
  end
end

I've also overwritten the default authorization methods in controllers/application_controller.rb

rescue_from CanCan::AccessDenied do |exception|
  redirect_to root_url, :alert => exception.message
end

def authenticate_admin_user!
  authenticate_user!
  unless user_signed_in?
    flash[:alert] = "You are not authorized to view this page"
    redirect_to root_path
  end
end

def current_admin_user #use predefined method name
  return nil unless user_signed_in?
  current_user
end

def after_sign_in_path_for(user)
  if current_user.has_role? :admin
    admin_dashboard_path
  elsif current_user.has_role? :moderator
    admin_manuals_path
  else
    company_path(user.company)
  end
end
1
Hey did you ever figure this out? I'm at the point where I'm getting the protected method authorize! error.Mike Vormwald
I did not. I ended up with so many deeply-nested routes that it became easier just to build my own admin.seancdavis

1 Answers

1
votes

Did you add the method load_and_authorize_resource to your controller?

Like this:

class SomeController < ApplicationController
  load_and_authorize_resource
  ...
end

Check Abilities & Authorization