使用AuthLogic保护内容

Rob*_*son 4 ruby-on-rails authlogic

我知道这听起来像一个非常,非常简单的例子,我希望它是,但我发誓我看了所有的地方,并没有发现任何方式任何提及 - 的 - 甚至不是最好的办法这样做.

我是Ruby,Rails以及周围所有东西的新品牌(可能解释很多).我正在使用的虚拟应用程序作为我的学习工具需要进行身份验证才能完成几乎任何有意义的事情,因此我选择从解决该问题开始.我已经安装了AuthLogic创业板有它很好地工作,这是由介绍文档和Railscast覆盖的范围内,但现在,我可以注册,登录和退出...我需要用它做什么.

例如,我需要创建一个用户可以上传图像的页面.我打算ImagesController使用一个upload动作方法,但我希望只有登录用户才能访问.我想在每个限制动作中我都可以添加代码来重定向,如果没有current_user,但这看起来真的很冗长.

有没有更好的方法可以让我定义或识别受限区域并在一个地方处理身份验证检查?

Jim*_*ath 6

确保在application_controller.rb中有这些方法

def current_user_session
  return @current_user_session if defined?(@current_user_session)
  @current_user_session = UserSession.find
end

def current_user
  return @current_user if defined?(@current_user)
  @current_user = current_user_session && current_user_session.record
end

def require_user
  unless current_user
    store_location
    flash[:notice] = "You must be logged in to access this page"
    redirect_to new_user_session_url
    return false
  end
end
Run Code Online (Sandbox Code Playgroud)

然后在您的控制器中,您可以使用前置过滤器来限制对页面的访问

class ExamplesController < ActionController::Base
  before_filter :require_user, :only => :private

  def public
    // some public stuff
  end

  def private
    // some protected stuff
  end
end
Run Code Online (Sandbox Code Playgroud)