Python list groups of an ldap user
This is a snippet from my session_app demo flask app. I wanted to return a list of the usergroups a user is a member of. I also wanted to provide the option to the admin to choose which attribute to show for the group, such as cn or description or whatever the admin wants.
def get_ldap_user_groups(server_uri, bind_dn, bind_pw,user_dn,user_attrib_memberof,group_name_attrib,group_base):
server = ldap3.Server(server_uri)
conn = ldap3.Connection(server, auto_bind=True,user=bind_dn, password=bind_pw)
conn.search(
search_base=user_dn,
search_filter="(cn=*)", # this has the potential to not work in a directory where CN is not a part of any dn?
search_scope="BASE",
attributes=[user_attrib_memberof]
)
these_groups = conn.entries[0].entry_attributes_as_dict[user_attrib_memberof]
#print(f"DEBUG: these_groups={these_groups}")
result = []
for group in these_groups:
#print(f"DEBUG: will check for value {group_base} in {group}")
if group_base in group:
if group_name_attrib == "dn":
#print(f"DEBUG: just add group via dn {group}")
result.append(group)
else:
# we need to lookup this group and pick the attribute of it the admin wants.
#print(f"DEBUG: need to lookup group {group} and extract attrib {group_name_attrib}")
conn.search(
search_base=group,
search_filter="(objectClass=*)",
search_scope="BASE",
attributes=[group_name_attrib]
)
this_group=conn.entries[0].entry_attributes_as_dict[group_name_attrib][0]
#print(f"DEBUG: Group {group} identified as attrib {group_name_attrib}={this_group}")
result.append(this_group)
return result
Some example calls:
>>> get_ldap_user_groups("ldaps://dns1.ipa.example.com:636","uid=serviceaccount,cn=users,cn=accounts,dc=ipa,dc=example,dc=com","nicetry","uid=bgstack15,cn=users,cn=accounts,dc=ipa,dc=example,dc=com","memberof","dn","cn=groups,cn=accounts,dc=ipa,dc=example,dc=com")
['cn=public,cn=groups,cn=accounts,dc=ipa,dc=example,dc=com', 'cn=netdev,cn=groups,cn=accounts,dc=ipa,dc=example,dc=com', 'cn=ipausers,cn=groups,cn=accounts,dc=ipa,dc=example,dc=com', 'cn=audio,cn=groups,cn=accounts,dc=ipa,dc=example,dc=com', 'cn=video,cn=groups,cn=accounts,dc=ipa,dc=example,dc=com']
>>> get_ldap_user_groups("ldaps://dns1.ipa.example.com:636","uid=serviceaccount,cn=users,cn=accounts,dc=ipa,dc=example,dc=com","nicetry","uid=bgstack15,cn=users,cn=accounts,dc=ipa,dc=example,dc=com","memberof","dn","cn=groups,cn=accounts,dc=ipa,dc=example,dc=com")
['public', 'netdev', 'ipausers', 'audio', 'video']
Comments