How do I getGivenName() of getActiveUser()
Asked Answered
K

6

15

Each user on the domain initiates a simple script we run for leave entitlements but we want the welcome message to be "Hi First Name," however the script doesn't seem to be able to fetch getGivenName() from getActiveUser() for a standard user.

Is there a way?

Kana answered 22/2, 2013 at 4:3 Comment(0)
M
16

As noted in comments, and in Documentation, the UserManager Service is only accessible by Domain Administrators.

Here's an alternative. Domain Users may have themselves in their own contacts, so how about a best-effort attempt at finding themselves there?

/**
 * Get current user's name, by accessing their contacts.
 *
 * @returns {String} First name (GivenName) if available,
 *                   else FullName, or login ID (userName)
 *                   if record not found in contacts.
 */
function getOwnName(){
  var email = Session.getEffectiveUser().getEmail();
  var self = ContactsApp.getContact(email);

  // If user has themselves in their contacts, return their name
  if (self) {
    // Prefer given name, if that's available
    var name = self.getGivenName();
    // But we will settle for the full name
    if (!name) name = self.getFullName();
    return name;
  }
  // If they don't have themselves in Contacts, return the bald userName.
  else {
    var userName = Session.getEffectiveUser().getUsername();
    return userName;
  }
}
Malvina answered 26/3, 2013 at 2:44 Comment(2)
It turns out ContactsApp is ridiculously slow. Don't use this unless you have to. – Downward
ContactsApp is deprecated since 2023. Use the People service instead. – Greeley
B
6

In Apps Script, I was able to get this information using the About REST API: https://developers.google.com/drive/v2/reference/about/get

var aboutData = DriveApp.About.get();
var userEmail = aboutData["user"]["emailAddress"];
var userDisplayName = aboutData["user"]["displayName"];
Brittnee answered 20/3, 2017 at 2:3 Comment(2)
Drive.About.get() isn't defined in Apps Script? ReferenceError: Drive is not defined πŸ˜• – Anemometry
@Anemometry Add Drive as a Service in the left hand tab – Randallrandan
P
2

You can get a user name but first you have to create a domain user using the provisioning api. You can enable the API by logging in to your admin account, and select Domain settings and the User settings tab to select the checkbox enabling the Provisioning API. Read more about it here

You can then use

   user = user.getgivenName()
Prognathous answered 22/2, 2013 at 4:44 Comment(1)
What you are saying is for administrators only. I'm talking about standard domain users accessing a script without administrative privileges. They are standard users so UserManager.getUser(Session.getActiveUser()).getGivenName(); doesn't work unless you are an admin. How do I get a standard user to access this? – Kana
M
2

Since the UserManager Service is only available to a Domain Administrator, you could publish a service as the administrator, that serves user's Given Names, and invoke that from the user-run script using the UrlFetchApp.

The UserName Service

Refer to the Content Service Documentation for the background information this is based upon.

The service accepts a parameter, userName, which it uses to perform a lookup as the administrator.

Paste the following code into a script, then deploy the script as a web service. This must be done by a Domain Administrator, as the service access the UserManager Service, but the script must be made accessible by all users in the domain. (Since I'm not an admin in my domain, I cannot access the UserManager, so I've included a domain-user-invokable line for testing, calling the getOwnName() function I described in my first answer.)

Remember to invoke doGet() from the debugger to go through the authorization before accessing the published service.

/**
 * When invoked as a Web Service running as Domain Administrator, 
 * returns the GivenName of the requested user.
 * 
 * @param {String} userName= Should be set to Session.getEffectiveUser().getUsername().
 */
function doGet(request) {
  //return ContentService.createTextOutput(getOwnName()); // for testing by non-admin user

  var userName = request.parameters.userName;
  var givenName = UserManager.getUser(userName).getGivenName();

  return ContentService.createTextOutput(givenName);
}

Invoke service using UrlFetch

Refer to Using External APIs for an explanation of how to make use of the service written in the previous section. I'll show how to access the service from another script, but remember that you can also do this from web pages within your domain.

We will use UrlFetchApp.fetch() to get our service to return the user's first name as a String.

The service was written to accept one parameter, userName, and we append this to the url, in the form userName=<string>.

With the URL built, we fetch(), then retrieve the name from the response. While this example returns just the name, you may choose to change the service to return the complete "Hello User" string.

function testService() {
  var domain = "my-google-domain.com";
  var scriptId = "Script ID of service";
  var url = "https://script.google.com/a/macros/"+domain+"/s/"+scriptId+"/exec?"
     + "userName="+Session.getEffectiveUser().getUsername();
  var response = UrlFetchApp.fetch(url);
  var myName = response.getContentText();
  debugger;  // pause in debugger
}
Malvina answered 26/3, 2013 at 3:47 Comment(0)
S
0

Another potential way of getting the display name on a gmail account is to find a Draft email in the GmailApp, and get the From header, which may have the full name. Some drafts might be setup with no display name in gmail, in which case the From header will only be the email address, but typically the From header is in the format: Firstname Lastname <[email protected]>

This code should get you the string above from the first gmail Draft: (note this will probably throw an exception if there are no drafts, so check that first.)

GmailApp.getDrafts()[0].getMessage().getHeader("From")

Ref: https://developers.google.com/apps-script/reference/gmail/gmail-message#getHeader(String)

Ref: https://www.ietf.org/rfc/rfc2822.txt

Strained answered 25/6, 2019 at 20:55 Comment(0)
A
0

The User class provides access to only one method which is the getEmail method. So, the easiest way to get user details within Apps Script would be via an API call to the https://www.googleapis.com/oauth2/v2/userinfo endpoint.

Example:

const api = 'https://www.googleapis.com/oauth2/v2/userinfo';
const query = UrlFetchApp.fetch(api, {
  headers: {
    Authorization: 'Bearer ' + ScriptApp.getOAuthToken(),
  },
});
const response = JSON.parse(query.getContentText());

User data such as name, email, picture etc will be contained in the response object.

ScriptApp.getOauthToken method gets token for the effective user and hence will work for all the users.

Akela answered 25/3 at 9:37 Comment(0)

© 2022 - 2024 β€” McMap. All rights reserved.