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

Commit 1de6156

Browse files
authored
feat: add samples (#10)
1 parent 0116de6 commit 1de6156

6 files changed

Lines changed: 225 additions & 53 deletions

File tree

package.json

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,10 @@
3939
"test": "c8 mocha build/test"
4040
},
4141
"dependencies": {
42-
"google-gax": "^2.6.3"
42+
"google-auth-library": "^6.0.5",
43+
"google-gax": "^2.6.3",
44+
"open": "^7.1.0",
45+
"server-destroy": "^1.0.1"
4346
},
4447
"devDependencies": {
4548
"@types/mocha": "^8.0.0",

samples/package.json

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,12 @@
1313
"test": "c8 mocha --timeout 600000 test/*.js"
1414
},
1515
"dependencies": {
16-
"@google-analytics/admin": "^0.1.0"
16+
"@google-analytics/admin": "^0.1.0",
17+
"google-auth-library": "^6.0.5",
18+
"google-gax": "^2.6.3",
19+
"http": "0.0.1-security",
20+
"open": "^7.1.0",
21+
"server-destroy": "^1.0.1"
1722
},
1823
"devDependencies": {
1924
"c8": "^7.1.0",

samples/quickstart.js

Lines changed: 0 additions & 44 deletions
This file was deleted.
Lines changed: 140 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,140 @@
1+
// Copyright 2020 Google LLC
2+
//
3+
// Licensed under the Apache License, Version 2.0 (the "License");
4+
// you may not use this file except in compliance with the License.
5+
// You may obtain a copy of the License at
6+
//
7+
// http://www.apache.org/licenses/LICENSE-2.0
8+
//
9+
// Unless required by applicable law or agreed to in writing, software
10+
// distributed under the License is distributed on an "AS IS" BASIS,
11+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
// See the License for the specific language governing permissions and
13+
// limitations under the License.
14+
15+
'use strict';
16+
17+
/** This application demonstrates the usage of the Analytics Admin API using
18+
OAuth2 credentials.
19+
Please familiarize yourself with the OAuth2 flow guide at
20+
https://developers.google.com/identity/protocols/oauth2
21+
For more information on authenticating as an end user, see
22+
https://cloud.google.com/docs/authentication/end-user
23+
*/
24+
25+
// Imports the Google Analytics Admin API client library
26+
const analyticsAdmin = require('@google-analytics/admin');
27+
28+
const {OAuth2Client} = require('google-auth-library');
29+
const {grpc} = require('google-gax');
30+
const http = require('http');
31+
const url = require('url');
32+
const open = require('open');
33+
const destroyer = require('server-destroy');
34+
35+
// Reads the secrets from a `keys.json` file, which should be downloaded from
36+
// the Google Developers Console and saved in the same directory with the sample
37+
// app.
38+
// eslint-disable-next-line node/no-unpublished-require
39+
// eslint-disable-next-line node/no-missing-require, node/no-unpublished-require
40+
const keys = require('./oauth2.keys.json');
41+
42+
const SCOPES = ['https://www.googleapis.com/auth/analytics.readonly'];
43+
44+
async function listAccounts(authClient) {
45+
// Instantiates a client using OAuth2 credentials.
46+
const sslCreds = grpc.credentials.createSsl();
47+
const credentials = grpc.credentials.combineChannelCredentials(
48+
sslCreds,
49+
grpc.credentials.createFromGoogleCredential(authClient)
50+
);
51+
const analyticsAdminClient = new analyticsAdmin.AnalyticsAdminServiceClient({
52+
sslCreds: credentials,
53+
});
54+
55+
// Calls listAccounts() method of the Google Analytics Admin API and prints
56+
// the response for each account.
57+
const [accounts] = await analyticsAdminClient.listAccounts();
58+
console.log('Accounts:');
59+
accounts.forEach(account => {
60+
console.log(account);
61+
});
62+
}
63+
64+
/**
65+
* Create a new OAuth2Client, and go through the OAuth2 content
66+
* workflow. Return the full client to the callback.
67+
*/
68+
function getAuthenticatedClient() {
69+
return new Promise((resolve, reject) => {
70+
// Create an oAuth client to authorize the API call. Secrets are kept in a
71+
// `keys.json` file, which should be downloaded from the Google Developers
72+
// Console.
73+
const oAuth2Client = new OAuth2Client(
74+
keys.web.client_id,
75+
keys.web.client_secret,
76+
// The first redirect URL from the `keys.json` file will be used to
77+
// generate the OAuth2 callback URL. Update the line below or edit the
78+
// redirect URL in the Google Developers Console if needed.
79+
// This sample app expects the callback URL to be
80+
// 'http://localhost:3000/oauth2callback'
81+
//keys.web.redirect_uris[0]
82+
'http://ikuleshov.mtv.corp.google.com:3000/oauth2callback'
83+
);
84+
85+
// Generate the url that will be used for the consent dialog.
86+
const authorizeUrl = oAuth2Client.generateAuthUrl({
87+
access_type: 'offline',
88+
scope: SCOPES.join(' '),
89+
});
90+
91+
// Open an http server to accept the oauth callback. In this simple example, the
92+
// only request to our webserver is to /oauth2callback?code=<code>
93+
const server = http
94+
.createServer(async (req, res) => {
95+
try {
96+
if (req.url.indexOf('/oauth2callback') > -1) {
97+
// acquire the code from the querystring, and close the web server.
98+
const qs = new url.URL(req.url, 'http://localhost:3000')
99+
.searchParams;
100+
const code = qs.get('code');
101+
console.log(`Code is ${code}`);
102+
res.end('Authentication successful! Please return to the console.');
103+
server.destroy();
104+
105+
// Now that we have the code, use that to acquire tokens.
106+
const r = await oAuth2Client.getToken(code);
107+
// Make sure to set the credentials on the OAuth2 client.
108+
oAuth2Client.setCredentials(r.tokens);
109+
console.info('Tokens acquired.');
110+
resolve(oAuth2Client);
111+
}
112+
} catch (e) {
113+
reject(e);
114+
}
115+
})
116+
.listen(3000, () => {
117+
// Open the browser to the authorize url to start the workflow.
118+
// This line will not work if you are running the code in the
119+
// environment where a browser is not available. In this case,
120+
// copy the URL and open it manually in a browser.
121+
console.info(`Opening the browser with URL: ${authorizeUrl}`);
122+
open(authorizeUrl, {wait: false}).then(cp => cp.unref());
123+
});
124+
destroyer(server);
125+
});
126+
}
127+
128+
async function main() {
129+
getAuthenticatedClient().then(authClient => listAccounts(authClient));
130+
}
131+
132+
main().catch(console.error);
133+
main(...process.argv.slice(2)).catch(err => {
134+
console.error(err.message);
135+
process.exitCode = 1;
136+
});
137+
process.on('unhandledRejection', err => {
138+
console.error(err.message);
139+
process.exitCode = 1;
140+
});
Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
// Copyright 2020 Google LLC
2+
//
3+
// Licensed under the Apache License, Version 2.0 (the "License");
4+
// you may not use this file except in compliance with the License.
5+
// You may obtain a copy of the License at
6+
//
7+
// http://www.apache.org/licenses/LICENSE-2.0
8+
//
9+
// Unless required by applicable law or agreed to in writing, software
10+
// distributed under the License is distributed on an "AS IS" BASIS,
11+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
// See the License for the specific language governing permissions and
13+
// limitations under the License.
14+
15+
'use strict';
16+
17+
/** This application demonstrates the usage of the Analytics Admin API using
18+
service account credentials. For more information on service accounts, see
19+
https://cloud.google.com/iam/docs/understanding-service-accounts
20+
The following document provides instructions on setting service account
21+
credentials for your application:
22+
https://cloud.google.com/docs/authentication/production
23+
In a nutshell, you need to:
24+
1. Create a service account and download the key JSON file.
25+
https://cloud.google.com/docs/authentication/production#creating_a_service_account
26+
2. Provide service account credentials using one of the following options:
27+
- set the GOOGLE_APPLICATION_CREDENTIALS environment variable, the API
28+
client will use the value of this variable to find the service account key
29+
JSON file.
30+
https://cloud.google.com/docs/authentication/production#setting_the_environment_variable
31+
OR
32+
- manually pass the path to the service account key JSON file to the API client
33+
by specifying the keyFilename parameter in the constructor.
34+
https://cloud.google.com/docs/authentication/production#passing_the_path_to_the_service_account_key_in_code
35+
*/
36+
37+
// Imports the Google Analytics Admin API client library
38+
const analyticsAdmin = require('@google-analytics/admin');
39+
40+
async function main() {
41+
// Instantiates a client using default credentials.
42+
// TODO(developer): uncomment and use the following line in order to
43+
// manually set the path to the service account JSON file instead of
44+
// using the value from the GOOGLE_APPLICATION_CREDENTIALS environment
45+
// variable.
46+
// const analyticsAdminClient = new analyticsAdmin.AnalyticsAdminServiceClient(
47+
// {keyFilename: "your_key_json_file_path"});
48+
const analyticsAdminClient = new analyticsAdmin.AnalyticsAdminServiceClient();
49+
50+
// Calls listAccounts() method of the Google Analytics Admin API and prints
51+
// the response for each account.
52+
const [accounts] = await analyticsAdminClient.listAccounts();
53+
54+
console.log('Accounts:');
55+
accounts.forEach(account => {
56+
console.log(account);
57+
});
58+
}
59+
60+
main().catch(console.error);
61+
main(...process.argv.slice(2)).catch(err => {
62+
console.error(err.message);
63+
process.exitCode = 1;
64+
});
65+
process.on('unhandledRejection', err => {
66+
console.error(err.message);
67+
process.exitCode = 1;
68+
});
Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -17,21 +17,21 @@
1717

1818
'use strict';
1919

20-
// const path = require('path');
21-
// const {assert} = require('chai');
22-
// const cp = require('child_process');
20+
//const path = require('path');
21+
//const {assert} = require('chai');
22+
//const cp = require('child_process');
2323
const {describe, it} = require('mocha');
2424

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

27-
// const cwd = path.join(__dirname, '..');
27+
////const cwd = path.join(__dirname, '..');
2828

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

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

0 commit comments

Comments
 (0)