We are trying to use the google-analytics-data-v1beta
Ruby client library to interact with Google Analytics V1 APIs.
However, we require permission from our web app's users so we added a consent screen (3-Legged OAuth2 flow).
The (web) example I have followed is the one in the docs for the authentication google-auth-library-ruby.
require 'googleauth'
require 'googleauth/web_user_authorizer'
require 'googleauth/stores/redis_token_store'
require 'redis'
client_id = Google::Auth::ClientId.from_file('/path/to/client_secrets.json')
scope = ['https://www.googleapis.com/auth/drive']
token_store = Google::Auth::Stores::RedisTokenStore.new(redis: Redis.new)
authorizer = Google::Auth::WebUserAuthorizer.new(
client_id, scope, token_store, '/oauth2callback')
get('/authorize') do
# NOTE: Assumes the user is already authenticated to the app
user_id = request.session['user_id']
credentials = authorizer.get_credentials(user_id, request)
if credentials.nil?
redirect authorizer.get_authorization_url(login_hint: user_id, request: request)
end
# Credentials are valid, can call APIs
# ...
end
get('/oauth2callback') do
target_url = Google::Auth::WebUserAuthorizer.handle_auth_callback_deferred(
request)
redirect target_url
end
It seems we can call the Google Analytics Data V1 Beta APIs on the line where credentials are available, but when checking the Google Analytics Data V1 library I can't find any way to pass in the credentials above and forced to use ADC (Application Default Credentials) to authenticate, but that's only for giving permission to our own Google Account.
Snippet from the Google Analytics Data V1 Beta docs: here
require "google/analytics/data/v1beta"
client = ::Google::Analytics::Data::V1beta::AnalyticsData::Client.new do |config|
config.credentials = "path/to/credentialfile.json"
end
Also, I found out that google-apis-analyticsadmin_v1beta
library works fine with adding other credentials type, and the following worked:
credentials = Signet::OAuth2::Client.new
credentials.access_token = token # user's access token
google_analytics_admin_client = ::Google::Apis::AnalyticsadminV1beta::GoogleAnalyticsAdminService.new
google_analytics_admin_client.authorization = credentials
accounts = google_analytics_admin_client.list_accounts
Feels like something is missing.
What I tried:
I was looking for a way to pass in credentials different than ADC (Application Default Credentials).
Something similar to:
credentials = Signet::OAuth2::Client.new
credentials.access_token = access_token # User's access token
client = ::Google::Analytics::Data::V1beta::AnalyticsData::Client.new do |config|
config.credentials = credentials
end
# OR -------
user_id = request.session['user_id']
credentials = authorizer.get_credentials(user_id, request)
client = ::Google::Analytics::Data::V1beta::AnalyticsData::Client.new do |config|
config.credentials = credentials
end
Found a working example:
This is the same snippet mentioned in the question, but it works.