You might want to look at the code of this plugin. It adds avatar flair for people in the same groups so they are able to recognize each other as group members. That’s a different thing but it does contain the code that checks if the viewing user is in the same group as the user that posted.