Commit 1d8c72b0 authored by Daniel Klaffenbach's avatar Daniel Klaffenbach 🐍

ldap: Use SYNC client strategy and try to handle LDAP errors

parent 01121349
Pipeline #5651 passed with stage
in 47 seconds
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import ssl
from ldap3 import Server, Connection, DSA, RESTARTABLE
from ldap3 import Server, Connection, DSA, SYNC
from ldap3.core.exceptions import LDAPException
from ldap3.core.tls import Tls
from ldap3.utils.uri import parse_uri
from django.conf import settings
......@@ -50,16 +51,35 @@ class Ldap(object):
'auto_bind': True,
'user': self.LDAP_SYNC_BASE_USER,
'password': self.LDAP_SYNC_BASE_PASS,
'client_strategy': SYNC,
}
if self.LDAP_PARAMS['host'] != 'localhost':
connection_kwargs['client_strategy'] = RESTARTABLE
return Connection(**connection_kwargs)
def get_attributes(self, username):
conn = self.connection
model_attrs = {}
if conn.search(self.LDAP_PARAMS['base'], '(uid=%s)' %username, attributes=self.LDAP_SYNC_USER_ATTRIBUTES.keys()):
search_kwargs = {
'search_base': self.LDAP_PARAMS['base'],
'search_filter': '(uid=%s)' %username,
'attributes': self.LDAP_SYNC_USER_ATTRIBUTES.keys(),
}
try:
result = conn.search(**search_kwargs)
except LDAPException:
# Try one more time before raising the exception
# @TODO: Catch exception in User.pre_save()
try:
conn.unbind()
except:
pass
conn.bind()
result = conn.search(**search_kwargs)
if result:
for attr in self.LDAP_SYNC_USER_ATTRIBUTES:
if attr in conn.response[0]['attributes'] and conn.response[0]['attributes'][attr]:
model_attrs[self.LDAP_SYNC_USER_ATTRIBUTES[attr]] = conn.response[0]['attributes'][attr][0]
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment