phi/src/phi/ldap/entry.py

77 lines
2.1 KiB
Python
Raw Normal View History

2017-12-21 13:44:54 +01:00
from ldap3 import ALL_ATTRIBUTES, ALL_OPERATIONAL_ATTRIBUTES
from phi.logging import get_logger
log = get_logger(__name__)
2020-10-04 17:45:09 +02:00
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
2017-12-21 13:44:54 +01:00
def get_entry_by_uid(client, uid):
log.info("Searching entry with identifier: {}".format(uid))
2020-09-30 16:38:31 +02:00
filter_ = "({}={})".format('uid', uid)
2017-12-21 13:44:54 +01:00
log.debug("Search filter: {}".format(filter_))
response_id = client.connection.search(
client.base_dn, filter_,
search_scope='SUBTREE',
2020-09-30 18:42:28 +02:00
attributes=[ALL_ATTRIBUTES]
2017-12-21 13:44:54 +01:00
)
2020-10-04 17:45:09 +02:00
response = get_response(client, response_id)
2017-12-21 13:44:54 +01:00
if not response:
return None
2020-10-04 17:45:09 +02:00
if len(response) > 1:
2020-09-30 16:42:53 +02:00
log.error("Looking for exactly one result but server gave {}. "
2017-12-21 13:44:54 +01:00
"Taking the first and ignoring the rest."
.format(len(response)))
return response[0]
2020-09-30 18:42:28 +02:00
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]
)
2020-10-04 17:45:09 +02:00
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
2020-09-30 18:42:28 +02:00
2020-10-04 17:45:09 +02:00
def delete_entry(client, dn):
log.info('Deleting entry with distinguiscet name: {}')
response_id = client.connection.delete(dn)
response = get_response(client, response_id)
2020-09-30 18:42:28 +02:00
return response