User's access control with Before Query Business Rule

SN4User
Tera Contributor

Hi, I would like to add a 'Before Query Business Rule' to control user's access to Demands by their Business Units. So each users belongs to a specific Business Unit. I have add a reference field for Business Unit in the form of a user. 

 

So let us imagine following:

  • User John belongs to Business Unit A
  • User Cathy belongs to Business Unit B
  • If John opens a Demand which belongs to Business Unit B, he is not allowed to see any data inside this Demand
  • If Cathy opens the same Demand which belongs to Business Unit B, she is allowed to see the data inside this Demand

How could I write the script for the Business Rule? I'm not a coder, I'm a Project Manager but learning ServiceNow, here is what I have coded, but is not working, do you see my mistake?

(function executeBeforeQuery(current, previous, query, request) {

  // Get the current user
  var currentUser = gs.getUser();

  // Get the user's business unit
  var userBusinessUnit = currentUser.getRefRecord("business_unit");

  // Add a condition to the query to only include demands from the user's business unit
  query.addCondition("business_unit", "=", userBusinessUnit);

})(current, previous, query, request);
1 ACCEPTED SOLUTION

umaaggarwal
Giga Guru
Giga Guru

Hi there,

 

Please use below two lines of code and should work. I just added BU field and it is working for me. you need to replace the field name with your field name in the instance 

 

var bu = gs.getUser().getRecord().getValue('u_bu');

// here u_bu is the field name on user record. Please use the one you have on your user record in backend table
current.addQuery('u_bu',bu);

//here in this line 'u_bu' field is on the demand table. Please use the backend name of the field which you are using

 

Please feel free to reach out in case you are stuck .

View solution in original post

6 REPLIES 6

Hi, 

 

This is expected behavior as we are showing demands of same BU which user has, admin has no BU so he sees the demands which have no BU.

 

If you want demands with no BU not to be shown, please add this one more line . this should sort this

current.addNotNullQuery('u_bu'); // you need to replace u_bu with your BU field name

 

This line is just making sure that it returns the demans where BU is not empty

 

Hope this helps!

 

 

 

Fazal Mohammad
ServiceNow Employee
ServiceNow Employee

Hi @SN4User 

I just need few inputs from you, Thanks in advance:

Are you implementing this functionality of User should have access to the demands based on its BU for any of your customers? and this functionality you're looking only for Demands or you're planning to do it for other entities also ? If Yes, What are they?

 

Thanks

Fazal