Protecting Content with AuthLogic

落花浮王杯 提交于 2019-12-05 12:12:01

Make sure you have these methods in your 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

Then in your controllers you can use a before filter to limit access to pages

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 is your friend here. You define a require_authentication function that returns false if there is no valid session and then set it up as a before_filter in the controllers and actions to your liking.

Take a look at the Authlogic Sample application, which defines some filters in the application_controller.rb and then uses it where needed (for example here, where you need to be logged to destroy your account, and not logged to create a new one.

You will need to use a before_filter on your page so that only logged in users can see it. If you want a running example of how Authlogic should be used (including the before_filter stuff), you can check out the Authlogic Exmaple from Github.

You have the entire code Gist available here at Github. Its roughly 360 lines of code. Inclusive of steps.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!