seancdavis
seancdavis

Reputation: 2821

User not being denied access in Active Admin using CanCan

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

Upvotes: 4

Views: 1988

Answers (1)

Hiasinho
Hiasinho

Reputation: 656

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

Upvotes: 1

Related Questions