#!/opt/python/bin/python
# -*- coding: iso-8859-1 -*-
"""
This script can be used for some basic LDAP / Active Directory Testing.

You need to configure the variables below this comment to match your setup.

If it does not authenticate your users correctly, you maybe also want to look
at the code below and find out why it does not work.

Please contribute changes back to us.

MoinMoin development at http://moinmoin.wikiwikiweb.de/
"""

server_uri = 'ldap://ldap.example.org/'
#server_uri = 'ldaps://ldap.example.org/'

# if bind_user and bind_pw is both '' it does an anonymous bind
bind_user = ''
bind_pw = ''

base_dn = 'dc=example,dc=org'
filter_str = '(uid=%s)' # check if this is correct for you!

users_passwords = [
    ('user1', 'correctpass1'),
    ('user1', ''), # check whoami output for this!
    ('user1', 'wrongpass1'),
]

import ldap

for user, password in users_passwords:
    # This is only required if you are using a self signed cert. 
    # Probably turn it off for production code.
    if server_uri.startswith('ldaps:'):
        ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_NEVER)

    # ActiveDirectory? Do this, otherwise, leave it out.
    ldap.set_option(ldap.OPT_REFERRALS, 0)

    print "Initializing connection to %s ..." % server_uri
    l = ldap.initialize(server_uri)
    print "LDAP protocol version %d" % l.protocol_version
    #l.protocol_version = ldap.VERSION3

    print "Binding to directory using bind user %r (and configured password) ..." % bind_user
    l.bind_s(bind_user, bind_pw)

    search_filter = filter_str % user
    print "Searching under base dn %s for %s ..." % (base_dn, search_filter)
    lusers = l.search_s(base_dn, ldap.SCOPE_SUBTREE, search_filter)
    results = len(lusers)
    print "Results: %d" % results
    if results:
        for dn, ldap_dict in lusers:
            print "    %s" % dn
        first_dn = lusers[0][0]
        print "Trying to authenticate with first found dn %s (and configured password) ..." % first_dn
        try:
            l.bind_s(first_dn, password)
            print "Succcessfully bound - whoami says: %s" % l.whoami_s()
        except ldap.INVALID_CREDENTIALS, err:
            print "LDAP Error: %s" % err
    print "Unbinding from directory ..."
    l.unbind()
    print "-"*70

