Integrate twitter oAuth in your rails application
Now Twitter is using oAuth service to intergrate with your web application. There are the few steps that you need to follow to use it.
First of all you need to get your consumer key and consumer secret. You will get these details by register your application on twitter.
After getting consumer key and consumer secret, you need to install oauth gem.
$ sudo gem install oauth Password: Successfully installed oauth-0.2.7 1 gem installed Installing ri documentation for oauth-0.2.7... Installing RDoc documentation for oauth-0.2.7...
Now create a new application.
rails twitteroauth cd twitteroauth
Create User scaffold in your application.
ruby script/generate scaffold user screen_name:string token:string secret:string rake db:create rake db:migrate
Add below code in UserController
def self.consumer
# The readkey and readsecret below are the values you get during registration
OAuth::Consumer.new("OmwO7wsjtYHjquu6bd6C4w", "j1kZ6yzsqChkeQtToErUx2LnPQMsSPkXMkiy4F82sPA",{ :site=>"http://twitter.com" })
end
def create
@request_token = UsersController.consumer.get_request_token
session[:request_token] = @request_token.token
session[:request_token_secret] = @request_token.secret
# Send to twitter.com to authorize
redirect_to @request_token.authorize_url
return
end
This action gets a request token from Twitter and then redirects the user to Twitter to authorize access. This action does not call User.new, that is delayed until the user returns from the Twitter authorization.
In the registration above we registered the callback URL as /users/callback, so let’s add that action:
def callback
@request_token = OAuth::RequestToken.new(UsersController.consumer,
session[:request_token],
session[:request_token_secret])
# Exchange the request token for an access token.
@access_token = @request_token.get_access_token
@response = UsersController.consumer.request(:get, '/account/verify_credentials.json',
@access_token, { :scheme => :query_string })
case @response
when Net::HTTPSuccess
user_info = JSON.parse(@response.body)
unless user_info['screen_name']
flash[:notice] = "Authentication failed"
redirect_to :action => :index
return
end
# We have an authorized user, save the information to the database.
@user = User.new({ :screen_name => user_info['screen_name'],:token => @access_token.token,:secret => @access_token.secret })
@user.save!
# Redirect to the show page
redirect_to(@user)
else
RAILS_DEFAULT_LOGGER.error "Failed to get user info via OAuth"
# The user might have rejected this application. Or there was some other error during the request.
flash[:notice] = "Authentication failed"
redirect_to :action => :index
return
end
end
end
def show
@user = User.find(params[:id])
# Get this users favorites via OAuth
@access_token = OAuth::AccessToken.new(UsersController.consumer, @user.token, @user.secret)
RAILS_DEFAULT_LOGGER.error "Making OAuth request for #{@user.inspect} with #{@access_token.inspect}"
@response = UsersController.consumer.request(:get, '/favorites.json', @access_token,
{ :scheme => :query_string })
case @response
when Net::HTTPSuccess
@favorites = JSON.parse(@response.body)
respond_to do |format|
format.html # show.html.erb
end
else
RAILS_DEFAULT_LOGGER.error "Failed to get favorites via OAuth for #{@user}"
# The user might have rejected this application. Or there was some other error during the request.
flash[:notice] = "Authentication failed"
redirect_to :action => :index
return
end
end
Add below code in /users/show.html.erb
Screen name: <%=h @user.screen_name %>
-
<% @favorites.each do |fav| %>
- <%= fav['user']['screen_name'] %>: <%=h fav['text'] %> <% end %>
/users/new.html.erb
New user
<% form_for(@user) do |f| %> <%= f.error_messages %>We'll be sending you to Twitter in a moment to login and grant us access. Once you allow us in we'll give you the super-cool feature you'bve heard about.
<%= f.submit "Grant Access" %>
<% end %> <%= link_to 'Back', users_path %>
route.rb
map.connect '/callback', :controller => 'users', :action => 'callback'
Now you have call users/new url and you will be able to login via Twitter account.


Comments
Thanks
Thanks for posting this. Its exactly what I've been searching for.