phi/src/phi/ldap/user.py

76 lines
1.9 KiB
Python
Raw Normal View History

2020-10-05 14:51:16 +02:00
from ldap3 import ALL_ATTRIBUTES
from phi.ldap.utils import get_response, make_user_dict, add_entry, delete_entry
from phi.logging import get_logger
2017-12-21 13:44:54 +01:00
2020-10-05 14:51:16 +02:00
log = get_logger(__name__)
2017-12-21 13:44:54 +01:00
2020-09-30 16:38:31 +02:00
2020-10-05 14:51:16 +02:00
def get_user_by_uid(client, uid):
log.info("Searching entry with identifier: {}".format(uid))
2020-09-30 18:42:28 +02:00
2020-10-05 14:51:16 +02:00
filter_ = "({}={})".format('uid', uid)
log.debug("Search filter: {}".format(filter_))
2020-09-30 18:42:28 +02:00
2020-10-05 14:51:16 +02:00
response_id = client.connection.search(
client.base_dn, filter_,
search_scope='SUBTREE',
attributes=[ALL_ATTRIBUTES]
)
2020-09-30 18:42:28 +02:00
2020-10-05 14:51:16 +02:00
response = get_response(client, response_id)
2017-12-21 13:44:54 +01:00
2020-10-05 14:51:16 +02:00
if not response:
2017-12-21 13:44:54 +01:00
return None
2020-10-05 14:51:16 +02:00
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 make_user_dict(client, response[0])
2017-12-21 13:44:54 +01:00
2020-10-05 14:51:16 +02:00
def get_all_users(client):
log.info("Searching all the users")
2017-12-21 13:44:54 +01:00
2020-10-05 14:51:16 +02:00
dn = 'ou=Hackers,{}'.format(client.base_dn)
log.debug("Search dn: {}".format(dn))
2020-09-30 18:42:28 +02:00
2020-10-05 14:51:16 +02:00
response_id = client.connection.search(
dn, '(objectclass=person)',
search_scope='SUBTREE',
attributes=[ALL_ATTRIBUTES]
)
response = get_response(client, response_id)
users = [make_user_dict(client, entry) for entry in response]
2020-09-30 18:42:28 +02:00
return users
2020-10-04 17:45:09 +02:00
2020-10-10 12:54:28 +02:00
def add_user(client, uid, cn, sn, mail, password):
2020-10-04 17:45:09 +02:00
dn = 'uid={},ou=Hackers,{}'.format(uid, client.base_dn)
attributes={
'objectClass': [
'inetOrgPerson',
'organizationalPerson',
'person', 'top'
],
'cn': cn,
'sn': sn,
2020-10-10 12:54:28 +02:00
'mail': mail,
'userPassword': password # TODO: use hashed password
2020-10-04 17:45:09 +02:00
}
add_entry(client, dn, attributes)
2020-10-05 14:51:16 +02:00
def delete_user(client, user):
delete_entry(client, user['dn'])
def delete_user_by_uid(client, uid):
2020-10-04 17:45:09 +02:00
dn = 'uid={},ou=Hackers,{}'.format(uid, client.base_dn)
delete_entry(client, dn)