简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM