Make ldap plugin python3 compatible
[mediagoblin.git] / mediagoblin / plugins / ldap / tools.py
CommitLineData
daf29c01
RE
1# GNU MediaGoblin -- federated, autonomous media hosting
2# Copyright (C) 2011, 2012 MediaGoblin contributors. See AUTHORS.
3#
4# This program is free software: you can redistribute it and/or modify
5# it under the terms of the GNU Affero General Public License as published by
6# the Free Software Foundation, either version 3 of the License, or
7# (at your option) any later version.
8#
9# This program is distributed in the hope that it will be useful,
10# but WITHOUT ANY WARRANTY; without even the implied warranty of
11# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12# GNU Affero General Public License for more details.
13#
14# You should have received a copy of the GNU Affero General Public License
15# along with this program. If not, see <http://www.gnu.org/licenses/>.
16import ldap
17import logging
18
386c9c7c
BP
19import six
20
2b55a0f8 21from mediagoblin.tools import pluginapi
daf29c01
RE
22
23_log = logging.getLogger(__name__)
24
25
26class LDAP(object):
c4513740 27 def __init__(self):
2b55a0f8 28 self.ldap_settings = pluginapi.get_config('mediagoblin.plugins.ldap')
daf29c01
RE
29
30 def _connect(self, server):
11782c00
RE
31 _log.info('Connecting to {0}.'.format(server['LDAP_SERVER_URI']))
32 self.conn = ldap.initialize(server['LDAP_SERVER_URI'])
33
34 if server['LDAP_START_TLS'] == 'true':
35 _log.info('Initiating TLS')
36 self.conn.start_tls_s()
daf29c01 37
517eb8b4 38 def _get_email(self, server, username):
517eb8b4 39 try:
1bc5b9df
RE
40 results = self.conn.search_s(server['LDAP_SEARCH_BASE'],
41 ldap.SCOPE_SUBTREE, 'uid={0}'
42 .format(username),
43 [server['EMAIL_SEARCH_FIELD']])
44
517eb8b4
RE
45 email = results[0][1][server['EMAIL_SEARCH_FIELD']][0]
46 except KeyError:
47 email = None
48
49 return email
50
daf29c01 51 def login(self, username, password):
386c9c7c 52 for k, v in six.iteritems(self.ldap_settings):
daf29c01 53 try:
daf29c01 54 self._connect(v)
11782c00 55 user_dn = v['LDAP_USER_DN_TEMPLATE'].format(username=username)
daf29c01 56 self.conn.simple_bind_s(user_dn, password.encode('utf8'))
517eb8b4
RE
57 email = self._get_email(v, username)
58 return username, email
daf29c01 59
8bb15a54 60 except ldap.LDAPError as e:
daf29c01
RE
61 _log.info(e)
62
11782c00 63 finally:
517eb8b4 64 _log.info('Unbinding {0}.'.format(v['LDAP_SERVER_URI']))
11782c00
RE
65 self.conn.unbind()
66
517eb8b4 67 return False, None