samuelsimoes
3/14/2013 - 1:46 PM

Using Garp gem with stored tokens from OAuth2

Using Garp gem with stored tokens from OAuth2

##Using Garp gem with stored tokens from OAuth2

You can easily get tokens using omniauth-google-oauth2 gem. Store token, refresh_token and expires_at from auth hash.

Case you don't have any credentials get this in Google Api Console.

Important: you need grant access to Analytics in your scope settings of ominauth gem and in Google API Console in "Services Tab" in order to use Garp gem.

module Reports
  class PageViews
    extend Garb::Model
    dimensions :date
    metrics :pageviews
  end
end
client = OAuth2::Client.new(
  GOOGLE_CLIENT_ID,
  GOOGLE_CLIENT_SECRET,
  {
    :site          => 'https://accounts.google.com',
    :authorize_url => '/o/oauth2/auth',
    :token_url     => '/o/oauth2/token'
  }
)

response = OAuth2::AccessToken.new(
  client,
  STORED_TOKEN, {
  refresh_token: STORED_REFRESH_TOKEN,
  expires_at: STORED_EXPIRES_AT
})

Garb::Session.access_token = response
profile = Garb::Management::Profile.all.detect { |p| p.web_property_id == 'UA-XXXXXXXX-X' }
@pageviews = Reports::PageViews.results(profile, start_date: Date.new(2012,8,1), end_date: Date.today, limit: 50)

Is important you have some strategy case your stored token expires, you can refresh your token using the method .refresh! of OAuth2::AcessToken object.