77 lines
2.1 KiB
Python
77 lines
2.1 KiB
Python
from ldap3 import ALL_ATTRIBUTES, ALL_OPERATIONAL_ATTRIBUTES
|
|
|
|
from phi.logging import get_logger
|
|
|
|
log = get_logger(__name__)
|
|
|
|
|
|
def get_response(client, response_id):
|
|
response, result, request = client.connection.get_response(
|
|
response_id, get_request=True
|
|
)
|
|
|
|
log.debug("Request: {}".format(request))
|
|
log.debug("Response: {}".format(response))
|
|
log.debug("Result: {}".format(result))
|
|
|
|
if result['description'] is not 'success':
|
|
raise Exception(result['description'])
|
|
|
|
return response
|
|
|
|
|
|
def get_entry_by_uid(client, uid):
|
|
log.info("Searching entry with identifier: {}".format(uid))
|
|
|
|
filter_ = "({}={})".format('uid', uid)
|
|
log.debug("Search filter: {}".format(filter_))
|
|
|
|
response_id = client.connection.search(
|
|
client.base_dn, filter_,
|
|
search_scope='SUBTREE',
|
|
attributes=[ALL_ATTRIBUTES]
|
|
)
|
|
|
|
response = get_response(client, response_id)
|
|
|
|
if not response:
|
|
return None
|
|
|
|
if len(response) > 1:
|
|
log.error("Looking for exactly one result but server gave {}. "
|
|
"Taking the first and ignoring the rest."
|
|
.format(len(response)))
|
|
|
|
return response[0]
|
|
|
|
|
|
def get_entries_by_ou(client, ou):
|
|
log.info("Searching entries with organizational unit: {}".format(ou))
|
|
|
|
dn = 'ou={},{}'.format(ou, client.base_dn)
|
|
log.debug("Search dn: {}".format(dn))
|
|
|
|
response_id = client.connection.search(
|
|
dn, '(objectclass=person)',
|
|
search_scope='SUBTREE',
|
|
attributes=[ALL_ATTRIBUTES]
|
|
)
|
|
|
|
response = get_response(client, response_id)
|
|
return response
|
|
|
|
|
|
def add_entry(client, dn, attributes):
|
|
log.info('Adding entry with distinguiscet name: {}'
|
|
'and attributes {}'.format(dn, attributes))
|
|
response_id = client.connection.add(dn, attributes=attributes)
|
|
response = get_response(client, response_id)
|
|
return response
|
|
|
|
|
|
def delete_entry(client, dn):
|
|
log.info('Deleting entry with distinguiscet name: {}')
|
|
response_id = client.connection.delete(dn)
|
|
response = get_response(client, response_id)
|
|
return response
|