1

How can I add a new user to the ACL for a Google Calendar? I'm trying to send a POST HTTP request. Perhaps there is something wrong with the XML? The code below generates a server error (400). (Edit: Shows the oAuth).

//---------------------------------------------------------------
// Add a rule to the Access Control List for 'Fake Calendar 1.0'
//---------------------------------------------------------------
function addRule() {
  // Get Calendar ID, script user's email, and the API Key for access to Calendar API
  var calId = '12345calendar.google.com';
  var userEmail = Session.getActiveUser().getEmail();
  var API_KEY = 'ABC123';
  var newUserEmail = 'person@example.net';

  // Get authorization to access the Google Calendar API
  var apiName = 'calendar';
  var scope = 'https://www.googleapis.com/auth/calendar';
  var fetchArgs = googleOAuth_(apiName, scope);

  fetchArgs.method = 'POST';
  var rawXML = "<entry xmlns='http://www.w3.org/2005/Atom' " +
               "xmlns:gAcl='http://schemas.google.com/acl/2007'>" +
               "<category scheme='http://schemas.google.com/g/2005#kind' " +
               "term='http://schemas.google.com/acl/2007#accessRule'/>" +
               "<gAcl:role value='owner'/>" +
               "<gAcl:scope type='user' value='"+userEmail+"'/>" +
               "</entry>";

  fetchArgs.payload = rawXML;
  fetchArgs.contentType = 'application/atom+xml';

  // Get the requested content (the ACL for the calendar)
  var base = 'https://www.googleapis.com/calendar/v3/calendars/';
  var url = base + calId + '/acl?key=' + API_KEY;
  var content = UrlFetchApp.fetch(url, fetchArgs).getContentText();
  Logger.log(content);
}

//--------------------------------------------------------------
// Google OAuth 
//--------------------------------------------------------------
function googleOAuth_(name,scope) {
  var oAuthConfig = UrlFetchApp.addOAuthService(name);
  oAuthConfig.setRequestTokenUrl("https://www.google.com/accounts/OAuthGetRequestToken?scope="+scope);
  oAuthConfig.setAuthorizationUrl("https://www.google.com/accounts/OAuthAuthorizeToken");
  oAuthConfig.setAccessTokenUrl("https://www.google.com/accounts/OAuthGetAccessToken");
  oAuthConfig.setConsumerKey("anonymous");
  oAuthConfig.setConsumerSecret("anonymous");
  return {oAuthServiceName:name, oAuthUseToken:"always"};
}
KarBytes
  • 61
  • 8

2 Answers2

0

Have you gone through the oAuth authorization process before executing this piece of code. Your app has to be explicitly authorized before it can do anything significant with the Calendar API

Srik
  • 7,907
  • 2
  • 20
  • 29
0

Srik is right. You need to use oAuth Arguments in your UrlFetchApp. Given Reference URL shows few examples for using oAuth in Apps script to work with Google's REST APIs https://sites.google.com/site/appsscripttutorial/urlfetch-and-oauth

Waqar Ahmad
  • 3,716
  • 1
  • 16
  • 27