Skip to content
This repository was archived by the owner on Sep 15, 2021. It is now read-only.
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions samples/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
{
"name": "nodejs-analyticsadmin-samples",
"license": "Apache-2.0",
"author": "Google LLC.",
"repository": "googleanalytics/nodejs-analyticsadmin",
"engines": {
"node": ">=10"
},
"version": "1.0.0",
"description": "A set of samples for the Google Analytics Admin API Node.js client library.",
"files": [
"*.js"
],
"dependencies": {
"@google-analytics/admin": "^1.0.0",
"google-auth-library": "latest",
"google-gax": "latest",
"open": "^7.0.4",
"server-destroy": "^1.0.1"
}
}
132 changes: 132 additions & 0 deletions samples/quickstart_installed_oauth2.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

'use strict';

/** This application demonstrates the usage of the Analytics Admin API using
OAuth2 credentials.

Please familiarize yourself with the OAuth2 flow guide at
https://developers.google.com/identity/protocols/oauth2

For more information on authenticating as an end user, see
https://cloud.google.com/docs/authentication/end-user
*/

// Imports the Google Analytics Admin API client library
const analyticsAdmin = require('@google-analytics/admin');

const {OAuth2Client} = require('google-auth-library');
const {grpc} = require('google-gax');
const http = require('http');
const url = require('url');
const open = require('open');
const destroyer = require('server-destroy');

// Reads the secrets from a `keys.json` file, which should be downloaded from
// the Google Developers Console and saved in the same directory with the sample
// app.
const keys = require('./oauth2.keys.json');

const SCOPES = ['https://www.googleapis.com/auth/analytics.readonly'];

async function listAccounts(authClient) {
// Instantiates a client using OAuth2 credentials.
const sslCreds = grpc.credentials.createSsl();
const credentials = grpc.credentials.combineChannelCredentials(
sslCreds,
grpc.credentials.createFromGoogleCredential(authClient)
);
const analyticsAdminClient = new analyticsAdmin.AnalyticsAdminServiceClient({
sslCreds: credentials,
});

// Calls listAccounts() method of the Google Analytics Admin API and prints
// the response for each account.
const [accounts] = await analyticsAdminClient.listAccounts();
console.log('Accounts:');
accounts.forEach(account => {
console.log(account);
});
}

/**
* Create a new OAuth2Client, and go through the OAuth2 content
* workflow. Return the full client to the callback.
*/
function getAuthenticatedClient() {
return new Promise((resolve, reject) => {
// Create an oAuth client to authorize the API call. Secrets are kept in a
// `keys.json` file, which should be downloaded from the Google Developers
// Console.
const oAuth2Client = new OAuth2Client(
keys.web.client_id,
keys.web.client_secret,
// The first redirect URL from the `keys.json` file will be used to
// generate the OAuth2 callback URL. Update the line below or edit the
// redirect URL in the Google Developers Console if needed.
// This sample app expects the callback URL to be
// 'http://localhost:3000/oauth2callback'
//keys.web.redirect_uris[0]
'http://ikuleshov.mtv.corp.google.com:3000/oauth2callback'
);

// Generate the url that will be used for the consent dialog.
const authorizeUrl = oAuth2Client.generateAuthUrl({
access_type: 'offline',
scope: SCOPES.join(' '),
});

// Open an http server to accept the oauth callback. In this simple example, the
// only request to our webserver is to /oauth2callback?code=<code>
const server = http
.createServer(async (req, res) => {
try {
if (req.url.indexOf('/oauth2callback') > -1) {
// acquire the code from the querystring, and close the web server.
const qs = new url.URL(req.url, 'http://localhost:3000')
.searchParams;
const code = qs.get('code');
console.log(`Code is ${code}`);
res.end('Authentication successful! Please return to the console.');
server.destroy();

// Now that we have the code, use that to acquire tokens.
const r = await oAuth2Client.getToken(code);
// Make sure to set the credentials on the OAuth2 client.
oAuth2Client.setCredentials(r.tokens);
console.info('Tokens acquired.');
resolve(oAuth2Client);
}
} catch (e) {
reject(e);
}
})
.listen(3000, () => {
// Open the browser to the authorize url to start the workflow.
// This line will not work if you are running the code in the
// environment where a browser is not available. In this case,
// copy the URL and open it manually in a browser.
console.info(`Opening the browser with URL: ${authorizeUrl}`);
open(authorizeUrl, {wait: false}).then(cp => cp.unref());
});
destroyer(server);
});
}

async function main() {
getAuthenticatedClient().then(authClient => listAccounts(authClient));
}

main().catch(console.error);
68 changes: 68 additions & 0 deletions samples/quickstart_service_account.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

'use strict';

/** This application demonstrates the usage of the Analytics Admin API using
service account credentials. For more information on service accounts, see
https://cloud.google.com/iam/docs/understanding-service-accounts

The following document provides instructions on setting service account
credentials for your application:
https://cloud.google.com/docs/authentication/production

In a nutshell, you need to:

1. Create a service account and download the key JSON file.
https://cloud.google.com/docs/authentication/production#creating_a_service_account

2. Provide service account credentials using one of the following options:

- set the GOOGLE_APPLICATION_CREDENTIALS environment variable, the API
client will use the value of this variable to find the service account key
JSON file.
https://cloud.google.com/docs/authentication/production#setting_the_environment_variable

OR

- manually pass the path to the service account key JSON file to the API client
by specifying the keyFilename parameter in the constructor.
https://cloud.google.com/docs/authentication/production#passing_the_path_to_the_service_account_key_in_code

*/

// Imports the Google Analytics Admin API client library
const analyticsAdmin = require('@google-analytics/admin');

async function main() {
// Instantiates a client using default credentials.
// TODO(developer): uncomment and use the following line in order to
// manually set the path to the service account JSON file instead of
// using the value from the GOOGLE_APPLICATION_CREDENTIALS environment
// variable.
// const analyticsAdminClient = new analyticsAdmin.AnalyticsAdminServiceClient(
// {keyFilename: "your_key_json_file_path"});
const analyticsAdminClient = new analyticsAdmin.AnalyticsAdminServiceClient();

// Calls listAccounts() method of the Google Analytics Admin API and prints
// the response for each account.
const [accounts] = await analyticsAdminClient.listAccounts();

console.log('Accounts:');
accounts.forEach(account => {
console.log(account);
});
}

main().catch(console.error);