simple Open Directory auth example

36 views
Skip to first unread message

Preston Holmes

unread,
Sep 11, 2009, 1:50:07 PM9/11/09
to pymac...@googlegroups.com
as part of django project I wanted to work out OD auth from python - and figured I'd share this quick sample code.

It uses anonymous binding and requires the python-ldap module

This is for user auth only - still need to look into group membership, probably will look into extending http://code.google.com/p/django-ldap-groups/


import sys
import os
import ldap
import getpass
AUTH_LDAP_SERVER = 'ldap://ldap.example.com'
DN = 'uid=%s,cn=users,dc=server,dc=example,dc=com'

def main():
    con = ldap.initialize(AUTH_LDAP_SERVER)
    con.set_option(ldap.OPT_X_TLS_DEMAND, True)
    con.set_option(ldap.OPT_PROTOCOL_VERSION,3)
    con.set_option(ldap.OPT_DEREF,3)
    user_name = raw_input('Username: ')
    pw = getpass.getpass("Password for %s: " % user_name)
    try:
        con.simple_bind_s (DN % user_name,pw)
        print "authentication success"
        print "Your dn is: \n",con.whoami_s()
    except ldap.LDAPError, e:
        sys.stderr.write("Fatal Error\n")
        if type(e.message) == dict:
            for (k, v) in e.message.iteritems():
                sys.stderr.write("%s: %s\n" % (k, v))
        else:
            sys.stderr.write("Error: %s\n" % e.message);
        sys.exit()
if __name__ == '__main__':
    main()

Reply all
Reply to author
Forward
0 new messages