Pergunta

I am making a Google apps script on a spreadsheet that creates users on a domain submitted from a registeration form powered by Google forms, creating a user was easy using this method UserManager.createUser(username, firstname, lastname,password); but the problem that I'm facing is how to check if the user being inserted into the spreadsheet already exists. I checked over the internet specially at https://developers.google.com/apps-script/ but found nothing helpful.

Foi útil?

Solução

What about using a try catch block? Simple but should facilitate your need.

try{
    // Get an existing user
    var user = UserManager.getUser("delete.me");
}catch(e){
    // If user does not exist // i.e. error // create the user
    var newUser = UserManager.createUser('delete.me', 'Delete', 'Me', 'testing123');
}

Outras dicas

There is no direct API for it from Apps Script, but you can use the User Provisioning using OAuth 2 and UrlFetchApp. You can see some sample integration with the Audit API

Here are 2 versions of a script that gets all users in my domain, the second one uses the API that Arun mentioned and returns an XML document viewable in the logger (for this test version) that you could parse in a suitable way.

The other one (the first actually) uses UserManager service and shows the results in a spreadsheet. From there (using the array) it would be easy to check if a user already has an account.

here is the code :

function findUsers(s) {     
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet()
  sheet.getDataRange().clear()
  var users = UserManager.getAllUsers();
  var r = new Array();
//
  for( var i = 0 ; i < users.length ; i++ ){
    var Umail = users[i].getEmail(); 
    var UnomF = users[i].getFamilyName()
    var UnomP = users[i].getGivenName()

      if(users[i].getAgreedToTerms()){var Udejaconnect = 'oui'}else{var Udejaconnect = 'jamais'}
//
     r.push([UnomF,UnomP,Umail,Udejaconnect]);
  }   
  r.sort(function(x,y){
  var xp = x[0].toLowerCase();
  var yp = y[0].toLowerCase();
  Logger.log(xp+'   '+yp)
  return xp == yp ? 0 : xp < yp ? -1 : 1;//  sort on name ascending
}
)
  var header = ['Nom de famille','Prénom','Email','Déjà Connecté?']
    sheet.getRange(1,1,1,r[0].length).setValues([header]).setFontWeight('bold')
    .setBackground('silver').setBorder(true,true,true,true,true,true);
    sheet.getRange(2,1,r.length,r[0].length).setValues(r);
}

// new version provisioning API
//
function getUserData() {
  var base = "https://apps-apis.google.com/a/feeds/";
  var fetchArgs = googleOAuth_("provisioning", base);
  var url = base + "domain.name" + "/user/2.0"; 

  var result = UrlFetchApp.fetch(url,fetchArgs).getContentText()
  var xml = Xml.parse(result);
  Logger.log(result)
  var users = xml.feed.entry;

  var r = [['Login', 'Nom complet', "Droits d'admin.", 'Quota Emails', 'Compte suspendu']];
  for( var i in users ) 
            r.push([users[i].login.userName,
            users[i].name.givenName+' '+users[i].name.familyName,
            users[i].login.admin,
            users[i].quota.limit,
            users[i].login.suspended]);
  var s = SpreadsheetApp.getActiveSheet();
  s.clearContents();
  s.getRange(1, 1, r.length, r[0].length).setValues(r);

}


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"};
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top