phi/src/phi/ldap/user.py

71 lines
1.9 KiB
Python
Raw Normal View History

2020-10-10 12:59:41 +02:00
from ldap3 import ALL_ATTRIBUTES, HASHED_SALTED_SHA
from ldap3.utils.hashed import hashed
2020-10-05 14:51:16 +02:00
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-11-20 12:04:17 +01:00
filter_ = "({}={})".format("uid", uid)
2020-10-05 14:51:16 +02:00
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(
2020-11-20 12:04:17 +01:00
client.base_dn, filter_, search_scope="SUBTREE", attributes=[ALL_ATTRIBUTES]
2020-10-05 14:51:16 +02:00
)
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:
2020-11-20 12:04:17 +01:00
log.error(
"Looking for exactly one result but server gave {}. "
"Taking the first and ignoring the rest.".format(len(response))
)
2020-10-05 14:51:16 +02:00
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-11-20 12:04:17 +01:00
dn = "ou=Hackers,{}".format(client.base_dn)
2020-10-05 14:51:16 +02:00
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(
2020-11-20 12:04:17 +01:00
dn, "(objectclass=person)", search_scope="SUBTREE", attributes=[ALL_ATTRIBUTES]
2020-10-05 14:51:16 +02:00
)
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-11-20 12:04:17 +01:00
dn = "uid={},ou=Hackers,{}".format(uid, client.base_dn)
2020-10-10 12:59:41 +02:00
hashed_password = hashed(HASHED_SALTED_SHA, password)
2020-10-04 17:45:09 +02:00
2020-11-20 12:04:17 +01:00
attributes = {
"objectClass": ["inetOrgPerson", "organizationalPerson", "person", "top"],
"cn": cn,
"sn": sn,
"mail": mail,
"userPassword": 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):
2020-11-20 12:04:17 +01:00
delete_entry(client, user["dn"])
2020-10-05 14:51:16 +02:00
def delete_user_by_uid(client, uid):
2020-11-20 12:04:17 +01:00
dn = "uid={},ou=Hackers,{}".format(uid, client.base_dn)
2020-10-04 17:45:09 +02:00
delete_entry(client, dn)