Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access Google analytics without consent page using JavaScript

I am creating a dashboard using Atlasboard.

I need to access the Google analytics data such as page views etc. where I will run some queries shown here.

Is there a way to access my Google analytics data without this consent page appearing? enter image description here

I am using the google-api-nodejs-client api.

I found this post where someone mentions using a service account. But I can't find anyway to get this working in JavaScript.

Any help would be great!

like image 660
smj2393 Avatar asked Apr 10 '14 14:04

smj2393


People also ask

How do I view Google Analytics URL without permission?

First you need to create a Google console account at console.developers.google.com. At Google console: Create a project with a suitable name e.g. dashboard1. Open up API's & Auth from the left menu -> open up API's tab -> turn on the analytics API.

Can I use Google Analytics without consent?

By default, Google Analytics is not GDPR compliant. When using Google Analytics on your website, you must first obtain the explicit consent of end-users to activate the Google Analytics cookies, as well as describe all personal data processing in your website's privacy policy.

Can I use Google Analytics without cookie consent?

1.7 Can I use Google Analytics without cookie consent? No. Under the ePrivacy Directive, all cookies require the user's consent except for strictly necessary cookies. Cookies for web analytics always require the user's consent, whether they are from GA or from a different software.


1 Answers

I have finally managed to find a solution to this problem!!! Here is the solution :)

This is assuming you already have a Google analytics account which has site data such as views and have the request and googleapis modules installed.

First you need to create a Google console account at console.developers.google.com.

At Google console:

  • Create a project with a suitable name e.g. dashboard1.
  • Open up API's & Auth from the left menu -> open up API's tab -> turn on the analytics API.
  • Open up the credentials tab -> create new client id -> select service account
  • A key should automatically download -> click on the key and follow the instructions -> the default password is "notasecret" -> it will then output a .pem file
  • The service account will have an email address e.g. [email protected]

Now go to your Google analytics account at www.google.com/analytics:

  • Follow the steps at https://support.google.com/analytics/answer/1009702?hl=en
  • Then add the email address from your service account.

In the dashboard job (server side using nodejs):

Use this code:

    var fs = require('fs'),
        crypto = require('crypto'),
        request = require('request'); // This is an external module (https://github.com/mikeal/request)

    var authHeader = {
            'alg': 'RS256',
            'typ': 'JWT'
        },
        authClaimSet = {
            'iss': '#######SERVICE ACCOUNT EMAIL GOES HERE#######', // Service account email
            'scope': 'https://www.googleapis.com/auth/analytics.readonly', // We MUST tell them we just want to read data
            'aud': 'https://accounts.google.com/o/oauth2/token'
        },
        SIGNATURE_ALGORITHM = 'RSA-SHA256',
        SIGNATURE_ENCODE_METHOD = 'base64',
        GA_KEY_PATH = '#######DIRECTORY TO YOUR .PEM KEY#######', //finds current directory then appends private key to the directory
        gaKey;

    function urlEscape(source) {
        return source.replace(/\+/g, '-').replace(/\//g, '_').replace(/\=+$/, '');
    }

    function base64Encode(obj) {
        var encoded = new Buffer(JSON.stringify(obj), 'utf8').toString('base64');
        return urlEscape(encoded);
    }

    function readPrivateKey() {
        if (!gaKey) {
            gaKey = fs.readFileSync(GA_KEY_PATH, 'utf8');
        }
        return gaKey;
    }

    var authorize = function(callback) {

        var self = this,
            now = parseInt(Date.now() / 1000, 10), // Google wants us to use seconds
            cipher,
            signatureInput,
            signatureKey = readPrivateKey(),
            signature,
            jwt;

        // Setup time values
        authClaimSet.iat = now;
        authClaimSet.exp = now + 60; // Token valid for one minute

        // Setup JWT source
        signatureInput = base64Encode(authHeader) + '.' + base64Encode(authClaimSet);

        // Generate JWT
        cipher = crypto.createSign('RSA-SHA256');
        cipher.update(signatureInput);
        signature = cipher.sign(signatureKey, 'base64');
        jwt = signatureInput + '.' + urlEscape(signature);

        // Send request to authorize this application
        request({
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            uri: 'https://accounts.google.com/o/oauth2/token',
            body: 'grant_type=' + escape('urn:ietf:params:oauth:grant-type:jwt-bearer') +
                '&assertion=' + jwt
        }, function(error, response, body) {
            if (error) {
                console.log(error);
                callback(new Error(error));
            } else {
                var gaResult = JSON.parse(body);
                if (gaResult.error) {
                    callback(new Error(gaResult.error));
                } else {
                    callback(null, gaResult.access_token);
                    console.log(gaResult);
                    console.log("Authorized");
                    ###########IF IT REACHES THIS STAGE THE ACCOUNT HAS BEEN AUTHORIZED##############
                }
            }
        });

    };



    var request = require('request'),
        qs = require('querystring');

    authorize(function(err, token) {
        if (!err) {
            // Query the number of total visits for a month
            ############requestConfig################
            var requestConfig = {
                'ids': 'ga:#######PROJECT ID GOES HERE#######',
                'dimensions': 'ga:country',
                'metrics': 'ga:users',
                'sort': '-ga:users',
                'start-date': '2014-04-08',
                'end-date': '2014-04-22',
                'max-results': '10'
            };

            request({
                method: 'GET',
                headers: {
                    'Authorization': 'Bearer ' + token // Here is where we use the auth token
                },
                uri: 'https://www.googleapis.com/analytics/v3/data/ga?' + qs.stringify(requestConfig)
            }, function(error, resp, body) {
                console.log(body);
                var data = JSON.parse(body);
                console.log(data);
            });
        }
    });

REMEMBER TO INPUT YOU'RE OWN SERVICE EMAIL ACCOUNT, GA_KEY_PATH AND IDS

You can Google analytics data by changing the requestConfig. I used this Google Analytics Query tool to help me: http://ga-dev-tools.appspot.com/explorer/

The data should then be outputted in the console.

Hope this helps :)

like image 63
smj2393 Avatar answered Oct 22 '22 17:10

smj2393