Skip to content

Instantly share code, notes, and snippets.

@hayesdavis
Created September 7, 2010 18:21
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save hayesdavis/568777 to your computer and use it in GitHub Desktop.
Save hayesdavis/568777 to your computer and use it in GitHub Desktop.
##
# Below is a template for implementing the "OAuth Dance" with Twitter using the Ruby OAuth gem in a Rails app.
# Ruby OAuth gem is required by grackle and is found here: http://github.com/oauth/oauth-ruby
##
# Step 1: User clicks "Sign in with Twitter" button
# Step 2: User is routed to your controller action that looks like the method below
def start_oauth
@consumer = OAuth::Consumer.new("YOUR_CONSUMER_KEY","YOUR_CONSUMER_SECRET",{:site=>"http://twitter.com" })
@req_token = @consumer.get_request_token(:oauth_callback=>"http://YOUR_CALLBACK_URL")
session[:request_token] = @req_token.token
session[:request_token_secret] = @req_token.secret
redirect_to @req_token.authorize_url
end
# Step 3: User is taken to Twitter to authorize your application
# Step 4: User is redirected from Twitter to your URL which invokes the action below
def finish_oauth
@consumer = OAuth::Consumer.new("YOUR_CONSUMER_KEY","YOUR_CONSUMER_SECRET",{:site=>"http://twitter.com" })
@req_token = OAuth::RequestToken.new(@consumer,session[:request_token],session[:request_token_secret])
# Request user access info from Twitter
@access_token = @req_token.get_access_token
# Store the OAuth info for the user
@user = current_user
@user.update_attributes(:token=>@access_token.token,:token_secret=>@access_token.secret)
# Send the user on their way
redirect_to user_path(@user)
end
@alvincrespo
Copy link

Just had to add the oauth_callback parameter to the get_request_token method:

@req_token = @consumer.get_request_token(:oauth_callback => ('http://' + request.env['HTTP_HOST'] + '/twitter/finalize/'))

@tibbon
Copy link

tibbon commented Nov 9, 2011

Doing this is returning me a pin. Is the URL correct for Twitter?

@tibbon
Copy link

tibbon commented Nov 10, 2011

alvincrespo's thing fixed it, but I hit a new problem.

I think I'm getting a 'nil' with the @oauth_consumer around line 24. I think. NoMethodError - undefined method http_method' for nil:NilClass: /usr/lib/ruby/gems/1.8/gems/oauth-0.4.5/lib/oauth/tokens/request_token.rb:18:inget_access_token'

Since @oauth_consumer isn't defined, I'm guessing tha'ts it. Is that supposed to be @consumer?

@hayesdavis
Copy link
Author

@tibbon, Yes that should be @consumer. I made that change and incorporated @alvincrespo's change.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment