question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

OAuth2Client does not work without a callback (Even in async await)

See original GitHub issue

Based on nodejs quickstart sample https://developers.google.com/calendar/quickstart/nodejs#step_3_set_up_the_sample

Following is the code that works:

const fs = require('fs');
const mkdirp = require('mkdirp');
const readline = require('readline');
const {google} = require('googleapis');
const OAuth2Client = google.auth.OAuth2;
const SCOPES = ['https://www.googleapis.com/auth/calendar.readonly'];
const TOKEN_PATH = 'credentials.json';

// Load client secrets from a local file.
fs.readFile('client_secret.json', (err, content) => {
  if (err) return console.log('Error loading client secret file:', err);
  // Authorize a client with credentials, then call the Google Drive API.
  authorize(JSON.parse(content), listEvents);
});

/**
 * Create an OAuth2 client with the given credentials, and then execute the
 * given callback function.
 * @param {Object} credentials The authorization client credentials.
 * @param {function} callback The callback to call with the authorized client.
 */
function authorize(credentials, callback) {
  const {client_secret, client_id, redirect_uris} = credentials.web;
  const oAuth2Client = new OAuth2Client(client_id, client_secret, redirect_uris[0]);

  // Check if we have previously stored a token.
  fs.readFile(TOKEN_PATH, (err, token) => {
    if (err) return getAccessToken(oAuth2Client, callback);
    oAuth2Client.setCredentials(JSON.parse(token));

    // THIS WORKS IF ITS HERE AND PASSED IN CALLBACK
    let client = new OAuth2Client("484407463774-e7biatgmpns9jcpakr5g0sed8fab376u.apps.googleusercontent.com", "722_fI1u2abNM3tL-VbCuZfF", "http://localhost:1337/api/v1/oauthCallback");
    client.setCredentials({
      "access_token": "ya29.GluyBSUYvP_Gi4_SdJHabcJmXUjHnw34MfMBJ8tzROflqyR9dFMDOh_AYh9dmL4FSNDiva_nAcWYCM9m5jBwaL3pWfSm_wv0IybUUdebt66gDakdFXL0o8Mr-0Ge",
      "expiry_date": 1525551674971,
      "token_type": "Bearer",
      "refresh_token": "1/Ug8agC92PkJRXEDLP1inlHcAh4MBP1SLjNoylPJrmfg"
    });


    callback(client);
  });
}

/**
 * Get and store new token after prompting for user authorization, and then
 * execute the given callback with the authorized OAuth2 client.
 * @param {google.auth.OAuth2} oAuth2Client The OAuth2 client to get token for.
 * @param {getEventsCallback} callback The callback for the authorized client.
 */
 function getAccessToken(oAuth2Client, callback) {
  const authUrl = oAuth2Client.generateAuthUrl({
    access_type: 'offline',
    scope: SCOPES,
  });
  console.log('Authorize this app by visiting this url:', authUrl);
  const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
  });
  rl.question('Enter the code from that page here: ', (code) => {
    rl.close();
    oAuth2Client.getToken(code, (err, token) => {
      if (err) return callback(err);
      oAuth2Client.setCredentials(token);
      // Store the token to disk for later program executions
      fs.writeFile(TOKEN_PATH, JSON.stringify(token), (err) => {
        if (err) console.error(err);
        console.log('Token stored to', TOKEN_PATH);
      });
      callback(oAuth2Client).catch(console.error);
    });
  });
}

/**
 * Lists the next 10 events on the user's primary calendar.
 * @param {google.auth.OAuth2} auth An authorized OAuth2 client.
 */
function listEvents(auth) {

  const calendar = google.calendar({ version: 'v3', auth });
  calendar.events.list({
    calendarId: 'primary',
    timeMin: (new Date()).toISOString(),
    maxResults: 10,
    singleEvents: true,
    orderBy: 'startTime',
  }, (err, {data}) => {
    if (err) return console.log('The API returned an error: ' + err);
    const events = data.items;
    if (events.length) {
      console.log('Upcoming 10 events:');
      events.map((event, i) => {
        const start = event.start.dateTime || event.start.date;
        console.log(`${start} - ${event.summary}`);
      });
    } else {
      console.log('No upcoming events found.');
    }
  });


}

So in above code, we are first finding the credentials from credentials.json file. I have simply hardcoded them for convenience in authorize()

let client = new OAuth2Client("484407463774-e7biatgmpns9jcpakr5g0sed8fab376u.apps.googleusercontent.com", "722_fI1u2abNM3tL-VbCuZfF", "http://localhost:1337/api/v1/oauthCallback");
        client.setCredentials({
          "access_token": "ya29.GluyBSUYvP_Gi4_SdJHabcJmXUjHnw34MfMBJ8tzROflqyR9dFMDOh_AYh9dmL4FSNDiva_nAcWYCM9m5jBwaL3pWfSm_wv0IybUUdebt66gDakdFXL0o8Mr-0Ge",
          "expiry_date": 1525551674971,
          "token_type": "Bearer",
          "refresh_token": "1/Ug8agC92PkJRXEDLP1inlHcAh4MBP1SLjNoylPJrmfg"
        });

But if I move the above lines in listEvents() like this:

const fs = require('fs');
const mkdirp = require('mkdirp');
const readline = require('readline');
const {google} = require('googleapis');
const OAuth2Client = google.auth.OAuth2;
const SCOPES = ['https://www.googleapis.com/auth/calendar.readonly'];
const TOKEN_PATH = 'credentials.json';

// Load client secrets from a local file.
fs.readFile('client_secret.json', (err, content) => {
  if (err) return console.log('Error loading client secret file:', err);
  // Authorize a client with credentials, then call the Google Drive API.
  authorize(JSON.parse(content), listEvents);
});

/**
 * Create an OAuth2 client with the given credentials, and then execute the
 * given callback function.
 * @param {Object} credentials The authorization client credentials.
 * @param {function} callback The callback to call with the authorized client.
 */
function authorize(credentials, callback) {
  const {client_secret, client_id, redirect_uris} = credentials.web;
  const oAuth2Client = new OAuth2Client(client_id, client_secret, redirect_uris[0]);

  // Check if we have previously stored a token.
  fs.readFile(TOKEN_PATH, (err, token) => {
    if (err) return getAccessToken(oAuth2Client, callback);
    oAuth2Client.setCredentials(JSON.parse(token));


    callback(null);
  });
}

/**
 * Get and store new token after prompting for user authorization, and then
 * execute the given callback with the authorized OAuth2 client.
 * @param {google.auth.OAuth2} oAuth2Client The OAuth2 client to get token for.
 * @param {getEventsCallback} callback The callback for the authorized client.
 */
 function getAccessToken(oAuth2Client, callback) {
  const authUrl = oAuth2Client.generateAuthUrl({
    access_type: 'offline',
    scope: SCOPES,
  });
  console.log('Authorize this app by visiting this url:', authUrl);
  const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
  });
  rl.question('Enter the code from that page here: ', (code) => {
    rl.close();
    oAuth2Client.getToken(code, (err, token) => {
      if (err) return callback(err);
      oAuth2Client.setCredentials(token);
      // Store the token to disk for later program executions
      fs.writeFile(TOKEN_PATH, JSON.stringify(token), (err) => {
        if (err) console.error(err);
        console.log('Token stored to', TOKEN_PATH);
      });
      callback(oAuth2Client).catch(console.error);
    });
  });
}

/**
 * Lists the next 10 events on the user's primary calendar.
 * @param {google.auth.OAuth2} auth An authorized OAuth2 client.
 */
function listEvents(auth) {
 // THIS DOES NOT WORK 
 let client = new OAuth2Client("480557463774-e7biatgmpns9jcpakran0sed8f55376u.apps.googleusercontent.com", "722_fBsu2ECNM3tL-VbCuZfF", "http://localhost:1337/api/v1/oauthCallback");
  client.setCredentials({
    "access_token": "ya29.GluyBSUYvP_Gi4_SdJHsuPJmXUjHdd34MfMBJ8tzROflqyR9dFMDOh_AYh9dmL4FSNDiva_nAcWYCM9m5jBwaL3pWfSm_wv0IybUUORbt66gDakdFXL0o8Mr-0Ge",
    "expiry_date": 1525551674971,
    "token_type": "Bearer",
    "refresh_token": "1/Ug8MhC92ddJRXEDLP1inlHcAh4MBP1SLjNoylPJrmfg"
  });

  const calendar = google.calendar({ version: 'v3', client });
  calendar.events.list({
    calendarId: 'primary',
    timeMin: (new Date()).toISOString(),
    maxResults: 10,
    singleEvents: true,
    orderBy: 'startTime',
  }, (err, {data}) => {
    if (err) return console.log('The API returned an error: ' + err);
    const events = data.items;
    if (events.length) {
      console.log('Upcoming 10 events:');
      events.map((event, i) => {
        const start = event.start.dateTime || event.start.date;
        console.log(`${start} - ${event.summary}`);
      });
    } else {
      console.log('No upcoming events found.');
    }
  });


}

Then it does not work any more and gives this error:

(node:95252) UnhandledPromiseRejectionWarning: TypeError: Cannot destructure property `data` of 'undefined' or 'null'.
    at calendar.events.list (C:\Users\rahulserver\Desktop\gcalapinodejs\quickstart.js:87:6)
    at C:\Users\rahulserver\Desktop\gcalapinodejs\node_modules\google-auth-library\build\src\transporters.js:74:17
    at <anonymous>
    at process._tickCallback (internal/process/next_tick.js:188:7)
(node:95252) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside o
f an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)
(node:95252) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections tha
t are not handled will terminate the Node.js process with a non-zero exit code.

IMO I am doing the same thing in either case. In first case, I am passing the client as a parameter to the callback. In second, I am passing null to the callback, and instantiating the oauth client in the callback itself. Not sure what “Mysterious” thing is happening in second approach that makes the code not work any more.

Maybe some bug in library itself? Or Something undocumented? <your detailed question and code samples go here>

Thanks!

Issue Analytics

  • State:closed
  • Created 5 years ago
  • Comments:6

github_iconTop GitHub Comments

9reactions
rahulservercommented, May 7, 2018

Nvm I figured it out.

  const calendar = google.calendar({ version: 'v3', client });

It was supposed to be

  const calendar = google.calendar({ version: 'v3', auth: client });

1reaction
linaizhongcommented, Apr 19, 2019

Sorry to bother you guys. I am testing this code as well. When I was asked to input the code for “Enter the code from that page here:”, I do not know what should we provide for the code. Could someone kindly let me know this? Thank you very much in advance.

Read more comments on GitHub >

github_iconTop Results From Across the Web

How to use async await with a callback function - Stack Overflow
Unfortunately the csv gets created before the data can be extracted from the document. I'm new to async/await but it seems like the...
Read more >
The journey to async/await - DEV Community ‍ ‍
A callback is a simple function that is passed as an argument to another function and will only execute when the "parent" function...
Read more >
Google Auth Library: Node.js Client
Start by acquiring a pre-authenticated oAuth2 client. */ async function main() { const oAuth2Client = await getAuthenticatedClient();
Read more >
Get Started with Flutter Authentication - Auth0
Learn how to add user authentication to Flutter apps using OAuth 2.0 and OpenID Connect.
Read more >
Using OAuth 2.0 for Web Server Applications | YouTube Data ...
Open the API Library in the Google API Console. ... Important: Do not store the client_secret.json file in a publicly-accessible location.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found