I have some confusion about integrating OAuth 2 flow (Google APIs) into my app. I have declared a Oauth2 client variable (globally) as shown below:
const {gapi} = require('googleapis');
var auth2;
/**
* Initializes the Sign-In client.
*/
var initClient = function() {
gapi.load('auth2', function(){
/**
* Retrieve the singleton for the GoogleAuth library and set up the
* client.
*/
auth2 = gapi.auth2.init({
client_id: 'CLIENT_ID.apps.googleusercontent.com'
});
// Attach the click handler to the sign-in button
auth2.attachClickHandler('signin-button', {}, onSuccess, onFailure);
});
};
If I were to use Google Calendar API, I would do this:
const doSomethingWithGCalendar = (token) => {
auth2.setCredentials({
access_token: token
});
const calendar = google.calendar({version: 'v3', auth: auth2});
// Execute some actions here
}
I am confused about how node.js handles this. After all, the auth2 client variable is globally declared (I picture in my head as one, single instance). However, there will be multiple users using my app, so the line .setCredentials and subsequent Google Calendar API calls will run, probably in multiple threads and concurrently, I'm assuming.
They should be running concurrently in the node.js server, but they're using the same globally declared variable auth2. How would that work ?
Should I, instead, declare a local variable inside doSomethingWithGCalendar() like this:
const doSomethingWithGCalendar = (token) => {
const auth2 = new OAuth2Client(
{client_id: 'CLIENT_ID.apps.googleusercontent.com'}
);
// Set Credentials/tokens and then run Google Calendar API operations ...