1

I created a script to be run for all users. I'm the admin.

(The script updates user's contacts).

I created a service accounts with contacts and gmail permissions.

How do I run the script for each user?

I don't want the user to do anything.

Berry Tsakala
  • 15,313
  • 12
  • 57
  • 80

1 Answers1

0

To use service-accounts in Apps Script, you need to use the apps-script-oauth2 library

  • Also, to act on behalf of other users, you need to enable and use domain-wide delegation.

  • This allows the service account to impersonate any domain user. The code for creating a impersonated service object would look like this:

function getService(user) {
  return OAuth2.createService(SOME NAME)
  .setTokenUrl('https://accounts.google.com/o/oauth2/token')
  .setPrivateKey(YOUR PRIVATE_KEY)
  .setIssuer(YOUR CLIENT_EMAIL)
  .setSubject(user) // the user you want to impersonate - you can call the function from a loop to perform calls for multiple users
  .setPropertyStore(PropertiesService.getScriptProperties())
  .setParam('access_type', 'offline')
  .setScope(YOUR SCOPES);
}
  • Then use the service object within your main function where you can make calls to the desired API with Urlfetch requests and the service account token:
var service = getService(user);
    
    if (service.hasAccess()) {
      Logger.log("service has access");
      var url = "the endpoint you are interested in";
      var headers ={
        "Authorization": 'Bearer ' + service.getAccessToken()
      };       
      var options = {
        'headers': headers,
        'method' : 'get',
        'muteHttpExceptions': true    
      };      
      var response=UrlFetchApp.fetch(url, options).getContentText();
  • For more information, see e.g. this sample that list all domain users and looping through those performs an action on behalf on each user.
ziganotschka
  • 25,866
  • 2
  • 16
  • 33