From b0e6b3e241004da47eacc24208d5d1b47fe1640d Mon Sep 17 00:00:00 2001 From: Ilya Kuleshov Date: Thu, 9 Jul 2020 14:39:52 -0700 Subject: [PATCH] docs(samples): added sample apps using service account and OAuth2 credentials --- samples/package.json | 21 ++++ samples/quickstart_installed_oauth2.js | 132 +++++++++++++++++++++++++ samples/quickstart_service_account.js | 68 +++++++++++++ 3 files changed, 221 insertions(+) create mode 100644 samples/package.json create mode 100644 samples/quickstart_installed_oauth2.js create mode 100644 samples/quickstart_service_account.js diff --git a/samples/package.json b/samples/package.json new file mode 100644 index 0000000..c0b33b8 --- /dev/null +++ b/samples/package.json @@ -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" + } +} diff --git a/samples/quickstart_installed_oauth2.js b/samples/quickstart_installed_oauth2.js new file mode 100644 index 0000000..42072d0 --- /dev/null +++ b/samples/quickstart_installed_oauth2.js @@ -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= + 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); diff --git a/samples/quickstart_service_account.js b/samples/quickstart_service_account.js new file mode 100644 index 0000000..1471639 --- /dev/null +++ b/samples/quickstart_service_account.js @@ -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);