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.