Ruby Twitter how to authorize a user?

I have an app that needs to tweet on a user page.

Using the Twitter gem

I have an action that should create everything.

def call
  client = set_client

  client.token

  client.update!("I'm tweeting with @gem!")
end

      

This method creates a client to use the API

def set_client
  Twitter::REST::Client.new do |config|
    config.consumer_key        = "****"
    config.consumer_secret     = "****"
    config.access_token        = "****"
    config.access_token_secret = "****"
  end
end

      

If I think it is correct, I need to access the user_token and grant permissions to it. But in application settings, I can only get a token for my page.

How can I implement this functionality when I get user access_token and access_token_secret?

+3


source to share


1 answer


To get an access token and secret for a user, you need to fill in Twitter's three-way authorization.

Gem omniauth-twitter makes this process easy and is even explained in a good railscasts tutorial

Assuming you have omniauth and UserController configured:

def create
  user = User.from_omniauth(env["omniauth.auth"])
end

      



Then in the User model:

def self.from_omniauth(auth)
  where(auth.slice("provider", "uid")).first || create_from_omniauth(auth)
end

def self.create_from_omniauth(auth)
  create! do |user|
    user.provider = auth["provider"]
    user.uid = auth["uid"]
    user.name = auth["info"]["nickname"]
    user.access_token = auth["credentials"]["token"]
    user.access_token_secret = auth["credentials"]["secret"]
  end
end

def set_client
  Twitter::REST::Client.new do |config|
    config.consumer_key        = "****"
    config.consumer_secret     = "****"
    config.access_token        = access_token
    config.access_token_secret = access_token_secret
  end
end

      

Further information: 3-legged authorization and the railscasts tutorial

+3


source







All Articles