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

Commit d94dd53

Browse files
committed
docs(samples): added sample apps using service account and OAuth2 credentials
1 parent a2dbf07 commit d94dd53

File tree

3 files changed

+223
-0
lines changed

3 files changed

+223
-0
lines changed

samples/package.json

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
{
2+
"name": "nodejs-analyticsadmin-samples",
3+
"license": "Apache-2.0",
4+
"author": "Google LLC.",
5+
"engines": {
6+
"node": ">=10"
7+
},
8+
"version": "1.0.0",
9+
"description": "A set of samples for the Google Analytics Admin API Node.js client library.",
10+
"files": [
11+
"*.js"
12+
],
13+
"dependencies": {
14+
"@google-analytics/admin": "^1.0.0",
15+
"google-auth-library": "latest",
16+
"google-gax": "latest",
17+
"open": "^7.0.4",
18+
"server-destroy": "^1.0.1"
19+
}
20+
}
Lines changed: 133 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,133 @@
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+
20+
Please familiarize yourself with the OAuth2 flow guide at
21+
https://developers.google.com/identity/protocols/oauth2
22+
23+
For more information on authenticating as an end user, see
24+
https://cloud.google.com/docs/authentication/end-user
25+
*/
26+
27+
// Imports the Google Analytics Admin API client library
28+
const analyticsAdmin = require('@google-analytics/admin');
29+
30+
const {OAuth2Client} = require('google-auth-library');
31+
const {grpc} = require('google-gax');
32+
const http = require('http');
33+
const url = require('url');
34+
const open = require('open');
35+
const destroyer = require('server-destroy');
36+
37+
// Reads the secrets from a `keys.json` file, which should be downloaded from
38+
// the Google Developers Console and saved in the same directory with the sample
39+
// app.
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+
const analyticsAdminClient = new analyticsAdmin.AnalyticsAdminServiceClient(
51+
{sslCreds: credentials});
52+
53+
// Calls listAccounts() method of the Google Analytics Admin API and prints
54+
// the response for each account.
55+
const [accounts] = await analyticsAdminClient.listAccounts();
56+
console.log('Accounts:');
57+
accounts.forEach(account => {
58+
console.log(account);
59+
}
60+
);
61+
}
62+
63+
/**
64+
* Create a new OAuth2Client, and go through the OAuth2 content
65+
* workflow. Return the full client to the callback.
66+
*/
67+
function getAuthenticatedClient() {
68+
return new Promise((resolve, reject) => {
69+
// Create an oAuth client to authorize the API call. Secrets are kept in a
70+
// `keys.json` file, which should be downloaded from the Google Developers
71+
// Console.
72+
const oAuth2Client = new OAuth2Client(
73+
keys.web.client_id,
74+
keys.web.client_secret,
75+
// The first redirect URL from the `keys.json` file will be used to
76+
// generate the OAuth2 callback URL. Update the line below or edit the
77+
// redirect URL in the Google Developers Console if needed.
78+
// This sample app expects the callback URL to be
79+
// 'http://localhost:3000/oauth2callback'
80+
//keys.web.redirect_uris[0]
81+
'http://ikuleshov.mtv.corp.google.com:3000/oauth2callback'
82+
);
83+
84+
// Generate the url that will be used for the consent dialog.
85+
const authorizeUrl = oAuth2Client.generateAuthUrl({
86+
access_type: 'offline',
87+
scope: SCOPES.join(' '),
88+
});
89+
90+
// Open an http server to accept the oauth callback. In this simple example, the
91+
// only request to our webserver is to /oauth2callback?code=<code>
92+
const server = http
93+
.createServer(async (req, res) => {
94+
try {
95+
if (req.url.indexOf('/oauth2callback') > -1) {
96+
// acquire the code from the querystring, and close the web server.
97+
const qs = new url.URL(req.url, 'http://localhost:3000')
98+
.searchParams;
99+
const code = qs.get('code');
100+
console.log(`Code is ${code}`);
101+
res.end(
102+
'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(
130+
authClient => listAccounts(authClient));
131+
}
132+
133+
main().catch(console.error);
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
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+
21+
The following document provides instructions on setting service account
22+
credentials for your application:
23+
https://cloud.google.com/docs/authentication/production
24+
25+
In a nutshell, you need to:
26+
27+
1. Create a service account and download the key JSON file.
28+
https://cloud.google.com/docs/authentication/production#creating_a_service_account
29+
30+
2. Provide service account credentials using one of the following options:
31+
32+
- set the GOOGLE_APPLICATION_CREDENTIALS environment variable, the API
33+
client will use the value of this variable to find the service account key
34+
JSON file.
35+
https://cloud.google.com/docs/authentication/production#setting_the_environment_variable
36+
37+
OR
38+
39+
- manually pass the path to the service account key JSON file to the API client
40+
by specifying the keyFilename parameter in the constructor.
41+
https://cloud.google.com/docs/authentication/production#passing_the_path_to_the_service_account_key_in_code
42+
43+
*/
44+
45+
// Imports the Google Analytics Admin API client library
46+
const analyticsAdmin = require('@google-analytics/admin');
47+
48+
async function main() {
49+
// Instantiates a client using default credentials.
50+
// TODO(developer): uncomment and use the following line in order to
51+
// manually set the path to the service account JSON file instead of
52+
// using the value from the GOOGLE_APPLICATION_CREDENTIALS environment
53+
// variable.
54+
// const analyticsAdminClient = new analyticsAdmin.AnalyticsAdminServiceClient(
55+
// {keyFilename: "your_key_json_file_path"});
56+
const analyticsAdminClient = new analyticsAdmin.AnalyticsAdminServiceClient();
57+
58+
// Calls listAccounts() method of the Google Analytics Admin API and prints
59+
// the response for each account.
60+
const [accounts] = await
61+
analyticsAdminClient.listAccounts();
62+
63+
console.log('Accounts:');
64+
accounts.forEach(account => {
65+
console.log(account);
66+
}
67+
);
68+
}
69+
70+
main().catch(console.error);

0 commit comments

Comments
 (0)