Sha256: 2bc66b7014ac0259cc7ec24aaae0bfe870ce9f9feaa175a87689cf063d1e26e7

Contents?: true

Size: 1.36 KB

Versions: 7

Compression:

Stored size: 1.36 KB

Contents

# This module is included in your application controller which makes
# several methods available to all controllers and views. Here's a
# common example you might add to your application layout file.
#
#   <% if logged_in? %>
#     Welcome <%= current_user.username %>.
#     <%= link_to "Edit profile", edit_current_user_path %> or
#     <%= link_to "Log out", logout_path %>
#   <% else %>
#     <%= link_to "Sign up", signup_path %> or
#     <%= link_to "log in", login_path %>.
#   <% end %>
#
# You can also restrict unregistered users from accessing a controller using
# a before filter. For example.
#
#   before_filter :login_required, :except => [:index, :show]
module ControllerAuthentication
  def self.included(controller)
    controller.send :helper_method, :current_user, :logged_in?, :redirect_to_target_or_default
  end

  def current_user
    @current_user ||= User.find(session[:user_id]) if session[:user_id]
  end

  def logged_in?
    current_user
  end

  def login_required
    unless logged_in?
      store_target_location
      redirect_to login_url, :alert => "You must first log in or sign up before accessing this page."
    end
  end

  def redirect_to_target_or_default(default, *args)
    redirect_to(session[:return_to] || default, *args)
    session[:return_to] = nil
  end

  private

  def store_target_location
    session[:return_to] = request.url
  end
end

Version data entries

7 entries across 7 versions & 2 rubygems

Version Path
dailycred-0.3.1 dummy-preauth/lib/controller_authentication.rb
dailycred-0.3.0 dummy-preauth/lib/controller_authentication.rb
dailycred-0.2.0 dummy-preauth/lib/controller_authentication.rb
alondra-0.1.1 test/dummy/lib/controller_authentication.rb
alondra-0.1.0 test/dummy/lib/controller_authentication.rb
alondra-0.0.4 test/dummy/lib/controller_authentication.rb
alondra-0.0.3 test/dummy/lib/controller_authentication.rb