|
| 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 | + ); |
| 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); |
0 commit comments