Skip to content

Instantly share code, notes, and snippets.

@radar
Created September 1, 2010 02:14
Show Gist options
  • Save radar/560117 to your computer and use it in GitHub Desktop.
Save radar/560117 to your computer and use it in GitHub Desktop.
ActionController::Routing::Routes.draw do |map|
map.twitter 'twitter', :controller => "twitter", :action => "twitter"
map.root :controller => "twitter"
end
class TwitterController < ApplicationController
before_filter :setup_consumer, :only => [:index, :twitter]
def index
# First step: get a request token.
# Remember to specify the oauth_callback option so twitter knows to redirect back to your app.
# If you don't, then it will give you a PIN and that is *so* 1990s.
@request_token = @consumer.get_request_token :oauth_callback => twitter_url
# Store the oauth_secret in the session.
# We use it when Twitter redirects back to us.
session[:oauth_secret] = @request_token.secret
# Redirect out to Twitter to let the user choose to authorize us.
redirect_to @request_token.authorize_url
end
def twitter
# Twitter redirects back to this action.
# We setup another request token.
@request_token = OAuth::RequestToken.new(@consumer,
params[:oauth_token],
session[:oauth_secret])
# We verify that this request token is 100% legit (or there abouts) by using oauth_verifier
@access_token = @request_token.get_access_token :oauth_verifier => params[:oauth_verifier]
# Now that we're authenticated, let's get the user's information just for the sake of it.
@credentials = @access_token.get('/account/verify_credentials.json')
# Or we could post a message by doing this:
@access_token.post('http://twitter.com/statuses/update.xml', { :status => "If this works, then I am authenticated with Twitter through OAuth"})
# Done!
render :text => "Twitter has been spammed!"
end
private
def setup_consumer
# This is not really my key and secret (I'm not *that* stupid), just random characters.
# Setup the consumer here.
@consumer = OAuth::Consumer.new("Nn1QencWdwK7Dh8sEdoA", #Consumer key
"4M76Ct1nrSZPkO42YHF0dSdmk57lKChQ0GmeJirs", #Consumer secret
:site => "http://twitter.com") # Yes, OAuth isn't just for Twitter!
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment