ckanext-googleanalytics/ckanext/googleanalytics/ga_auth.py

54 lines
1.6 KiB
Python
Raw Normal View History

from apiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials
2022-05-07 00:59:15 +02:00
from . import utils
2022-05-07 00:59:15 +02:00
def init_service(credentials_file):
"""Get a service that communicates to a Google API."""
2019-11-22 15:59:22 +01:00
scope = ["https://www.googleapis.com/auth/analytics.readonly"]
credentials = ServiceAccountCredentials.from_json_keyfile_name(
2022-05-07 00:59:15 +02:00
credentials_file, scopes=scope
)
2022-05-07 00:59:15 +02:00
return build("analytics", "v3", credentials=credentials)
def get_profile_id(service):
2022-05-07 00:59:15 +02:00
"""Get static profile ID or fetch one from the service.
Get the profile ID for this user and the service specified by the
'googleanalytics.id' configuration option. This function iterates
over all of the accounts available to the user who invoked the
service to find one where the account name matches (in case the
user has several).
2022-05-07 00:59:15 +02:00
If not user configured, the first account is used
"""
2022-05-07 00:59:15 +02:00
profile_id = utils.config_profile_id()
if profile_id:
return profile_id
accounts = service.management().accounts().list().execute()
2019-11-22 15:59:22 +01:00
if not accounts.get("items"):
return None
2022-05-06 18:01:29 +02:00
accountName = utils.config_account()
webPropertyId = utils.config_id()
2019-11-22 15:59:22 +01:00
for acc in accounts.get("items"):
2022-05-07 00:59:15 +02:00
if not accountName or acc.get("name") == accountName:
2019-11-22 15:59:22 +01:00
accountId = acc.get("id")
2019-11-22 15:59:22 +01:00
profiles = (
service.management()
.profiles()
.list(accountId=accountId, webPropertyId=webPropertyId)
.execute()
)
2019-11-22 15:59:22 +01:00
if profiles.get("items"):
return profiles.get("items")[0].get("id")
return None