Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Getting all LDAP users with django

I’m using django-auth-ldap and I’m trying to get all users from LDAP server, I didn’t find a way to do so, the authenticating is working in the backend, here is my code

@api_view(['GET'])
def users(request):
    l = ldap.initialize(backend.AUTH_LDAP_SERVER_URI)
    l.simple_bind_s(backend.AUTH_LDAP_BIND_DN, backend.AUTH_LDAP_BIND_PASSWORD)
    users  = LDAPBackend().populate_user('*') #this line is returning None
    l.unbind_s()
    print (users)
    serializer = userSerializer(users, many=True)
    return Response(serializer.data)

I know that line is incorrect LDAPBackend().populate_user('*')

but I really need to get all users with something like this : conn.search('ou=users, dc=example,dc=com', '(objectclass=person)', attributes=['uid', 'cn', 'givenName', 'sn', 'gidNumber'])
(this is how I did with another library called ldap3)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thank you

>Solution :

You can do something like this below

def get_users():
    conn = ldap.initialize(LDAP_URL)
    results = conn.search_s(GROUP_DN, ldap.SCOPE_ONELEVEL, '(cn=*)')
    # get all non-empty uniqueMember of all groups (list of list), flattern the list and get only unique value
    users_dn = set(list(chain.from_iterable(filter(lambda x: x, [x[1].get('uniqueMember') for x in results]))))
    users = [x.split(',')[0].split('=')[1] for x in users_dn]
    return users
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading