Search code examples
javascriptnode.jsgoogle-calendar-apigoogle-oauthgoogle-hangouts

Is it possible to do google API sign in from the server side and pass the result to user?


I have an app that clients can pick a time to book a video appointment and I just want to send them the Google Hangouts Meet link. For this purpose I'm using google calendar API in my JavaScript code from this document https://developers.google.com/calendar/create-events it works and I can create the link fine. But my question is that is there any way that I can create the link based on the time that they select on server side (node js) with a Gsuite account and just send them the link at the end? (I don't want to create event on their Google calendar or send them notification from Google) I don't want the user to prompt with Google login page for authorization. I just need to create the link and send it to the client.Is this possible? I appreciate any suggestion.


Solution

  • Using the code from this guide to auhtenticate with a service account and searching in this examples from the google-auth nodejs repository to see how to set the subject parameter which is the used to impersonate a user, I was able to get the authenticated JWT auth client object which can be used to make google API requests like listing the events of the impersonated user:

    let google = require('googleapis').google;
    let privatekey = require("./[JSON-FILENAME].json");
    
    // configure a JWT auth client
    let jwtClient = new google.auth.JWT(
        privatekey.client_email,
        null,
        privatekey.private_key,
        ['https://www.googleapis.com/auth/calendar'],
        '[EMAIL-OF-USER-TO-IMPERSONATE]'
    );
    //authenticate request
    jwtClient.authorize(function (err, tokens) {
        if (err) {
            console.log(err);
            return;
        } else {
            console.log("Successfully connected!");
        }
    });
    
    listEvents(jwtClient);
    
    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, res) => {
            if (err) return console.log('The API returned an error: ' + err);
            const events = res.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.');
            }
        });
    }