Skip to content
This repository has been archived by the owner on Sep 19, 2023. It is now read-only.

Commit

Permalink
feat: add samples (#10)
Browse files Browse the repository at this point in the history
  • Loading branch information
sofisl committed Jul 27, 2020
1 parent 0116de6 commit 1de6156
Show file tree
Hide file tree
Showing 6 changed files with 225 additions and 53 deletions.
5 changes: 4 additions & 1 deletion package.json
Expand Up @@ -39,7 +39,10 @@
"test": "c8 mocha build/test"
},
"dependencies": {
"google-gax": "^2.6.3"
"google-auth-library": "^6.0.5",
"google-gax": "^2.6.3",
"open": "^7.1.0",
"server-destroy": "^1.0.1"
},
"devDependencies": {
"@types/mocha": "^8.0.0",
Expand Down
7 changes: 6 additions & 1 deletion samples/package.json
Expand Up @@ -13,7 +13,12 @@
"test": "c8 mocha --timeout 600000 test/*.js"
},
"dependencies": {
"@google-analytics/admin": "^0.1.0"
"@google-analytics/admin": "^0.1.0",
"google-auth-library": "^6.0.5",
"google-gax": "^2.6.3",
"http": "0.0.1-security",
"open": "^7.1.0",
"server-destroy": "^1.0.1"
},
"devDependencies": {
"c8": "^7.1.0",
Expand Down
44 changes: 0 additions & 44 deletions samples/quickstart.js

This file was deleted.

140 changes: 140 additions & 0 deletions samples/quickstart_installed_oauth2.js
@@ -0,0 +1,140 @@
// 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.
// eslint-disable-next-line node/no-unpublished-require
// eslint-disable-next-line node/no-missing-require, node/no-unpublished-require
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);
main(...process.argv.slice(2)).catch(err => {
console.error(err.message);
process.exitCode = 1;
});
process.on('unhandledRejection', err => {
console.error(err.message);
process.exitCode = 1;
});
68 changes: 68 additions & 0 deletions samples/quickstart_service_account.js.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);
main(...process.argv.slice(2)).catch(err => {
console.error(err.message);
process.exitCode = 1;
});
process.on('unhandledRejection', err => {
console.error(err.message);
process.exitCode = 1;
});
14 changes: 7 additions & 7 deletions samples/test/quickstart.js → samples/test/quickstarts.js
Expand Up @@ -17,21 +17,21 @@

'use strict';

// const path = require('path');
// const {assert} = require('chai');
// const cp = require('child_process');
//const path = require('path');
//const {assert} = require('chai');
//const cp = require('child_process');
const {describe, it} = require('mocha');

// const execSync = cmd => cp.execSync(cmd, {encoding: 'utf-8'});
//const execSync = cmd => cp.execSync(cmd, {encoding: 'utf-8'});

// const cwd = path.join(__dirname, '..');
////const cwd = path.join(__dirname, '..');

// const name = 'google-cloud-node';

describe('Quickstart', () => {
describe('Quickstart', async () => {
it('should run quickstart', async () => {
// TODO: find out an actual test for our API client:
// const stdout = execSync(`node ./quickstart.js ${name}`, {cwd});
// const stdout = execSync(`node quickstart_service_account.js`, {cwd});
// assert.match(stdout, /insufficient authentication scopes/);
});
});

0 comments on commit 1de6156

Please sign in to comment.