开发者

How do I fetch the access token for a user using the Twitter gem and the Omniauth gem when the users is already logged in?

Currently I authenticate the user using omniauth. This looks like this in my sessions controller and works well:

def create
  auth = request.env['omniauth.auth']
  unless @auth = Authentication.find_from_hash(auth)
    # Create a new user or add an auth to existing user, depending on
    # whether there is already a user signed in.
    @auth = Authentication.create_from_hash(auth, current_user)
  end
  # Log the authorizing user in.
  self.current_user = @auth.user

  redirect_to authentications_url, :notice => "You've signed in!"
end

After this, I've stored the twitter uid in my authentications table (I also use linkedin, facebook) and I think that the twitter sessions has been closed.

How do I now authenticate so that I can use the Twitter gem? I think it should be something like this if I was calling it right after the 开发者_运维百科omniauth callback.

  token = auth['credentials']['token'],
  secret = auth['credentials']['secret']
  Twitter.oauth_token = token
  Twitter.oauth_token_secret = secret

I clearly need to restart the session and put the token and secret in the right place. How can I create a method to do this?


You need to store both the token and the secret provided by Twitter in your authentications table (Authentication.create_from_hash). As long as you're doing that, this should work:

twitter_credentials = current_user.authorizations.find_by_provider(:twitter)

Twitter.oauth_token = twitter_credentials.token
Twitter.oauth_token_secret = twitter_credentials.token_secret

That's assuming that in your authentications table you store the Twitter token and secret as token and token_secret, as well as storing the provider as twitter

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