Finding Out Group Membership

October 1, 2007

AFAIK, group membership is not stored on a per-user basis. In other words, if you want to find out which groups a specific user is member of, you have to ask that from Groups, not Users.

The first time I ran into this I was pretty bummed out because it seemed you had to poll every specific group to see if the member belongs to it. Then I read this helpful hint from Mr. Kersten.

My case was a little different in that I had to do all of this from PHP. Instead of calling dscl with system, I decided to do a little more experimenting and came up with this very straight-forward LDAP solution.

So without further ado, my code to find all the names of groups a user is member of, is as follows (snipped from a bigger authentication routine):

<?php
function get_groups($username)
{
    $groups = array();
    $ds = ldap_connect("ldaps://example.com") or die("LDAP connection failed");
    ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
    
    $base_dn = "dc=example,dc=com";
    $result = ldap_search($ds, $base_dn, "uid={$username}", array("cn", "uid"));
    $info = ldap_get_entries($ds, $result);
    $user_id  = $info[0]['uid'][0];

    // Fetch all groups the user is a member of
    $result = ldap_search($ds, "cn=groups,{$base_dn}" , "memberuid={$username}", array("cn"));
    $result = ldap_get_entries($ds, $result);

    // First is "count" of results which we don't care about
    unset($result['count']);

    // Copy the group names into a clean array
    foreach($result as $g) {
        $groups[] = $g['cn'][0];
    }

    return $groups;
}