使用AuthLogic保护内容

我知道这听起来像一个非常非常简单的用例,我希望它是,但我发誓我已经到处寻找并且没有找到任何方式 – 甚至不是最好的方式 – 这样做。

我是Ruby,Rails以及周围所有东西的新品牌(可能解释很多 )。 我正在使用的虚拟应用程序作为我的学习工具需要进行身份validation才能完成几乎任何有意义的操作,因此我选择从解决该问题开始。 我已经安装了AuthLogic gem并且它在介绍文档和Railscast所涵盖的范围内工作得很好,但现在我可以注册,登录和注销……我需要用它来做一些事情。

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

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

确保在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 

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

 class ExamplesController < ActionController::Base before_filter :require_user, :only => :private def public // some public stuff end def private // some protected stuff end end 

before_filter是你的朋友。 您定义了一个require_authentication函数,如果没有有效会话,则返回false,然后根据您的喜好将其设置为控制器和操作中的before_filter。

查看Authlogic示例应用程序,该应用程序在application_controller.rb中定义了一些filter,然后在需要的地方使用它(例如,在这里 ,您需要记录以销毁您的帐户,而不是记录以创建新帐户。

您需要在页面上使用before_filter,以便只有登录的用户才能看到它。 如果你想要一个如何使用Authlogic的运行示例(包括before_filter的东西),你可以从Github查看Authlogic Exmaple 。

您可以在Github上找到完整的代码Gist。 它大约有360行代码。 包括步骤。

http://gist.github.com/96556.txt