使用STI子类和Rails Admin设计身份验证

时间:2012-02-27 01:26:44

标签: ruby-on-rails devise rails-admin

所以我使用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实际指向任何东西。我一直在收到错误。如果用户不是我需要的管理员,也是一个简单的重定向?这是最佳实践,最安全吗?我在这里朝着正确的方向前进吗?任何帮助,将不胜感激。感谢

1 个答案:

答案 0 :(得分: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)接下来,可能更有价值的是,您不希望在authenticate方法中抛出重定向代码。相反,您可能希望将以下内容添加到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
相关问题