hassox (owner)

Revisions

gist: 111416 Download_button fork
public
Public Clone URL: git://gist.github.com/111416.git
Embed All Files: show embed
foo_controller.rb #
1
2
3
4
5
6
class FooController < Application
  before_filter :authenticate!
 
  # snip
 
end
logins_controller.rb #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class LoginsController < ApplicationController
  
  def new
    logout
  end
  
  def create
    authenticate
    if authenticated?
      flash[:message] = "Login Successful"
      redirect_to "/"
    else
      render :new
    end
  end
  
  def destroy
    logout
    flash[:message] = "Logged Out"
    redirect_to "/"
  end
  
  def unauthenticated
    logout
    flash[:message] = "Could Not Login"
    render :new
  end
  
end
 
rails_warden_initializer.rb #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# Configure the middlware
# The following options are available:
# :defaults - the default strategies to run. Can be an array of strategies
# :failure_app - the application to use on failure. Use a controller
# :unauthenticated_acion - The action in the failure_app to call on fail. Defaults to :unauthenticated
Rails.configuration.middleware.use RailsWarden::Manager, :defaults => [:password],
                                                          :failure_app => "logins_controller"
 
#### Strategies for authentication
# Strategies are the logic used to authenticate a user into the system
 
Warden::Strategies.add(:password) do
  # valid? is an optional method that will check if the strategy should be attempted
  # For example, there's no point attempting a strategy if required parameters are missing.
  # If they're not available, the next strategy will be tried
  def valid?
    params["password"] || params["username"]
  end
  
  # The work horse of the strategy. This is where the actual logic lives
  # for the authentication
  def authenticate!
    if u = User.authenticate(params["username"], params["password"])
      success!(u)
    else
      errors.add(:login, "Password or Username incorrect.")
      fail!("Password or Username incorrect.")
    end
  end # authenticate!
end