简体   繁体   中英

Reading x-access-Level header for Twitter REST API using omniauth-twitter / twitter Gem

I'm using Omniauth to authenticate users with Twitter through OAuth (using omniauth-twitter gem). I plan to allow normal users to login with just 'read' permissions, and only authorise 'read-write' permissions if/when they decide to create things within the site.

In my Identity model I'm analysing the AuthHash omniauth passes to the create_with_omniauth action, and I'm making separate logic for each provider type, so that I can look deeper into the returned hash schema if necessary.

If I raise auth.to_yaml to output the structure, I see the 'x-access-level' header that I'd like to read, but I don't know how to look into the response: Net::HTTPOK object in order to get to the next level of the structure.

This is the auth structure, cutting out some of the unnecessary details

--- !ruby/hash:OmniAuth::AuthHash
provider: twitter
...
extra: !ruby/hash:Hashie::Mash
  ...
  access_token: !ruby/object:OAuth::AccessToken
    ...
    response: !ruby/object:Net::HTTPOK
      http_version: '1.1'
      code: '200'
      message: OK
      header:
        x-access-level:
        - read-write
        x-ratelimit-limit:
        - '350'
        x-ratelimit-remaining:
        - '348'
        x-ratelimit-reset:
        - '1330798604'

So far I can get to the response with auth["extra"]["access_token"].response but putting .header at the end returns the same response structure, and ["header"] is empty when I raise it.

I'm ok with using the Twitter gem if necessary to do a verify_credentials call inside the Identity model (since Twitter adds the x-access-level header to every response, but even with this approach I wouldn't know how to read the returned headers to read the x-access-level header.

I know this is not the same ruby twitter client but it might help other that arrive here after looking for the same question with the ruby twitter client (gem "twitter").

So going from this call:

twitter_client = Twitter::Client.new(:oauth_token => token, :oauth_token_secret => secret)

twitter_client.verify_credentials

That will give you only the user info json. You can actually get the twitter api response and then check the x-access-level contained in the header

resp = twitter_client.get, "/1.1/account/verify_credentials.json"
resp[:response_headers]["x-access-level"] # "read-write" in my case

Hope this helps others...

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