71 lines
1.9 KiB
Python
71 lines
1.9 KiB
Python
from ldap3 import ALL_ATTRIBUTES, HASHED_SALTED_SHA
|
|
from ldap3.utils.hashed import hashed
|
|
from phi.ldap.utils import get_response, make_user_dict, add_entry, delete_entry
|
|
from phi.logging import get_logger
|
|
|
|
log = get_logger(__name__)
|
|
|
|
|
|
def get_user_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 make_user_dict(client, response[0])
|
|
|
|
|
|
def get_all_users(client):
|
|
log.info("Searching all the users")
|
|
|
|
dn = "ou=Hackers,{}".format(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)
|
|
|
|
users = [make_user_dict(client, entry) for entry in response]
|
|
return users
|
|
|
|
|
|
def add_user(client, uid, cn, sn, mail, password):
|
|
dn = "uid={},ou=Hackers,{}".format(uid, client.base_dn)
|
|
hashed_password = hashed(HASHED_SALTED_SHA, password)
|
|
|
|
attributes = {
|
|
"objectClass": ["inetOrgPerson", "organizationalPerson", "person", "top"],
|
|
"cn": cn,
|
|
"sn": sn,
|
|
"mail": mail,
|
|
"userPassword": hashed_password,
|
|
}
|
|
|
|
add_entry(client, dn, attributes)
|
|
|
|
|
|
def delete_user(client, user):
|
|
delete_entry(client, user["dn"])
|
|
|
|
|
|
def delete_user_by_uid(client, uid):
|
|
dn = "uid={},ou=Hackers,{}".format(uid, client.base_dn)
|
|
delete_entry(client, dn)
|