1
votes

I have set up a base application with ActiveAdmin, Cancan, Devise and Rolify. It is using a single user model (no separate admin/user).

Works like a charm so far, but I am struggling to limit access to the admin interface to users with the role 'superadmin' (roles are defined in a table 'roles' and assigned via users_roles)

In the activeadmin initalizer I have set:

config.authentication_method = :authenticate_superadmin_user!
config.authorization_adapter = ActiveAdmin::CanCanAdapter
config.cancan_ability_class = "AdminAbility"

Then I have created a file called admin_ability.rb:

class AdminAbility
  include CanCan::Ability

  def initialize(user)
    if user.has_role?('superadmin')
      can :manage, :all
    end
 end
end

and this is my application controller:

class ApplicationController < ActionController::Base
 protect_from_forgery with: :exception

  def authenticate_superadmin_user!
    raise SecurityError unless current_user.try(:role => 'superadmin')
  end

  def access_denied(exception)
    redirect_to root_path, :alert => exception.message
  end 
end

I think I am making a stupid mistake somewhere (and I have done a bit too much copy & paste) - probably in the application controller? Can somebody help me and explain what I have done wrong?

Much obliged!

1
any ideas how to get super admin working with devise: is there a link to such a page? - BenKoshy

1 Answers

2
votes

You're calling the try method incorrectly, change this:

def authenticate_superadmin_user!
  raise SecurityError unless current_user.try(:role => 'superadmin')
end

to this:

def authenticate_superadmin_user!
  raise SecurityError unless current_user.try(:role, 'superadmin')
end

The try method's first argument is the method name, then each argument after that will be arguments to that method. You're supplying a Hash to the try method which is invalid.

This is, of course, if your User model responds to role and accepts an argument of the role name. I would think you actually want to do: current_user.try(:has_role?, 'superadmin')