Skip to content

Instantly share code, notes, and snippets.

@wave-inguane
Last active Sep 28, 2021
Embed
What would you like to do?
hasRoles
ICONS SEE PAGE 11700 & ALL g_form API
//-------------------------------------------------------------
Name: Hide Activity Formatter on Form based on Role
Type: Client Script
Table: Task
Description: This removes the activity section on task forms for anyone who doesn't have the admin role.
Parameters:
Script:
//---------------------------------------------------------------------------------------------
function onLoad() {
//hide the activity section for users that do not have the admin role
var isAdmin = g_user.hasRole('admin'); //Check if user has admin role
if (!isAdmin) {
//activity section does not have an id
//get all of the TD tag elements in the document
var refs = document.getElementsByTagName("TD");
if (refs) {
for (var i = 0; i < refs.length; i++) {
var ref = refs[i];
var inner = ref.innerHTML;
//check for the ID of the activity section label
if (inner.indexOf("formatter.incident_activity.xml") > 0) {
ref.style.display = 'none';
}
}
}
}
}
//---------------------------------------------------------------
//
//--------------------------------------------------------------
function onLoad() {
var vincident_state = g_form.getValue('incident_state');
var isItil = g_user.hasRole('itil');
var isAdmin = g_user.hasRole('admin');
var incidentClosed = false;
if (vincident_state == 7 || vincident_state == 5) {
incidentClosed = true;
}
var dArray = new Array();
var di = 0;
var email_icon = true;
var attachment_icon = true;
var lookup_icon = true;
var infoBox_icon = true;
var calendar_icon = true;
if (incidentClosed) {
email_icon = false;
attachment_icon = false;
lookup_icon = false;
infoBox_icon = false;
calendar_icon = false;
email_icon = false;
}
if (!isAdmin && (!email_icon || !attachment_icon || !lookup_icon ||
!infoBox_icon || !calendar_icon)) {
var refs = document.getElementsByTagName("a");
if (refs) {
for (var i = 0; i < refs.length; i++) {
var ref = refs[i];
var inner = ref.innerHTML;
if (!attachment_icon && inner.indexOf("attachment.gifx") >
0) {
ref.style.display = 'none';
}
if (!email_icon && inner.indexOf("email.gifx") > 0) {
ref.style.display = 'none';
}
if (!lookup_icon && inner.indexOf("reference_list.gifx") >
0) {
ref.style.display = 'none';
}
if (!infoBox_icon && inner.indexOf("log.gifx") > 0) {
ref.style.display = 'none';
}
if (!calendar_icon && inner.indexOf("small_calendar.gifx") >
0) {
ref.style.display = 'none';
}
}
var form = document.getElementById('incident.do');
if (form) {
for (var x = 0; x < form.elements.length; x++) {
form.elements[x].disabled = true;
}
alert('This incident is closed and can only be updated by an administrator');
}
}
}
}
//-----------------------------------------------------------
// Getting a User Object
//------------------------------------------------------------
var ourUser = gs.getUser();
ourUser.isMemberOf('Capacity Mgmt');
myUserObject.getUserRoles();
myUserObject.getRoles() -- returns all of the roles of the current user
myUserObject.getMyGroups();-- an iterator that returns a list of all groups to which the current user belongs (takes no argument). For an
example of how to consume an iterator, see Examples of Extracting the Contents of an Iterator into an
Array. getMyGroups() only returns groups that are active.
myUserObject.isMemberOf()-- returns true or false if the current user is a member of the provided group (takes a group name or sys_id
as its argument). isMemberOf() returns false if the group is inactive, even if the user is a member.
//-----------------------------------------------------------
//
//-----------------------------------------------------------
var groupsArray = gs.getUser().getMyGroups().toArray();
OR
function returnCurrentUserGroup(){
var myUserObject = gs.getUser();
var myUserGroups = myUserObject.getMyGroups();
var groupsArray = new Array();
var it = myUserGroups.iterator();
var i=0;
while(it.hasNext()){
var myGroup = it.next();
groupsArray[i]=myGroup;
i++;
}
return groupsArray;
}
var test = returnCurrentUserGroup();
gs.print(test[0]);
//---------------------------------------------------------------
hasRoleInGroup(Object, Object)
Determines if the current user has the specified role within a specified group.
Input Fields
Parameters:
The name of the role to check for.
A GlideRecord or the sys_id of the group to check within.
Output Fields
Returns: Returns true if all of the following conditions are met:
1. The logged-in user HAS the role in question
2. The "Granted by" field on the user role record is set to the specified group
3. The "inherited" field on the user role record is false
//----------------------------------------------------------------------
var group = new GlideRecord('sys_user_group');
group.addQuery('name', 'GROUP_NAME');
group.setLimit(1);
group.query();
if (group.next()) {
if (gs.hasRoleInGroup('role_name', group)) {
gs.print('User has role in group');
} else {
gs.print('User does NOT have role in group');
}
}
//-----------------------------------------------------------
//
//-----------------------------------------------------------
For example, users without the admin role may lose read access
to reports because of security constraints.
Because the Report Security plugin overrides ACL customizations,
it is not enabled by default upon upgrade. You
must enable it manually.
//-----------------------------------------------------------
// Users with the role "newRole" will not have access
//-----------------------------------------------------------
function incidentDisplayFilter() {
if (gs.getUser().hasRoles() && !gs.hasRole("newrole")) {
answer = true;
} else {
answer = false;
}
if (gs.hasRole("admin")) {
answer = true;
}
//-----------------------------------------------------------
//
//-----------------------------------------------------------
var grpList = gs.getUser().getMyGroups();
var myGrps = '';
for (var i = 0; i != grpList.size(); i++) {
if (i != 0) myGrps += ',';
myGrps += grpList.get(i);
}
var myUserId = gs.getUserID();
var gr = new GlideRecord('sys_report_users_groups');
gr.addQuery('report_id', current.getUniqueValue());
var qc = gr.addQuery('user_id', myUserId);
if (myGrps != '')
qc.addOrCondition('group_id', 'IN', myGrps);
gr.query();
if (gr.getRowCount() > 0)
return true;
return false;
}
//--------------------------------------------------------------
//
//--------------------------------------------------------------
function onLoad() {
var yesRole = g_user.hasRoles();
if (yesRole)
alert('true');
else
alert('not true');
}
//------------------------------------------------------------
//
//------------------------------------------------------------
if (!gs.hasRole("admin") && !gs.hasRole("groups_admin") &&
gs.getSession().isInteractive()) {
var qc = current.addQuery("u_hidden", "!=", "true"); //cannot see
hidden groups...
qc.addOrCondition("sys_id", "javascript:getMyGroups()"); //...unless
in the hidden group
}
//------------------------------------------------------------------
// isAdmin
//------------------------------------------------------------------
function onLoad(){
var isAdmin = g_user.hasRole('admin');
if (isAdmin)
alert('Current user is an admin');
else
alert('Current user is NOT an admin');
}
//------------------------------------------------------------
//
//------------------------------------------------------------
function onLoad() {
var isItil = g_user.hasRoleExactly('itil');
if (isItil)
alert('Current user has this exact role');
else
alert('Current user does NOT have this exact role');
}
//-----------------------------------------------------------
//
//-----------------------------------------------------------
function onLoad() {
var isOK = g_user.hasRoleFromList("itil, maint");
if (isOK)
alert('true');
else
alert('not true');
}
//----------------------------------------------------------
//
//----------------------------------------------------------
var userRoleGA = new GlideAggregate('sys_user_has_role');
userRoleGA.groupBy('user');
userRoleGA.groupBy('role');
userRoleGA.query();
var userRoleGR;
while (userRoleGA.next()) {
// Fetch the records for this user/role pair
userRoleGR = new GlideRecord('sys_user_has_role');
userRoleGR.addQuery('user', userRoleGA.user);
userRoleGR.addQuery('role', userRoleGA.role);
userRoleGR.query();
userRoleGR.next(); // Skip the first result
while (userRoleGR.next()) { // delete the rest
userRoleGR.deleteRecord();
}
}
//data.canEdit = data.canView = gs.getUser().isMemberOf('Program Managers');
//gs.addInfoMessage(data.canView +" : "+gs.getUserDisplayName());
//data.canView = gs.getUser().isMemberOf(options.group+'');
//data.canView = gs.getUser().hasRole('x_smart.program_manager');
//data.canView = gs.getUser().isMemberOf('Program Managers');
//gs.addInfoMessage(data.canView +" : "+gs.getUserDisplayName());
/*
if(gs.getUser().hasRole('admin') || gs.getUser().isMemberOf('Service Liasion'))
{
//data.canView = true;
//data.canEdit = false;
}
*/
//data.canEdit
var userRoleGA = new GlideAggregate('sys_user_has_role');
userRoleGA.groupBy('user');
userRoleGA.groupBy('role');
userRoleGA.query();
var userRoleGR;
var sysID = grUser.sys_id+"";
while (userRoleGA.next() && userRoleGA.user.toString() == sysID) {//current.u_app.u_person
gs.addInfoMessage('User : '+ userRoleGA.user.name +" ROLE: "+ userRoleGA.role.name);
}
var email = current.u_person.email_primary+"";
var grUser = new GlideRecord('sys_user');
grUser.addQuery('user_name', email);
grUser.query();
if(grUser.next()){
}
if(gs.getUser().hasRoles(){
}
if(gs.hasRole('admin'){
}
var grpList = gs.getUser().getMyGroups();
var myGrps = '';
for (var i = 0; i != grpList.size(); i++) {
if (i != 0) myGrps += ',';
myGrps += grpList.get(i);
}
function isGroup(){
var grpList = gs.getUser().getMyGroups();
var myGrps = '';
for (var i = 0; i != grpList.size(); i++) {
if (i != 0) myGrps += ',';
myGrps += grpList.get(i);
}
var myUserId = gs.getUserID();
var gr = new GlideRecord('sys_report_users_groups');
gr.addQuery('report_id', current.getUniqueValue());
var qc = gr.addQuery('user_id', myUserId);
if (myGrps != '')
qc.addOrCondition('group_id', 'IN', myGrps);
gr.query();
if (gr.getRowCount() > 0)
return true;
return false;
//--------------------------------------------
//
//--------------------------------------------
function onLoad() {
var yesRole = g_user.hasRoles();
if (yesRole)
alert('true');
else
alert('not true');
}
if (!gs.hasRole("admin") && gs.getSession().isInteractive()) {
var qc1 = current.addQuery('u_group',"");
var gra = new GlideRecord('sys_user_grmember');
gra.addQuery('user', gs.getUserID());
gra.query();
while (gra.next()) {
qc1.addOrCondition('u_group', gra.group);
}
}
var currentUser = gs.getUser();
gs.info(currentUser.isMemberOf('Capacity Mgmt'));
var email = current.u_person.email_primary+"";
var grUser = new GlideRecord('sys_user');
grUser.addQuery('user_name', email);
grUser.query();
if(grUser.next()){
}
//-------------------------------------
// When you remove a user from a group, the
// group roles are revoked for that user. This method makes
// managing roles much easier than assigning roles to
// individual users.
//-------------------------------------------
//------------------------------------
Adding Users to Groups
After defining a group, add users to the group.
1. Navigate to User Administration > Groups.
2. Click a group Name.
3. In the Group Members related list, click Edit
4. Select one or more names in the Collection list.
5. Click Add.
6. Click Submit.
Removing Users from Groups
You can remove users from a group at any time.
1. Navigate to User Administration > Groups.
2. Click a group Name.
3. In the Group Members related list, select the check box next to a group member name.
4. From the Actions on selected rows menu, select Delete.
//--------------------------------------------------------------------------------
Name: Prevent Closure if Child Task is Active
Type: "Before Update" Business Rule
Table:
Description: Prevents closing a task if any of the task's child tasks are still active.
Parameters:
Script:
//--------------------------------------------------------------------------------------
var gr = new GlideRecord('task');
gr.addQuery('active','true');
gr.addQuery('parent',current.sys_id);
gr.query();
if (gr.next()) {
current.setAbortAction(true);
}
//-----------------------------------------------------------
// POPUPS
//----------------------------------------------------------------------
// Only alert if ticket is being inserted (as opposed to modified)
function onSubmit() {
if (g_form.getValue('priority') == '1') {
return confirm('Submit a priority one ticket?');
}
}
//--------------------------------------------------------
//REFERENCE FIELDS
//---------------------------------------------------
function onChange(control, oldValue, newValue, isLoading) {
// if the caller_id field is not present, then we can't add an
icon anywhere
if (!g_form.hasField('caller_id'))
return;
if (!newValue)
return;
g_form.getReference('caller_id', function(ref) {
g_form.removeDecoration('caller_id', 'icon-star', 'VIP');
if (ref.getValue('vip') == 'true')
g_form.addDecoration('caller_id', 'icon-star',
'VIP');
});
}
//---------------------------------------------------------------------------
// Tested
//----------------------------------------------------------------------------
//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');
}
}
//------------------------------------------------------------------
Not Tested
Name: Restrict Form Views by Role
Type: Business Rule
Table: global
Description: Generally the view used on a form is controlled by either specifying the sysparm_view parameter in
the url or module properties, or by inheriting the view from the previous form or list. In some cases this does not
apply, such as opening a referenced field form from a record producer. In this case you may want to control the view
of the form based on roles. Here's an example of controlling the view of the user form.
This script is based off of the out-of-box global business rule incident functions.
Parameters:
Script:
//---------------------------------------------------------------------------------------
function sys_userGetViewName() {
if (gs.hasRole("itil"))
{ return; }
if (view.startsWith("ess"))
{ return; }
// do not change view if it starts with sys_ (e.g. sys_ref_list)
if (view.startsWith("sys_"))
{ return; }
answer = "ess";
}
function sys_user_listGetViewName() {
sys_userGetViewName();
}
//-------------------------------------------------------------------
// Not Tested
Name: Restrict Access to Admin Role
Type: Business rule
Table: User Role [sys_user_has_role]
Description: Allows only users with the admin role to grant or remove the admin role. Prevents users who do not
have the admin role from granting or removing the admin role.
Parameters: When: Before (insert,update,delete), Condition: !gs.hasRole('admin')
Script:
//------------------------------------------------------------------------
if (current.role.getDisplayValue()=='admin') {
gs.addErrorMessage('only admins can add/remove the admin role')
current.setAbortAction(true);
}
//------------------------------------------------------------------
// Tobe tested again
Name: Add Role to Every User
Type: Client Script, Background Script
Table: sys_user
Description: Adds a role to every user. In this sample, the role being added is Self Service. To add a different role,
simply substitute the desired role for self_service.
Parameters:
Script:
//------------------------------------------------------------------
var gr = new GlideRecord("sys_user");
gr.query();
while (gr.next()) {
if (gr.accumulated_roles.toString().indexOf(",self_service,") == -1) {
gr.roles = gr.roles + ",self_service";
gr.update();
}
}
//--------------------------------------------------------------
// Accumulated Roles
//------------------------------------------------------------------------
// Not upplicable for smart
// Lock accounts if bcNetIDStatus != active in LDAP and user does not
// have self-service, itil or admin role
var rls = current.accumulated_roles.toString();
if (current.u_bcnetidstatus == 'active' &&
(rls.indexOf(',itil,') > 0 ||
rls.indexOf(',admin,') > 0 ||
rls.indexOf(',ess,') > 0)) {
current.locked_out = false;
}
else {
current.locked_out = true;
}
var gr = new GlideRecord("sys_user");
gr.query();
while (gr.next()) {
gr.update();
gs.print("updating " + gr.getDisplayValue());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment