Monday, August 13, 2012

How to create OmniAuth provider aliases

I'm working on a project that uses OmniAuth to authenticate with many third-party services, including a few different Google products. There's an omniauth-google-oauth2 strategy that makes this easy, but I wanted to make an alias for this strategy so I could treat access to a user's AdWords account separately from their Analytics or Profile data. Some users will only be connecting our service to one of these products, and I didn't want to request access to everything at once.

My solution was to make aliases for the google_oauth2 strategy. I didn't see a built-in way to do this, nor did web searches reveal other solutions, so here's what I came up with:
# lib/omniauth-adwords-oauth2.rb
require "omniauth-google-oauth2"

class AdwordsOauth2 < OmniAuth::Strategies::GoogleOauth2
  option :name, 'adwords_oauth2'
end

# config/initializers/omniauth.rb
require "omniauth-adwords-oauth2"

Rails.application.config.middleware.use OmniAuth::Builder do
  provider :adwords_oauth2, ENV['GOOGLE_API_CLIENT_ID'], ENV['GOOGLE_API_CLIENT_SECRET'], {
    scope: "https://adwords.google.com/api/adwords/" # could also be adwords-sandbox.google.com
  }
end

OmniAuth.config.logger = Rails.logger

No comments: