Getting a user object in a UI script

Kyle Ketterer1
Giga Contributor

Hello all,

I understand that UI scripts are not *recommended* at this point, however, for what I need to accomplish I believe it's the only way to get it done.

Basically, I need to detect a user's groups in a UI script and hide certain elements on any given page based on the user's groups. These elements are html objects contained within content blocks. Therefore, attaching roles to content blocks will not accomplish what I need to.

It appears that in my UI script the g_user object is not yet defined. Even when calling getActiveUser() it doesn't appear to create the object. g_user.userID returns undefined at that point.

The end goal is for me to be able to call g_user.hasRole() - or at the very least query sys_user_grmember using g_user.userID. I am aware of the possible overhead here, however, I feel like user object/data should be baseline available to us even when using deprecated UI scripts.

Is there any workaround for this issue? I am running Eureka.

Thanks

1 ACCEPTED SOLUTION

Ok, tested this in a demo instance...



UI Script


userHasRole('admin');


function userHasRole(role){


  var ga = new GlideAjax('CheckUserRole');


  ga.addParam('sysparm_name','u_hasRole');


  ga.addParam('sysparm_role',role);


  ga.getXMLWait();


  alert(ga.getAnswer());


}



Script Include


Name: CheckUserRole


Client Callable: Checked


var CheckUserRole = Class.create();


CheckUserRole.prototype = Object.extendsObject(AbstractAjaxProcessor, {


  u_hasRole: function() {


  var role = this.getParameter("sysparm_role");


  return gs.hasRole(role);


  }


});


View solution in original post

12 REPLIES 12

EDIT:



This works fine while impersonating. Please disregard that statement.


Well, my alert always returns "null".     Yes, I verified I have the role.   Any ideas?


Kalaiarasan Pus
Giga Sage

g_user object doesn't seem to work in ui script....


sshall
Mega Expert

I recently encountered the same issue in trying to implement custom dimensions for Google Analytics. I wanted to add a dimension based on user roles. There is a way to do it without a GlideAjax call, though I must say this is about as far into the weeds as you can get from a platform perspective.



View the page source within ServiceNow, and about 60 lines down you'll find:



window.NOW.user = {};


window.NOW.user.preferences = [];


window.NOW.user.roles = 'admin';


window.NOW.user.id = '6816f79cc0a8016401c5a33be04be441';


window.NOW.user.departmentID = 'a581ab703710200044e0bfc8bcbe5de8';


window.NOW.user.firstName = 'System';


window.NOW.user.lastName = 'Administrator';


window.NOW.user.name = 'admin';



Within your UI Script, you can reference these variables, in particular the window.NOW.user.roles variable, to get the list of roles for the current user.


Hey Scott,



It looks like cheat code. But it helped me. Thank you for sharing this.



Thanks