从我的应用程序发布到另一个用户的Twitter帐户

时间:2016-03-28 17:52:57

标签: ruby-on-rails twitter omniauth-twitter

我正在创建Rails应用程序,允许我的Twitter应用程序(来自我的Twitter帐户)发布到用户的时间线。目前我在我的网络应用程序中有这些设置应用程序:

consumer_key 
consumer_secret 
access_token
access_token_secret

目前,当用户登录我的网络应用时,会创建一些推文并发布。帖子转到我的推特账户。在授权回调之后,我的网络应用可以将回调中的secrettoken设置为用户帐户。我需要设置哪些密钥和令牌才能使我的网络应用程序在授权后发布到另一个用户的帐户?

我正在使用这个gem从twitter返回一些哈希值:https://github.com/arunagw/omniauth-twitter#authentication-hash

我的代码如下所示: 配置/ secrets.yml

development:
  secret_key_base: 69cc9e7ad45eadafe574hsaf5ba04a21c8bbe9337fb0cb73966bde47a397d72dd0963b29f6218d43c1baeca8bd0a74218e2e552c8d2ab5fdb7fef14
  twitter_api_key: 2BN4jYtsf453374VM4m7HG
  twitter_api_secret: LOE545ksfjkae3r8FOzj3NTHXVBfx8njPX0JHMNqCJs3mOnhQleH

test:
  secret_key_base: 4c644a9f6d038388ec8ds3060177db7a6c342e4d12083cd36b0b7c3b6609eeb6771681c651c3eee3d740f9003103592sdafdsfaeDFHDGAd6c3e938bf

# Do not keep production secrets in the repository,
# instead read values from the environment.
production:
  secret_key_base: <%= ENV["SECRET_KEY_BASE"] %>

配置/初始化/ twitter.rb

$twitter = Twitter::REST::Client.new do |config|
  config.consumer_key = "2BN4jYtsf453374VM4m7HG"
  config.consumer_secret = "LOE545ksfjkae3r8FOzj3NTHXVBfx8njPX0JHMNqCJs3mOnhQleH"
  config.access_token = "714265291988058112-EkpjQvSeO6fQBc1ksHahlL8r6QLsYinA"
  config.access_token_secret = "qFdiOIP6aozmBlPfsUEYvDK884jsfaehwOXqlFSf8J4g8bl0x"
end

account.rb

class Account < ActiveRecord::Base
    before_save :capitalize_name

    belongs_to :user
    has_many :posts, dependent: :destroy

    accepts_nested_attributes_for :posts

    validates :account_name, :description, presence: :true

    default_scope { order('created_at DESC') }

    def self.find_or_create_from_auth_hash(auth_hash)
        #account = where(provider: auth_hash.provider, uid: auth_hash.uid).first_or_create
        account = where(id: id_goes_here).first_or_create
        account.update_attributes!(
            name: auth_hash.info.name,
            profile_image: auth_hash.info.image,
            token: auth_hash.credentials.token,
            secret: auth_hash.credentials.secret,
            uid: auth_hash.uid
        )
        account
    end

    private
    def capitalize_name
        self.account_name = self.account_name.split.map { |name| name.capitalize }.join(" ")
    end
end

目前我的rails应用程序总是发布到我的帐户,即使其他用户登录,获得授权并在授权回调中设置了他们的帐户和秘密。这不是我想要的。

PS:这里贴的钥匙都是假的。

1 个答案:

答案 0 :(得分:2)

由于您使用一组固定的凭据在初始化程序中实例化Twitter::REST::Client,因此我假设客户端始终使用与其实例化的凭据。

为了代表Account发布推文,您需要实例化一个利用您从授权中获得的凭据的客户端,如下所示:

class Account < ActiveRecord::Base
  def twitter_client
    Twitter::REST::Client.new do |config|
      config.consumer_key = "2BN4jYtsf453374VM4m7HG"
      config.consumer_secret = "LOE545ksfjkae3r8FOzj3NTHXVBfx8njPX0JHMNqCJs3mOnhQleH"
      config.access_token = self.token
      config.access_token_secret = self.secret
    end
  end
end

然后给出一个帐户,您可以这样张贴:

account.twitter_client.update("Just setting up my twttr")