0

I am trying to create events using the google calendar api however, I am having trouble with the authorization. I created a google login, a different way so I am not sure the best way to go about connecting to the google calendar, this is my hwapi file:

var Homework = require('../models/homework');
var mongoose = require('mongoose');
var google = require('googleapis');
var jwt = require('jsonwebtoken');
var secret = 'check123';
var googleAuth = require('google-auth-library');
var GoogleStrategy = require('passport-google-oauth').OAuth2Strategy;


var googleAuth = require('google-auth-library');

// function authorize(credentials, callback) {
//   var clientSecret = credentials.installed.client_secret;
//   var clientId = credentials.installed.client_id;
//   var redirectUrl = credentials.installed.redirect_uris[0];

//   var oauth2Client = new auth.OAuth2(clientId, clientSecret, redirectUrl);

//   // Check if we have previously stored a token.
//   fs.readFile(TOKEN_PATH, function(err, token) {
//     if (err) {
//       getNewToken(oauth2Client, callback);
//     } else {
//       oauth2Client.credentials = JSON.parse(token);
//       callback(oauth2Client);
//     }
//   });
// }
//mongoose.connect('mongodb://localhost:27017/test');
var auth = new googleAuth();


  var clientSecret = '4etHKG0Hhj84bKCBPr2YmaC-';
  var clientId = '655984940226-dqfpncns14b1uih73i7fpmot9hd16m2l.apps.googleusercontent.com';
  var redirectUrl = 'http://localhost:8000/auth/google/callback';
  var auth = new googleAuth();
  var oauth2Client = new auth.OAuth2(clientId, clientSecret, redirectUrl);
    //console.log(auth);    



module.exports = function(hwRouter,passport){

    hwRouter.post('/homeworks', function(req, res){
        var homework = new Homework();
        homework.summary = req.body.summary;
        homework.description = req.body.description;
        homework.startDate = req.body.startDate;
        homework.endDate = req.body.endDate;
        if(req.body.summary == null || req.body.summary == '' || req.body.description == null || req.body.description == '' || req.body.startDate == null || req.body.startDate == '' || req.body.endDate == null || req.body.endDate == ''){
            res.send("Ensure all fields were provided!");
        }
        else{
            homework.save(function(err){
                if(err){
                    res.send('Homework already exists!');
                }
                else{
                    res.send('Homework created successfully!');
                }
            });
        }
    })


    var calendar = google.calendar('v3');
    hwRouter.get('/retrieveHW/:summary', function(req,res){
        Homework.find({},function(err,hwData){
            console.log(hwData);
            var event = {
              'summary': 'Google I/O 2015',
              'location': '800 Howard St., San Francisco, CA 94103',
              'description': 'A chance to hear more about Google\'s developer products.',
              'start': {
                'dateTime': '2015-05-28T09:00:00-07:00', 
                'timeZone': 'America/Los_Angeles',
              },
              'end': {
                'dateTime': '2015-05-28T17:00:00-07:00',
                'timeZone': 'America/Los_Angeles',
              },
              'recurrence': [
                'RRULE:FREQ=DAILY;COUNT=2'
              ],
              'attendees': [
                {'email': 'lpage@example.com'},
                {'email': 'sbrin@example.com'},
              ],
              'reminders': {
                'useDefault': false,
                'overrides': [
                  {'method': 'email', 'minutes': 24 * 60},
                  {'method': 'popup', 'minutes': 10},
                ],
              },
            };

console.log(auth)
        calendar.events.insert({

          auth: auth,
          calendarId: 'primary',
          resource: event,
        }, function(err, event) {
          if (err) {
            console.log('There was an error contacting the Calendar service: ' + err);
            return;
          }
          console.log('Event created: %s', event.htmlLink);
        });

            res.json({success: true, message: "successfull retrieved the homework!"});
        }); 

    })

    return hwRouter;
}

As you can see Ive tried using some of the code that the goog api has provided just to make sure I can connect to it. The part my code gets stuck is I believe when I pass it the auth: auth in the calendar.event.create portion. it gives me the error: authClient.request is not a function. any advice would help thanks!

1 Answers1

0

Try following the JavaScript sample:

/**
       *  Initializes the API client library and sets up sign-in state
       *  listeners.
       */
      function initClient() {
        gapi.client.init({
          discoveryDocs: DISCOVERY_DOCS,
          clientId: CLIENT_ID,
          scope: SCOPES
        }).then(function () {
          // Listen for sign-in state changes.
          gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus);

          // Handle the initial sign-in state.
          updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get());
          authorizeButton.onclick = handleAuthClick;
          signoutButton.onclick = handleSignoutClick;
        });
      }

      /**
       *  Called when the signed in status changes, to update the UI
       *  appropriately. After a sign-in, the API is called.
       */
      function updateSigninStatus(isSignedIn) {
        if (isSignedIn) {
          authorizeButton.style.display = 'none';
          signoutButton.style.display = 'block';
          listUpcomingEvents();
        } else {
          authorizeButton.style.display = 'block';
          signoutButton.style.display = 'none';
        }
      }

In this code, after the initClient() runs, the gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus); listens for any state changes. updateSigninStatus function handles if initClient() successfully logged in or not. If yes, it call the listUpcomingEvents() function, in your case you will call the create event function.

Here is a related SO post that can help you with a JS client library code implementation.

Hope this helps.

Community
  • 1
  • 1
Mr.Rebot
  • 6,703
  • 2
  • 16
  • 91