comparison rhodecode/lib/auth_ldap.py @ 700:07fd56c36bfe beta

added basic ldap auth lib
author Marcin Kuzminski <marcin@python-works.com>
date Tue, 16 Nov 2010 09:31:40 +0100
parents
children 6602bf1c5546
comparison
equal deleted inserted replaced
699:52da7cba88a6 700:07fd56c36bfe
1 import logging
2 logging.basicConfig(level=logging.DEBUG)
3 log = logging.getLogger('ldap')
4
5 #==============================================================================
6 # LDAP
7 #Name = Just a description for the auth modes page
8 #Host = DepartmentName.OrganizationName.local/ IP
9 #Port = 389 default for ldap
10 #LDAPS = no set True if You need to use ldaps
11 #Account = DepartmentName\UserName (or UserName@MyDomain depending on AD server)
12 #Password = <password>
13 #Base DN = DC=DepartmentName,DC=OrganizationName,DC=local
14 #
15 #On-the-fly user creation = yes
16 #Attributes
17 # Login = sAMAccountName
18 # Firstname = givenName
19 # Lastname = sN
20 # Email = mail
21
22 #==============================================================================
23 class UsernameError(Exception):pass
24 class PasswordError(Exception):pass
25
26 LDAP_USE_LDAPS = False
27 ldap_server_type = 'ldap'
28 LDAP_SERVER_ADDRESS = '192.168.2.56'
29 LDAP_SERVER_PORT = '389'
30
31 LDAP_BIND_DN = ''
32 LDAP_BIND_PASS = ''
33
34 if LDAP_USE_LDAPS:ldap_server_type = ldap_server_type + 's'
35 LDAP_SERVER = "%s://%s:%s" % (ldap_server_type,
36 LDAP_SERVER_ADDRESS,
37 LDAP_SERVER_PORT)
38
39 BASE_DN = "ou=people,dc=server,dc=com"
40
41 def authenticate_ldap(username, password):
42 """Authenticate a user via LDAP and return his/her LDAP properties.
43
44 Raises AuthenticationError if the credentials are rejected, or
45 EnvironmentError if the LDAP server can't be reached.
46 """
47 try:
48 import ldap
49 except ImportError:
50 raise Exception('Could not import ldap make sure You install python-ldap')
51
52 from rhodecode.lib.helpers import chop_at
53
54 uid = chop_at(username, "@%s" % LDAP_SERVER_ADDRESS)
55 dn = "uid=%s,%s" % (uid, BASE_DN)
56 log.debug("Authenticating %r at %s", dn, LDAP_SERVER)
57 if "," in username:
58 raise UsernameError("invalid character in username: ,")
59 try:
60 #ldap.set_option(ldap.OPT_X_TLS_CACERTFILE, '/etc/openldap/cacerts')
61 server = ldap.initialize(LDAP_SERVER)
62 server.protocol = ldap.VERSION3
63 server.simple_bind_s(dn, password)
64 properties = server.search_s(dn, ldap.SCOPE_SUBTREE)
65 if not properties:
66 raise ldap.NO_SUCH_OBJECT()
67 except ldap.NO_SUCH_OBJECT, e:
68 log.debug("LDAP says no such user '%s' (%s)", uid, username)
69 raise UsernameError()
70 except ldap.INVALID_CREDENTIALS, e:
71 log.debug("LDAP rejected password for user '%s' (%s)", uid, username)
72 raise PasswordError()
73 except ldap.SERVER_DOWN, e:
74 raise EnvironmentError("can't access authentication server")
75 return properties
76
77
78 print authenticate_ldap('test', 'test')