Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby Twitter how to authorize user?

I have an app which must to tweet in user's page.

Using gem Twitter

I have an action which must create all stuff.

def call
  client = set_client

  client.token

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

This method create client for using 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 correct I need to get user's access_token and authorize him with permissions. But in app's setting I can get token for my page only.

How I can realize the feature, when I'm getting user's access_token and access_token_secret?

like image 918
mxgoncharov Avatar asked Feb 11 '26 15:02

mxgoncharov


1 Answers

To get an access token and secret for a user, you need to complete Twitter's 3-legged authorization.

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

Assuming you have omniauth configured and a UsersController with:

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

More info: 3-legged authorization and railscasts tutorial

like image 156
user2140039 Avatar answered Feb 14 '26 17:02

user2140039