2
votes

Is it possible to obtain the User ID (instead of email address) in Google Apps Script using the Session service or similar.

I haven't seen any reference to it in GAS, but within GAE I am able to obtain the User ID from the Users API. The User ID is an identifier that uniquely identifies a user, even if the user changes their email address.

I am hoping to use the same in GAS.

2

2 Answers

3
votes

Is it possible to obtain the User ID (instead of email address) in Google Apps Script using the Session service or similar?

Yes, it's possible. You can obtain User IDs by leveraging the AdminSDK Directory API which is accessible from App Script via the Admin Directory Advanced Google Service.

Sample Usage:

// NOTE: Admin Directory Advanced Service must be enabled first.

// Get first page of user ids for users in domain
var userIds = AdminDirectory.Users.list({"domain":"www.example.com"}).users.map(function(user) { 
    return user.id; 
});
3
votes

Use the "advanced service" Drive REST API to query the About resource, which can return a more nuanced user object:

function getInfo() {
  var about = Drive.About.get();
  // Use the name, permissionId, email, etc
  var user = {
    name: about.name,
    permissionId: about.permissionId,
    driveUser: about.user,
    ....
  };

  return user;
}

Or the Drive.Permissions.getIdForEmail method if that is all you want.

If the automatic scope detection is too aggressive, you may try adding one of the .readonly scopes to your manifest instead: https://developers.google.com/drive/v2/reference/about/get#auth

Note: you will have to enable the advanced service client library, and its underlying API, before it can be used in your Apps Script project.

See also: