Created
October 24, 2009 05:45
-
-
Save hassox/217383 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'rubygems' | |
require 'sinatra' | |
require 'warden' | |
Warden::Strategies.add(:password) do | |
def authenticate! | |
if params["login"] == "name" | |
success!("the user") | |
else | |
fail!("Can't log you in") | |
end | |
end | |
end | |
Warden::Strategies.add(:nigel) do | |
def authenticate! | |
if params["login"] == "nigel" | |
success!("the user") | |
else | |
fail!("You're not nigel") | |
end | |
end | |
end | |
Warden::Manager.before_failure do |env, opts| | |
env['REQUEST_METHOD'] = "POST" | |
end | |
class ::MyMiddleware | |
def initialize(app) | |
@app = app | |
end | |
def call(env) | |
request = Rack::Request.new(env) | |
if request.path == "/custom" | |
request.env["warden"].authenticate! | |
Rack::Response.new("You're OK!").finish | |
else | |
@app.call(env) | |
end | |
end | |
end | |
class MyApp < Sinatra::Application | |
use Rack::Session::Cookie | |
use Warden::Manager do |manager| | |
manager.default_strategies :password | |
manager.failure_app = self | |
end | |
use MyMiddleware | |
helpers do | |
def warden | |
request.env['warden'] | |
end | |
def require_login(*args) | |
warden.authenticate!(*args) | |
end | |
end | |
get "/authd" do | |
require_login | |
"Session: #{request.session}" | |
end | |
get "/public" do | |
"Public" | |
end | |
get "/logout" do | |
warden.logout | |
redirect "/public" | |
end | |
post "/unauthenticated" do | |
out = warden.message | |
out << " You need to login" | |
out | |
end | |
end | |
MyApp.run! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment