google authorize | use selenium to authorize Google access | Cell 3 | Search

This code imports dependencies for a Node.js application, sets up OAuth 2.0 credentials, and creates an instance of the OAuth2Client class to request an access token. The access token is requested using the getToken method of the oauth2Client instance, and the result is handled through a promise with a callback function for both successful and error cases.

Cell 2

var util = require('util');
var {OAuth2Client} = require('google-auth-library');
var TOKEN_DIR = path.join(process.env.HOME || process.env.HOMEPATH || process.env.USERPROFILE || '', '.credentials');
var SECRET_PATH = path.join(TOKEN_DIR, 'client_secret.json');
var credentials = JSON.parse(fs.readFileSync(SECRET_PATH).toString());

var oauth2Client = new OAuth2Client(
    credentials.installed.client_id,
    credentials.installed.client_secret,
    credentials.installed.redirect_uris[0]);

$.async()
util.promisify(oauth2Client.getToken.bind(oauth2Client))
('4/QwGy62FM_KlubQwYvKLAu5z1xrT0cF85Zwb_3U7-IHvmm1gJZ-hj0Qo')
    .then(r => $.sendResult(JSON.stringify(r)))
    .catch(e => $.sendError(e))

What the code could have been:

const { google } = require('googleapis');
const fs = require('fs').promisify('fs');
const path = require('path');
const $ = require('./utils');

async function getOAuth2Client() {
  // Load client secret from local file
  const tokenDir = process.env.HOME
   ? path.join(process.env.HOME, '.credentials')
    : process.env.HOMEPATH
   ? path.join(process.env.HOMEPATH, '.credentials')
    : process.env.USERPROFILE
   ? path.join(process.env.USERPROFILE, '.credentials')
    : null;
  
  if (!tokenDir) {
    throw new Error('Unable to determine token directory');
  }

  const secretPath = path.join(tokenDir, 'client_secret.json');
  const credentials = JSON.parse(await fs.readFile(secretPath, 'utf8'));

  // Create OAuth2 client instance
  const oauth2Client = new google.auth.OAuth2(
    credentials.installed.client_id,
    credentials.installed.client_secret,
    credentials.installed.redirect_uris[0],
  );

  return oauth2Client;
}

async function getToken(oauth2Client, code) {
  try {
    const token = await oauth2Client.getToken(code);
    return token;
  } catch (error) {
    $.sendError(error);
  }
}

async function main() {
  // Get OAuth2 client instance
  const oauth2Client = await getOAuth2Client();

  // Get access token using authorization code
  const code = '4/QwGy62FM_KlubQwYvKLAu5z1xrT0cF85Zwb_3U7-IHvmm1gJZ-hj0Qo';
  const token = await getToken(oauth2Client, code);

  // Send access token as response
  $.sendResult(JSON.stringify(token));
}

main();

Code Breakdown

Importing Dependencies

Setting Up Credentials

Creating an OAuth2 Client

Requesting an Access Token