Module: Authentication

Defined in:
lib/generators/i0n/authentication/templates/lib/authentication.rb

Overview

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 %>! Not you?
  <%= 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]

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(controller) ⇒ Object



20
21
22
# File 'lib/generators/i0n/authentication/templates/lib/authentication.rb', line 20

def self.included(controller)
  controller.send :helper_method, :current_user, :logged_in?, :redirect_to_target_or_default
end

Instance Method Details

#current_userObject



24
25
26
# File 'lib/generators/i0n/authentication/templates/lib/authentication.rb', line 24

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

#logged_in?Boolean

Returns:

  • (Boolean)


28
29
30
# File 'lib/generators/i0n/authentication/templates/lib/authentication.rb', line 28

def logged_in?
  current_user
end

#login_requiredObject



32
33
34
35
36
37
38
# File 'lib/generators/i0n/authentication/templates/lib/authentication.rb', line 32

def 
  unless logged_in?
    flash[:error] = "You must first log in or sign up before accessing this page."
    store_target_location
    redirect_to 
  end
end

#redirect_to_target_or_default(default) ⇒ Object



40
41
42
43
# File 'lib/generators/i0n/authentication/templates/lib/authentication.rb', line 40

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