Commit 29f9fd19 authored by Daniel Klaffenbach's avatar Daniel Klaffenbach 🐍

ldap: Add method for getting all LDAP data for a particular user

This makes it easier for 3rd party code to read LDAP attributes.

Fixes #4
parent 43a4fa59
Pipeline #6508 passed with stage
in 46 seconds
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import ssl
import ldap3
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 ldap3.utils.conv import escape_filter_chars
from django.conf import settings
from django.contrib.auth import get_user_model
from django.utils.functional import cached_property
......@@ -68,15 +70,35 @@ class Ldap(object):
return Connection(**connection_kwargs)
def get_attributes(self, username):
conn = self.connection
model_attrs = {}
"""
:attention: This method is not part of the public API. Do not use it.
"""
model_attrs = {}
ldap_user = self.get_user(username, self.LDAP_SYNC_USER_ATTRIBUTES.keys())
for attr in self.LDAP_SYNC_USER_ATTRIBUTES:
if attr in ldap_user and ldap_user[attr]:
field_name = self.LDAP_SYNC_USER_ATTRIBUTES[attr]
ldap_value = ldap_user[attr][0]
# Limit the LDAP value to the `max_length` of the field. Otherwise
# we run into validation errors.
model_attrs[field_name] = ldap_value[0:self.USER_MODEL_ATTRS_MAX_LENGTH[field_name]]
return model_attrs
def get_user(self, username, attributes=ldap3.ALL_ATTRIBUTES):
"""
Returns the specified user from LDAP, without doing any conversion.
:rtype: dict
"""
cleaned_username = escape_filter_chars(username)
search_kwargs = {
'search_base': self.LDAP_PARAMS['base'],
'search_filter': '(uid=%s)' %username,
'attributes': self.LDAP_SYNC_USER_ATTRIBUTES.keys(),
}
'search_filter': '(uid=%s)' %cleaned_username,
'attributes': attributes,
}
conn = self.connection
try:
result = conn.search(**search_kwargs)
except LDAPException:
......@@ -88,13 +110,8 @@ class Ldap(object):
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]:
field_name = self.LDAP_SYNC_USER_ATTRIBUTES[attr]
ldap_value = conn.response[0]['attributes'][attr][0]
# Limit the LDAP value to the `max_length` of the field. Otherwise
# we run into validation errors.
model_attrs[field_name] = ldap_value[0:self.USER_MODEL_ATTRS_MAX_LENGTH[field_name]]
return model_attrs
if not result:
return {}
else:
return conn.response[0]['attributes']
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