阻止用户,管理员登录 - Rails设计

时间:2012-10-06 13:35:06

标签: ruby-on-rails authentication devise

我试图在仪表板控制器中使用Devise阻止用户,管理员,代理 - 我收到此错误:

  

未定义的局部变量或方法`current_admin'   DashboardController:类

class DashboardController < ApplicationController
  if current_admin.present?
    before_filter :blocked_admin?
  elsif current_agent.present?
    before_filter :blocked_agent?
  elsif current_user.present?
    before_filter :blocked_user?
  end

  def blocked_admin?
    if current_admin.present? && current_admin.blocked_admin?
      sign_out current_admin
      redirect_to root_path, :notice => "This account has been Blocked - Please Contact Admin"
    end
  end

  def blocked_agent?
    if current_agent.present? && current_agent.blocked_agent?
      sign_out current_agent
      redirect_to root_path, :notice => "This account has been Blocked - Please Contact Admin"
    end
  end

  def blocked_user?
    if current_user.present? && current_user.blocked_user?
      sign_out current_user
      redirect_to root_path, :notice => "This account has been Blocked - Please Contact Admin"
    end
  end

end

我是rails的新手,优化(DRY)代码的最佳方法是什么。并且为了解决上面提到的错误。

我也尝试这样做,我已经以不同的方式将它放在“应用程序控制器”中。 我在删除此行之前遇到的错误:

redirect_to root_path, :notice => "This account has been Blocked - Please Contact Admin"
  

在此操作中多次调用渲染和/或重定向。   请注意,您最多只能调用渲染或重定向   每次行动一次。另请注意,重定向和渲染都不会终止   执行动作,所以如果你想在之后退出动作   重定向,你需要做一些像“redirect_to(...)和   返回”。

删除此行后

redirect_to root_path, :notice => "This account has been Blocked - Please Contact Admin"
  

TrueClass的未定义方法`model_name':Class

  def after_sign_in_path_for(resource)
    if resource.is_a?(Admin) && resource.blocked_admin?
      sign_out current_admin
      redirect_to root_path, :notice => "This account has been Blocked - Please Contact Admin"
    elsif resource.is_a?(Agent) && resource.blocked_agent?
      sign_out current_agent
      redirect_to root_path, :notice => "This account has been Blocked - Please Contact Admin"
    elsif resource.is_a?(Agent) && resource.blocked_agent?
      sign_out current_user
      redirect_to root_path, :notice => "This account has been Blocked - Please Contact Admin"
    else
      #super
      "/dashboard"
    end
  end

2 个答案:

答案 0 :(得分:2)

我建议您考虑使用cancan等外部gem进行身份验证。有真正有用的文档/截屏视频。如果您认为它不适合您的需求,您可以随时检查可用的工具here。你也可以尝试做类似的事情:

在你的application_controller.rb中:

before_filter :check_for_blocking

def check_for_blocking
  if current_user.blocked?
    sign_out current_user
    redirect_to root_path, :notice => "This account has been Blocked - Please Contact Admin"
  end
end

您将面临的主要问题是将current_admin,current_agent统一为current_user。您需要进行角色管理 - 可以使用cancan或其他类似角色的auth gem。

答案 1 :(得分:0)

尝试添加这三行

before_filter :authenticate_user!
before_filter :authenticate_admin!
before_filter :authenticate_agent!