User Object Cheat Sheet

Home/Scripting/User Object Cheat Sheet

User Object Cheat Sheet

N

o matter what system you’re working in, it is always critical to be able to identify information about the user who is accessing that system. Being able to identify who the user is, what their groups and/or roles are, and what other attributes their user record has are all important pieces of information that allow you to provide that user with a good experience (without giving them information they don’t need to have or shouldn’t have). ServiceNow gives administrators some pretty simple ways to identify this information in the form of a couple of user objects and corresponding methods. This article describes the functions and methods you can use to get information about the users accessing your system.



GlideSystem User Object

The GlideSystem (gs) user object is designed to be used in any server-side JavaScript (Business rules, UI Actions, System security, etc.). The following table shows how to use this object and its corresponding functions and methods.

Function/MethodReturn ValueUsage
gs.getUser()Returns a reference to the user object for the currently logged-in user.var userObject = gs.getUser();
gs.getUserByID()Returns a reference to the user object for the user ID (or sys_id) provided.var userObject = gs.getUser().getUserByID('employee');
gs.getUserName()Returns the User ID (user_name) for the currently logged-in user.
e.g. 'employee'
var user_name = gs.getUserName();
gs.getUserDisplayName()Returns the display value for the currently logged-in user.
e.g. 'Joe Employee'
var userDisplay = gs.getUserDisplayName();
gs.getUserID()Returns the sys_id string value for the currently logged-in user.var userID = gs.getUserID();
getFirstName()Returns the first name of the currently logged-in user.var firstName = gs.getUser().getFirstName();
getLastName()Returns the last name of the currently logged-in user.var lastName = gs.getUser().getLastName();
getEmail()Returns the email address of the currently logged-in user.var email = gs.getUser().getEmail();
getDepartmentID()Returns the department sys_id of the currently logged-in user.var deptID = gs.getUser().getDepartmentID();
getCompanyID()Returns the company sys_id of the currently logged-in user.var companyID = gs.getUser().getCompanyID();
getCompanyRecord()Returns the company GlideRecord of the currently logged-in user.var company = gs.getUser().getCompanyRecord();
getLanguage()Returns the language of the currently logged-in user.var language = gs.getUser().getLanguage();
getLocation()Returns the location of the currently logged-in user.var location = gs.getUser().getLocation();
getDomainID()Returns the domain sys_id of the currently logged-in user (only used for instances using domain separation).var domainID = gs.getUser().getDomainID();
getDomainDisplayValue()Returns the domain display value of the currently logged-in user (only used for instances using domain separation).var domainName = gs.getUser().getDomainDisplayValue();
getManagerID()Returns the manager sys_id of the currently logged-in user.var managerID = gs.getUser().getManagerID();
getMyGroups()Returns a list of all groups that the currently logged-in user is a member of.var groups = gs.getUser().getMyGroups();
isMemberOf()Returns true if the user is a member of the given group, false otherwise.Takes either a group sys_id or a group name as an argument.

if(gs.getUser().isMemberOf(current.assignment_group)){
//Do something...
}

var isMember = gs.getUser().isMemberOf('Hardware');

To do this for a user that isn't the currently logged-in user...

var user = 'admin';
var group = "Hardware";
if (gs.getUser().getUserByID(user).isMemberOf(group)){
gs.log( gr.user_name + " is a member of " + group);
}

