Skip to content

Instantly share code, notes, and snippets.

@ches
Forked from lukesutton/gist:107966
Created November 26, 2009 19:09
Show Gist options
  • Save ches/243611 to your computer and use it in GitHub Desktop.
Save ches/243611 to your computer and use it in GitHub Desktop.

Revisions

  1. lukesutton created this gist May 7, 2009.
    20 changes: 20 additions & 0 deletions gistfile1.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,20 @@
    Warden::Manager.serialize_into_session{|user| user.id }
    Warden::Manager.serialize_from_session{|id| User.get(id) }

    Warden::Manager.before_failure do |env,opts|
    # Sinatra is very sensitive to the request method
    # since authentication could fail on any type of method, we need
    # to set it for the failure app so it is routed to the correct block
    env['REQUEST_METHOD'] = "POST"
    end

    Warden::Strategies.add(:password) do
    def valid?
    params["email"] || params["password"]
    end

    def authenticate!
    u = User.authenticate(params["email"], params["password"])
    u.nil? ? fail!("Could not log in") : success!(u)
    end
    end
    9 changes: 9 additions & 0 deletions gistfile2.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,9 @@
    require 'login_management'

    use Rack::Session::Cookie
    use Warden::Manager do |manager|
    manager.default_strategies :password
    manager.failure_app = LoginManager
    end

    run LoginManager
    24 changes: 24 additions & 0 deletions gistfile3.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,24 @@
    class LoginManager < Sinatra::Base
    get "/" do
    haml :welcome
    end

    post '/unauthenticated/?' do
    status 401
    haml :login
    end

    get '/login/?' do
    haml :login
    end

    post '/login/?' do
    env['warden'].authenticate!
    redirect "/"
    end

    get '/logout/?' do
    env['warden'].logout
    redirect '/'
    end
    end