Search code examples
google-apps-scriptoauth-2.0google-appsgoogle-admin-sdkgoogle-directory-api

Creating a group with Admin SDK Directory API in Google Apps Script doesn't work "On form submit"


I've read through all of the relevant pages in the Admin ADK Directory API documentation and several questions on stackoverflow, and I'm still stuck.

I am the super admin of my Google Apps domain, and I want users in my domain to be able to create their own Google Groups. I made a Google Form where the user specifies the name and email of the group. Then the Google Form Responses sheet has an "On form submit" trigger that invokes my code to create the group.

This code works when I run createGroupTest() from the Script Editor. It creates the group in my Google apps domain immediately.

This code does not work when the "On form submit" trigger runs the onFormSubmit(e) function. I get the email from the catch(e) saying Exception: Failed to authenticate for service: Groups.

Does anyone know what is causing the oauth authentication to work from within the Script Editor but not when invoked by the onFormSubmit function?

function onFormSubmitTest() {
 
  var t = new Date();
  t = t.getTime();
  
  onFormSubmit([t, "AAA Test Group " + t], ["aaa.testgroup." + t + "@mydomain.com"], ["me@mydomain.com"]);
  
}

var consumerKey = "mydomain.com";
var consumerSecret = "xxxxxxxxxxxxxxxxxxxxxxxx";
var domainName = "mydomain.com";

function onFormSubmit(e) {
  
  var timestamp  = e.values[0];
  var groupName  = e.values[1];
  var groupEmail = e.values[2];
  var owner      = e.values[3];
  
  owner = owner.split("@")[0];
  
  var description = 'test';
  
  var requestBody = {email: groupEmail, name: groupName, description: description};
             
  var scope = "https://www.googleapis.com/auth/admin.directory.group";
  
  var fetchArgs                = googleOAuth_("Groups", scope);
  fetchArgs.method             = "POST";
  fetchArgs.contentType        = "application/json";
  fetchArgs.payload            = JSON.stringify(requestBody);
  fetchArgs.muteHttpExceptions = true;
   
  var url = 'https://www.googleapis.com/admin/directory/v1/groups?key=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
  
  UrlFetchApp.fetch(url, fetchArgs);

}
 

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(consumerKey);
  oAuthConfig.setConsumerSecret(consumerSecret);
  return {oAuthServiceName:name, oAuthUseToken:'always'};
}

Solution

  • I figured it out: I had failed to include the domain extension in the groupEmail string (because my Google Form only asks the user to fill in the group email name without the domain extension).