Search code examples
javascriptgoogle-analyticsgoogle-api-js-client

Google Analytics API - Authorization on Analytics Properties


I'm using Google Analytics API. I need to know if exists a function that returns me a boolean value (or something like that) telling me if the logged google account has the rights to show the charts, but I didn't find anything similar in the API.

So I tried to do something different, I tried to handle the error when I draw the charts with the function execute(), using the callback as explained here: https://developers.google.com/analytics/devguides/reporting/core/v3/coreDevguide#build-a-core-reporting-api-query but my code doesn't call that callback.

Here is my code:

var dataChart = new gapi.analytics.googleCharts.DataChart({
    query: {
      ids: ga_property_id,
      metrics: 'ga:sessions, ga:users',
      dimensions: 'ga:date',
    },
    chart: {
      container: 'chart-container',
      type: 'LINE',
      options: {
        width: '100%',
        fontSize: 14
      }
    }
});

function makeApiCall() {
    dataChart.set({query: dateRange});
    dataChart.execute(handleCoreReportingResults);
}

function handleCoreReportingResults(results) {
    if (!results.error) 
    {
        console.log("success");
    } 
    else 
    {
        console.log("fail");
    }
}

makeApiCall();

I tried also to put the execute() into a try/catch but it works without catch, I guess because the exception comes from the gapi.

Finding a way to know if the logged user has rights on the property will be better, but it will be really good also fixing this code and make it works!

Thanks in advance!


Solution

  • You could call the accounts Summaries API and find the complete list of accounts to which the user has access.

    summary = gapi.client.analytics.management.accountSummaries.list();
    

    And then loop the results to verify that the property or view are among the list.

    But you could also include a view selector component and in that way you would only ever be using view Ids to which the user has access.