0

所以我使用 STI 将一些角色合并到我的用户表中。现在我只有普通用户和管理员。我已经安装了 Rails_admin,我需要一种方法来验证管理员身份,但我不确定如何安全地进行。

现在我的应用程序控制器中有这段代码

def authenticate_admin!(opts={})
  current_admin || redirect_to(?)
end

def current_admin
  current_user if current_user.is_a? Admin
end

在我的 rails_admin.rb 文件中,我有这个

config.authenticate_with do
 authenticate_admin!
end

我目前的问题是我无法让 redirect_to 真正指向任何东西。我不断收到错误。如果用户不是我所需要的管理员,这也是一个简单的重定向吗?这是最佳实践和最安全的吗?我在这里朝着正确的方向前进吗?任何帮助,将不胜感激。谢谢

4

1 回答 1

1

好的,有几件事:

1) CanCan 非常易于使用,值得进行少量安装。如果您有两个用户实例方法 is_admin,下面是 app/models/ability.rb 的示例?和 is_reviewer?

class Ability
  include CanCan::Ability
  def initialize(user)
    if user && user.is_reviewer?
      can :access, :rails_admin
      can :dashboard
      cannot :read, [Class1, Class2, Class3]
      can :read, Class4
    end
    if user && user.is_admin?
      can :access, :rails_admin
      can :manage, :all
    end
  end
end

您的 RailsAdmin 配置将包含以下内容:

RailsAdmin.config do |config|
  config.authorize_with :cancan
  ...
end

并且不要忘记,您必须将 cancan 添加到您的 Gemfile 中才能作为依赖项安装。

2)接下来,可能更有价值的是,您不想在身份验证方法中抛出重定向代码。相反,您可能希望将以下内容添加到 ApplicationController:

rescue_from Acl9::AccessDenied do |exception|
  respond_to do |format|
    format.json do
      render :json => { :success => false, :message => "You do not have access to do this action." }
    end
    format.html do
      flash[:error] = 'You do not have access to view this page.'
      redirect_to root_url
    end
  end
end

要不就:

rescue_from Acl9::AccessDenied do |exception|
  flash[:error] = 'You do not have access to view this page.'
  redirect_to root_url
end
于 2012-02-29T05:07:57.447 回答