Skip to content

Instantly share code, notes, and snippets.

@machu
Created June 6, 2010 13:49
Show Gist options
  • Save machu/427597 to your computer and use it in GitHub Desktop.
Save machu/427597 to your computer and use it in GitHub Desktop.
require 'rubygems'
require 'rack/auth/twitter'
class ProtectedApp
def call(env)
Rack::Response.new("Hello, #{env['REMOTE_USER']}").finish
end
end
use Rack::Session::Pool, :expire_after => 2592000
use Rack::OAuth,
:key => 'AI5HDE3OfT4VFiUl3cA',
:secret => 'Pv21pmDppxm02jv5y9K95wLUpIGHqZH0aB0p5gl6iM',
:site => 'http://twitter.com',
:redirect_to => '/protected'
map "/protected" do
use Rack::Auth::Twitter do |screen_name|
screen_name == 'machu'
end
run ProtectedApp.new
end
map "/" do
message = %Q|Hello, world! <a href="/protected">login with Twitter</a>|
run lambda{ Rack::Response.new(message).finish }
end
require 'rack/auth/abstract/request'
require 'rack/oauth'
module Rack
module Auth
# Rack::Auth::Twitter implements Twitter OAuth Authentication.
#
# Initialize with the Rack application that you want protecting,
# and a block that checks if a screen_name is valid.
class Twitter < AbstractHandler
def call(env)
oauth = oauth(env)
screen_name = screen_name(oauth, env)
return oauth_login(oauth) unless screen_name
return forbidden(screen_name) unless valid?(screen_name)
env['REMOTE_USER'] = screen_name
@app.call(env)
end
private
def oauth_login(oauth)
[ 302, { 'Content-Type' => 'text/html', 'Location' => oauth.login_path }, [] ]
end
def forbidden(screen_name)
[ 403, { 'Content-Type' => 'text/plain' }, ["#{screen_name} is not allowed"] ]
end
def valid?(screen_name)
@authenticator.call(screen_name)
end
def screen_name(oauth, env)
session = oauth.session(env)
session[:access_token_params] ? session[:access_token_params][:screen_name] : nil
end
def oauth(env)
Rack::OAuth.get(env, nil)
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment