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