<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Dhaval Parikh &#187; OAuth + twitter + rails</title>
	<atom:link href="http://blog.dhavalparikh.co.in/tag/oauth-twitter-rails/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.dhavalparikh.co.in</link>
	<description>Ruby on Rails, Stock Markets, Technology news and info - Its all about my passion</description>
	<lastBuildDate>Wed, 25 Jan 2012 07:06:53 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
<xhtml:meta xmlns:xhtml="http://www.w3.org/1999/xhtml" name="robots" content="noindex" />
		<item>
		<title>Step by Step Twitter OAuth Integration with Rails</title>
		<link>http://blog.dhavalparikh.co.in/2009/06/step-by-step-twitter-oauth-integration-with-rails/</link>
		<comments>http://blog.dhavalparikh.co.in/2009/06/step-by-step-twitter-oauth-integration-with-rails/#comments</comments>
		<pubDate>Wed, 10 Jun 2009 03:14:36 +0000</pubDate>
		<dc:creator>Dhaval Parikh</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[OAuth + twitter + rails]]></category>
		<category><![CDATA[OAuth integration with rails]]></category>
		<category><![CDATA[rails OAuth and Twitter]]></category>
		<category><![CDATA[ruby on rails]]></category>

		<guid isPermaLink="false">http://blog.dhavalparikh.co.in/?p=231</guid>
		<description><![CDATA[There are many articles posted under this topic but none of them have all information or a Step by Step guide of how to integrate OAuth for use with Twitter Apps and Rails. So thought of posting one here. Here are few steps which you should follow. The code below is same as provided by [...]]]></description>
			<content:encoded><![CDATA[<p class="claimcode">There are many articles posted under this topic but none of them have all information or a Step by Step guide of how to integrate OAuth for use with Twitter Apps and Rails.</p>
<p>So thought of posting one here. Here are few steps which you should follow. The code below is same as provided by the twitter wiki but i have made couple of changes and organized it to make it simple to understand</p>
<p>Step 1 : = You need to get your consumer key and consumer secret # from the twitter OAuth site under this link twitteroauth.</p>
<p>Step 2 := Install OAuth Gem with &#8220;gem install oauth&#8221; command on ur terminal</p>
<p>Step 3 := Generate a Scaffold using the following command and then migrate the table called &#8220;users&#8221; to ur database</p>
<p>ruby script/generate scaffold user screen_name:string token:string secret:string</p>
<p>rake db:migrate</p>
<p>Step 4 := Add the following code to your User Controller. Replace the key and secret code with yours <img src='http://blog.dhavalparikh.co.in/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> </p>
<p>def self.consumer</p>
<p># The readkey and readsecret below are the values you get during registration</p>
<p>OAuth::Consumer.new(&#8220;OmwO7wsjtYHjquu6bd6C4w&#8221;, &#8220;j1kZ6yzsqChkeQtToErUx2LnPQMsSPkXMkiy4F82sPA&#8221;,{ :site=&gt;&#8221;http://twitter.com&#8221; })</p>
<p>end</p>
<p>def create</p>
<p>@request_token = UsersController.consumer.get_request_token</p>
<p>session[:request_token] = @request_token.token</p>
<p>session[:request_token_secret] = @request_token.secret</p>
<p># Send to twitter.com to authorize</p>
<p>redirect_to @request_token.authorize_url</p>
<p>return</p>
<p>end</p>
<p>Now this is an important part where you need to set the call back url Which u will define while you register your app at twitter OAuth site. Again add this to the UserController</p>
<p>def callback<br />
@request_token = OAuth::RequestToken.new(UsersController.consumer,<br />
session[:request_token],<br />
session[:request_token_secret])<br />
# Exchange the request token for an access token.<br />
@access_token = @request_token.get_access_token<br />
@response = UsersController.consumer.request(:get, &#8216;/account/verify_credentials.json&#8217;,<br />
@access_token, { :scheme =&gt; :query_string })<br />
case @response<br />
when Net::HTTPSuccess<br />
user_info = JSON.parse(@response.body)<br />
unless user_info['screen_name']<br />
flash[:notice] = &#8220;Authentication failed&#8221;<br />
redirect_to :action =&gt; :index<br />
return<br />
end</p>
<p># We have an authorized user, save the information to the database.<br />
@user = User.new({ :screen_name =&gt; user_info['screen_name'],:token =&gt; @access_token.token,:secret =&gt; @access_token.secret })<br />
@user.save!<br />
# Redirect to the show page<br />
redirect_to(@user)<br />
else<br />
RAILS_DEFAULT_LOGGER.error &#8220;Failed to get user info via OAuth&#8221;<br />
# The user might have rejected this application. Or there was some other error during the request.<br />
flash[:notice] = &#8220;Authentication failed&#8221;<br />
redirect_to :action =&gt; :index<br />
return<br />
end<br />
end<br />
end</p>
<p>As you can see from the comments this callback action exchanges the request token for an access token. Since the user is going to need to type in the username and password at Twitter I avoid prompting for it and instead we fetch that using a call to verify_credentials. This saves duplicate entry and makes it easier on the user. This also prevents users with multiple accounts from giving you one username and then using another when they login to twitter. The access token and secret are what is needed to act on behalf of a user, so those are saved to the database. The show action then uses this information to display some data like so:</p>
<p>def show<br />
@user = User.find(params[:id])<br />
# Get this users favorites via OAuth<br />
@access_token = OAuth::AccessToken.new(UsersController.consumer, @user.token, @user.secret)<br />
RAILS_DEFAULT_LOGGER.error &#8220;Making OAuth request for #{@user.inspect} with #{@access_token.inspect}&#8221;<br />
@response = UsersController.consumer.request(:get, &#8216;/favorites.json&#8217;, @access_token,<br />
{ :scheme =&gt; :query_string })<br />
case @response<br />
when Net::HTTPSuccess<br />
@favorites = JSON.parse(@response.body)<br />
respond_to do |format|<br />
format.html # show.html.erb<br />
end<br />
else<br />
RAILS_DEFAULT_LOGGER.error &#8220;Failed to get favorites via OAuth for #{@user}&#8221;<br />
# The user might have rejected this application. Or there was some other error during the request.<br />
flash[:notice] = &#8220;Authentication failed&#8221;<br />
redirect_to :action =&gt; :index<br />
return<br />
end</p>
<p>Finally the views</p>
<p>&lt;p&gt;<br />
&lt;b&gt;Screen name:&lt;/b&gt;<br />
&lt;%=h @user.screen_name %&gt;<br />
&lt;/p&gt;<br />
&lt;ul&gt;<br />
&lt;% @favorites.each do |fav| %&gt;<br />
&lt;li&gt;&lt;b&gt;&lt;%= fav['user']['screen_name']  %&gt;&lt;/b&gt;: &lt;%=h fav['text']  %&gt;&lt;/li&gt;<br />
&lt;% end %&gt;<br />
&lt;/ul&gt;</p>
<p>and</p>
<p>the new.html.erb</p>
<p>&lt;h1&gt;New user&lt;/h1&gt;</p>
<p>&lt;% form_for(@user) do |f| %&gt;<br />
&lt;%= f.error_messages %&gt;<br />
&lt;p&gt;<br />
We&#8217;ll be sending you to Twitter in a moment to login and grant us access.<br />
Once you allow us in we&#8217;ll give you the super-cool feature<br />
you&#8217;bve heard about.<br />
&lt;/p&gt;<br />
&lt;p&gt;<br />
&lt;%= f.submit &#8220;Grant Access&#8221; %&gt;<br />
&lt;/p&gt;<br />
&lt;% end %&gt;<br />
&lt;%= link_to &#8216;Back&#8217;, users_path %&gt;</p>
<p>Also Add validates_presence_of to the User model for screen_name, token and secret.</p>
<p>And in the routes.rb set the following route</p>
<p>map.connect &#8216;/callback&#8217;, :controller =&gt; &#8216;users&#8217;, :action =&gt; &#8216;callback&#8217;</p>
<p>Thats it you are ready for the twitter Login. Start the server and open localhost:3000/users<br />
and you will see the magic.</p>
<p>These are all the steps. Post me a comment if you still face any isssues.</p>
<p>Please note : &#8211; This method might not function correctly now since the method of authentication has changed. Thanks</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.dhavalparikh.co.in/2009/06/step-by-step-twitter-oauth-integration-with-rails/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
	</channel>
</rss>

