tools.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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/>.
  16. import ldap
  17. import logging
  18. import six
  19. from mediagoblin.tools import pluginapi
  20. _log = logging.getLogger(__name__)
  21. class LDAP(object):
  22. def __init__(self):
  23. self.ldap_settings = pluginapi.get_config('mediagoblin.plugins.ldap')
  24. def _connect(self, server):
  25. _log.info('Connecting to {0}.'.format(server['LDAP_SERVER_URI']))
  26. self.conn = ldap.initialize(server['LDAP_SERVER_URI'])
  27. if server['LDAP_START_TLS'] == 'true':
  28. _log.info('Initiating TLS')
  29. self.conn.start_tls_s()
  30. def _get_email(self, server, username):
  31. try:
  32. results = self.conn.search_s(server['LDAP_SEARCH_BASE'],
  33. ldap.SCOPE_SUBTREE, 'uid={0}'
  34. .format(username),
  35. [server['EMAIL_SEARCH_FIELD']])
  36. email = results[0][1][server['EMAIL_SEARCH_FIELD']][0]
  37. except KeyError:
  38. email = None
  39. return email
  40. def login(self, username, password):
  41. for k, v in six.iteritems(self.ldap_settings):
  42. try:
  43. self._connect(v)
  44. user_dn = v['LDAP_USER_DN_TEMPLATE'].format(username=username)
  45. self.conn.simple_bind_s(user_dn, password.encode('utf8'))
  46. email = self._get_email(v, username)
  47. return username, email
  48. except ldap.LDAPError, e:
  49. _log.info(e)
  50. finally:
  51. _log.info('Unbinding {0}.'.format(v['LDAP_SERVER_URI']))
  52. self.conn.unbind()
  53. return False, None