[SalesForce] How to find the groups a user is a part of, either directly or via another groups

I had been wondering if there is a simple solution to find out the different groups that a user is a part of, either by direct membership or via a sub groups or even deep.

We were facing a challenge where we wanted to find out if a user belongs to a certain group and based on that, certain actions were made possible.

Querying the group member object was a solution but to a certain extent.

Lets take an example. User A is a part of Group A. Group A is a part of Group B. Group B is a part of Group C. So, User A is indirectly a part of Group B and Group C.

So the apex query would return us Group A but not Group B and Group C.

What is the solution to this? I have one which I am going to post as an answer (possible). Please provide your suggestions / improvements.

Best Answer

If you navigate to the user detail page, there is a section for Group Memberships. If there are more than 5 records under the list, you will get a link 'Go To List' that takes you to the list of groups. We have made use of this page.

Here is the code snippet.

//create a page reference to the standard salesforce page.
//pass the id of the user in context.
PageReference page = new PageReference('/_ui/system/user/GroupMembershipPage/d?userId=005Q000000O4AK6');

//get the html content of the page
String html = page.getContent().toString();

//set of group ids
Set<Id> groupsIds = new Set<Id>();

//if you study the html code of the page, you will understand the below string we have used for the string functions.
while(html.contains('/setup/own/groupdetail.jsp?id=')) {
    html = html.subString(html.indexOf('/setup/own/groupdetail.jsp?id=') + 1);
    String groupId = html.subString(html.indexOf('=') + 1 , html.indexOf('"'));
    System.debug('***** ' + groupId);
    groupIds.add(groupId);
}