import ldap
server = "_insert_ldap_server_fqdn_"
basedn = "_insert_base_dn_"
scope = ldap.SCOPE_SUBTREE # or ldap.SCOPE_ONE
def ldap_check(user, passw):
try:
l = ldap.open(server)
# guess full common name from wikiname
# eg. "AndrewBaumann" -> "Andrew Baumann"
cut = 0
for c in range(1, len(user)):
if user[c].isupper():
cut = c
commonname = user[:cut] + " " + user[cut:]
# Any errors will throw an ldap.LDAPError exception
# or related exception so you can ignore the result
# first bind anonymously to the server
l.simple_bind_s()
# then do a search on the common name or userid to find the UID
filter = "(|(cn=%s)(uid=%s))" % (commonname, user)
res = l.search_s(basedn, scope, filter, ['dn'])
if len(res) == 0:
return False # no matching name in LDAP
# extract their user ID
try:
user_dn = res[0][0]
except (IndexError, KeyError):
return False # something screwed up with the search?
# now try authenticated bind as their user with the password
res = l.simple_bind_s(user_dn, passw)
if res is None:
return True
else:
return False
except ldap.LDAPError, e:
# print e
# handle error however you like
return False