Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Twitter API via OmniAuth on Rails 3, Net::HTTPUnauthorized hell

I followed the Simple OmniAuth tutorial (http://asciicasts.com/episodes/241-simple-omniauth), and I can log in with my twitter account on the service. Now I want to access the twitter API and tweet from the app. My code is as follows:

class TwitterController < ApplicationController

def prepare_access_token(oauth_token, oauth_token_secret)
consumer = OAuth::Consumer.new("KEY", "SECRET",
    {
        :site => "http://api.twitter.com"
    })
    # now create the access token object from passed values
    token_hash =
    {
      :oauth_token => oauth_token,
      :oauth_token_secret => oauth_token_secret
    }
    access_token = OAuth::AccessToken.from_hash(consumer, token_hash)
    return access_token
end

def tweet
    # Exchange our oauth_token and oauth_token secret for the AccessToken instance.
    @access_token = prepare_access_token(current_user.token, current_user.secret)

    @response = @access_token.request(:post, "http://api.twitter.com/1/statuses/update.json", :status => "Tweet pela API")

    render :html => @response.body
end

end

The render line does not do anything. Furthermore, if I add

<p><%= @response %></p>

to my view, I get

#<Net::HTTPUnauthorized:0x2ac5149e94f0>

Still, I am able to get the username from the twitter account.

My user model is as follows:

class User < ActiveRecord::Base
def self.create_with_omniauth(auth)  
       create! do |user|  
         user.provider = auth["provider"]  
         user.uid = auth["uid"]  
         user.name = auth["user_info"]["name"] 
         user.token = auth['credentials']['token'],
         user.secret = auth['credentials']['secret'] 
       end  
    end  
 end

What am I doing wrong?

like image 544
Pedro Vanzella Avatar asked Jan 04 '11 15:01

Pedro Vanzella


2 Answers

I've figured out the problem and now I feel rather silly. There was a comma on the User Model which shouldn't be there. The model should be

class User < ActiveRecord::Base
    def self.create_with_omniauth(auth)  
       create! do |user|  
         user.provider = auth["provider"]  
         user.uid = auth["uid"]  
         user.name = auth["user_info"]["name"] 
         user.token = auth['credentials']['token']
         user.secret = auth['credentials']['secret'] 
       end  
    end  
end

And now everything works fine.

like image 112
Pedro Vanzella Avatar answered Sep 22 '22 19:09

Pedro Vanzella


Rather than coding this up manually., you might want to try using the twitter gem (gem install twitter.) Works for us. Syntax is:

httpauth = Twitter::HTTPAuth.new(twitterName, twitterPass)
client = Twitter::Base.new(httpauth)
client.update(yourTweetText)
like image 44
Joshua Avatar answered Sep 24 '22 19:09

Joshua