else{
gs.log( gr.user_name + " is NOT a member of " + group);
}
gs.hasRole()Returns true if the user has the given role, false otherwise.if(gs.hasRole('itil')){ //Do something... }
gs.hasRole()Returns true if the user has one of the given roles, false otherwise.if(gs.hasRole('itil,admin')){
//If user has 'itil' OR 'admin' role then Do something...
}
hasRoles()Returns true if the user has any roles at all, false if the user has no role (i.e. an ess user).if(!gs.getUser().hasRoles()){
//User is an ess user...
}

It is also very simple to get user information even if the attribute you want to retrieve is not listed above by using a ‘gs.getUser().getRecord()’ call as shown here…

//This script gets the user's title
gs.getUser().getRecord().getValue('title');



g_user User Object

The g_user object can be used only in UI policies and Client scripts. Contrary to its naming, it is not truly a user object. g_user is actually just a handful of cached user properties that are accessible to client-side JavaScript. This eliminates the need for most GlideRecord queries from the client to get user information (which can incur a fairly significant performance hit if not used judiciously).

g_user Property or MethodReturn value
g_user.userNameUser name of the current user e.g. employee
g_user.firstNameFirst name of the current user e.g. Joe
g_user.lastNameLast name of the current user e.g. Employee
g_user.userIDsys_id of the current user e.g. 681ccaf9c0a8016400b98a06818d57c7
g_user.hasRole()True if the current user has the role specified, false otherwise. ALWAYS returns true if the user has the 'admin' role.

Usage: g_user.hasRole('itil')
g_user.hasRoleExactly()True if the current user has the exact role specified, false otherwise, regardless of 'admin' role.

Usage: g_user.hasRoleExactly('itil')
g_user.hasRoles()True if the current user has at least one role specified, false otherwise.

Usage: g_user.hasRoles('itil','admin')

It is often necessary to determine if a user is a member of a given group from the client as well. Although there is no convenience method for determining this from the client, you can get the information by performing a GlideRecord query. Here’s an example…

//Check to see if assigned to is a member of selected group
var grpName = 'YOURGROUPNAMEHERE';
var usrID = g_form.userID; //Get current user ID
var grp = new GlideRecord('sys_user_grmember');
grp.addQuery('group.name', grpName);
grp.addQuery('user', usrID);
grp.query(groupMemberCallback);
   
function groupMemberCallback(grp){
//If user is a member of selected group
    if(grp.next()){
        //Do something
        alert('Is a member');
    }
    else{
        alert('Is not a member');
    }
}

To get any additional information about the currently logged-in user from a client-script or UI policy, you need to use a GlideRecord query. If at all possible, you should use a server-side technique described above since GlideRecord queries can have performance implications when initiated from a client script. For the situations where there’s no way around it, you could use a script similar to the one shown below to query from the client for more information about the currently logged in user.

//This script gets the user's title
var gr = new GlideRecord('sys_user');
gr.get(g_user.userID);
var title = gr.title;
alert(title);



Useful Scripts

There are quite a few documented examples of some common uses of these script methods. These scripts can be found on the ServiceNow wiki.

By | 2014-07-02T18:42:12+00:00 February 25th, 2010|Categories: Scripting|Tags: , , , |26 Comments

About the Author:

Mark has worked in the IT industry since 2002 and with ServiceNow since 2007. He is the founder and creator of SN | Guru and the co-founder of Crossfuze, one of the worlds leading ServiceNow consulting partners. Prior to co-founding Crossfuze, he worked for ServiceNow as a Senior Architect on the Professional Services team. He has personally led dozens of successful implementations encompassing every part of the ServiceNow platform. He is also responsible for designing and developing groundbreaking ServiceNow solutions and best practices in the form of various applications, turnkey solutions, and integrations during his tenure at ServiceNow, Crossfuze and, of course, SN | Guru. These solutions are used today by ServiceNow administrators and consultants alike in hundreds of ServiceNow instances around the world!

26 Comments

  1. Joe February 26, 2010 at 4:55 am - Reply

    Thanks for the great tips… My personal favorite:

    gs.getUser().getRecord().getValue(‘title’);

    never knew you could do that, awesome!

    • Alex March 23, 2011 at 12:44 am - Reply

      I was looking for a way to get the default set to the User Time Zone. Looked everywhere and it was on my favorite site..!

      javascript:gs.getUser().getRecord().getValue(‘time_zone’);

      Thanks!

      • valor January 10, 2013 at 12:00 pm - Reply

        Note that if you use this method, and you have the time zone selector turned on, you may run into issues.
        The time zone selector sets the User’s Session TZ, but not their default.

        For more consistent results, use the following:
        var tzStr = gs.getSession().getTimeZoneName(); // “US/Pacific”
        var jTZ = gs.getSession().getTimeZone(); // sun.util.calendar.ZoneInfo java object. APIDoc linked below

        Java doc ZoneInfo api:
        http://www.docjar.com/docs/api/sun/util/calendar/ZoneInfo.html

  2. Wolfgang October 25, 2011 at 7:20 am - Reply

    Thank you for the great work… finally one place to get the information about the UserObject stuff…

    Just one note:

    – the hasRole() returns true, if the user has the role specified (e.g. hasRole(role)) OR the admin role.

    – to get a true/false for a specific role, use hasRoleExactly(role), which will only return true, if the user has the itil-role.

    • Mark Stanger October 25, 2011 at 8:04 am - Reply

      Thanks for the feedback. This method had some issues in the past (which is why I didn’t include it). It looks like it’s in the official ServiceNow doc now though so hopefully I’m safe in including it here :). I just added it to the article above.

  3. Andreas February 7, 2013 at 2:20 pm - Reply

    I looked at the Usage example for “isMemberOf()” and also checked the wiki article for the function “getUserByID” (http://wiki.servicenow.com/index.php?title=Getting_a_User_Object&redirect=no#Method_Detail) but I cannot get it to work.

    Is this function maybe retired?

    Some code I played with is:

    var usr = gs.getUserByID('guest');
    gs.print(JSUtil.type_of(usr)); //Result: "null"
    gs.print(usr.hasRoles()); //e.g. this GlideSystem function for the user object is not available. Result is "undefined"
     
    var usr2 = gs.getUser();
    gs.print(JSUtil.type_of(usr2)); //Result: "object"
    gs.print(usr2.hasRoles()); //here the GlideSystem function for the user object is available. Result is "true"
    • Mark Stanger February 7, 2013 at 5:23 pm - Reply

      I’m not having any luck with it either. I haven’t heard of it being retired, but you’ll probably need to contact ServiceNow support to see. Please post back here with your findings.

      • Andreas February 8, 2013 at 7:45 am - Reply

        Here we go: first we have to initialize a variable with “getUser()”. After that we can get any user object using it’s sys_id or UserID.
        Below the updated code to make the example work:

        //get object for specific user
        var usr = gs.getUser();
        usr = usr.getUserByID('beth.anglin'); //instead of UserID it is possible to use the sys_id

        var group = 'Service Desk';
        if (usr.isMemberOf(group)) {
            gs.log(usr.getName() + " is a member of " + group);
        } else {
            gs.log(usr.getName() + " is NOT a member of " + group);
        }
        • Mark Stanger February 8, 2013 at 8:12 am - Reply

          Thanks Andreas! I’ve updated the table above with this solution.

  4. Abdul Fathah April 12, 2013 at 7:21 am - Reply

    is it possible to check whether he/she is one of the member of Assignment group? Please guide me friends.

  5. Martin Robinson October 8, 2013 at 6:49 am - Reply

    Hi Mark,

    Thanks for all the info, very handy and interesting indeed. One question though, is there a method like the var hasRoleExactly that will work server-side? I can get it to work okay client-side but that’s it.

    Thanks Martin

    • Mark Stanger October 8, 2013 at 8:22 am - Reply

      I don’t know of any built-in way of doing this, but you could always query the ‘sys_user_has_role’ table directly or create an on-demand script include that would allow you to call it in a shorthand way.

      • Martin October 8, 2013 at 8:25 am - Reply

        Thanks Mark, I thought that might be the alternative 🙂

        Cheers

  6. Shane C January 29, 2014 at 11:28 am - Reply

    How does one get the client’s business number? The wiki shows how to get the mobile number, but not the business number.

    http://wiki.servicenow.com/index.php?title=Getting_a_User_Object

    • Mark Stanger January 29, 2014 at 12:28 pm - Reply

      Up above I explain for both back-end and client-side code how you can get any attribute even if there’s not a specific function defined. You can get any attribute from the back-end like this.
      gs.getUser().getRecord().getValue(‘title’);

      • Shane C January 29, 2014 at 12:32 pm - Reply

        If I understand that correctly, then I could use this in a script of a workflow that works on a condition of an incident being submitted, to set the value of phone for the incident, to the user’s business phone, with the following script?

        current.u_cos_contact_no = gs.getUser().getRecord().getValue(‘phone’);

        • Mark Stanger January 29, 2014 at 12:34 pm - Reply

          Correct. As long as ‘phone’ is the name of the field you want to pull the value from.

          • Shane C January 29, 2014 at 12:38 pm - Reply

            On my incident form, “Contact Phone” variable is called u_cos_contact_no.

            In my client’s user form, “Business Phone” variable is called phone.

            For my workflow, would I want to do a custom script, or simply put do a Set Values, and then use javascript:gs.getUser().getRecord().getValue(‘phone’) ?

          • Shane C January 29, 2014 at 12:44 pm - Reply

            An update, I made a script step in the workflow, and the following works in my system:

            var businessphone = gs.getUser().getRecord().getValue(‘phone’);
            current.u_cos_contact_no = businessphone;

            Now to try it as a Set Value step in the workflow, with javascript:gs.getUser().getRecord().getValue(‘phone’);
            Not sure if it will work, but it’s work a shot to eliminate extra steps in the workflow.

          • Shane C January 29, 2014 at 12:48 pm - Reply

            Sorry to keep filling this up, but I can’t figure out how to edit my previous post.

            On further testing, javascript:gs.getUser().getRecord().getValue(‘phone’) does work in a Set Value step of the workflow, however it pulls the phone number of the user logging in the incident, not the phone number of who the “client” has been set to for the incident. Any way to modify this?

            Much thanks Mark

  7. Vivek March 8, 2017 at 5:13 am - Reply

    Hi Mark,

    I wanted to know if we could access the company of the user involved, using the g_user field.

    Thanks and Regards,
    Vivek

    • Mark Stanger March 8, 2017 at 1:33 pm - Reply

      Sure. Take a look at the ‘title’ example at the bottom of the article. It shows how you can use a GlideRecord query to get any additional information about the user (including company) that you want.

Leave A Comment