1

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!

4

1 に答える 1

2

tryメソッドを間違って呼び出しています。これを変更してください:

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

これに:

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

tryメソッドの最初の引数はメソッド名で、その後の各引数はそのメソッドの引数になります。try メソッドに無効な Hash を指定しています。

もちろん、これは User モデルroleがロール名の引数に応答して受け入れる場合です。私はあなたが実際にやりたいと思うでしょう:current_user.try(:has_role?, 'superadmin')

于 2014-02-04T18:34:09.953 に答える