Lesson 2
Fetch detail of logged in user
To fetch details of the currently logged-in user in ServiceNow, you can use the gs.getUser() method in server-side scripts or the g_user object in client-side scripts. These methods provide access to the user object, which contains various attributes like user ID, name, email, and more.
Server-side:
gs.getUser(): This method returns a GlideUser object representing the currently logged-in user.gs.getUserID(): Returns the sys_id (unique identifier) of the logged-in user.gs.getUserName(): Returns the user name of the logged-in user.- Example:
JavaScript
var user = gs.getUser(); var userID = user.getID(); var userName = user.getName(); var userEmail = user.getEmail(); gs.info("User ID: " + userID + ", Name: " + userName + ", Email: " + userEmail);
Client-side:
g_user: This object provides access to user information in client scripts (e.g., UI scripts, client scripts).g_user.userID: Returns the sys_id of the logged-in user.g_user.userName: Returns the user name of the logged-in user.- Example:
JavaScript
var userID = g_user.userID; var userName = g_user.userName; alert("User ID: " + userID + ", Name: " + userName);
Accessing specific user details:
- You can access other user attributes like
firstName,lastName,department,location, etc., by using the corresponding methods on theGlideUserobject (server-side) or accessing them directly on theg_userobject (client-side). - For example:
user.getFirstName()(server-side)user.getDepartment()(server-side)g_user.location(client-side)
Important Notes:
- Always use the appropriate method for the context (server-side or client-side).
- For accessing user roles, you can use
gs.getUser().hasRole('role_name')on the server-side org_user.hasRoleExactly('role_name')on the client-side. - To check group membership, use
gs.getUser().isMemberOf('group_name_or_sys_id')on the server-side.
