Rails : OmniAuth : Doorkeeper : Get access to provider’s api

I assume  you have set up your own OmniAuth provider or have used Providers like Facebook, Twitter, LinkedIn.

If in some condition you need to access the api of the OAuth provider like FB’s Graph API and modifying user data in Linked in or Twitter or even in your own provider, you need to verify your authenticity to the provider.

So make sure you keep the access_token given by the provider safe somewhere in session for future use.

class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
  def the_pact
    # You need to implement the method below in your model (e.g. app/models/user.rb)
    auth_data = request.env["omniauth.auth"]
    @user = Spree::User.from_omniauth(auth_data)
    if @user.persisted?
      set_return_to_path_for_admin if @user.is_admin?
      sign_in_and_redirect @user, :event => :authentication # this will throw if @user is not activated
      
      token = auth_data['credentials']['token']
      session['the_pact_access_token'] = token
      
      set_flash_message(:notice, :success, :kind => "ThePact") if is_navigational_format?
    else
      session["devise.the_pact_data"] = auth_data
      redirect_to new_user_registration_url
    end
  end

Then some where in controller you can use the token to use the provider’s APIs to access some external resource.

To have a token object you can simple do

class ThePact::Client < OAuth2::Client
  def initialize
    super(
        ENV['thepact_app_id'],
        ENV['thepact_secret'],
        site: ENV['oauth_provider_url'],
        parse_json: true
    )
  end
end

class ThePact::Token < OAuth2::AccessToken
  # Return a new OAuth2::AccessToken specific to the app
  # and the user with the given token.
  def initialize(token)
    super(
        ThePact::Client.new,
        token
    )
  end
end


access_token = ThePact::Token.new(session['the_pact_access_token'])
access_token.post('some/url', params: {url: 'params'}, body: {file: upload})

Note:

if you pass `params` hash then the data will be sent via URL and visible to network sniffers. If you are sending form data use `body` instead.

 

Sources:

http://stackoverflow.com/a/5698954/3437900

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s