feat(ldap): add functions to add Users to DIT

This commit is contained in:
Julian Lobbes 2022-11-15 00:41:16 +01:00
parent 168fd34174
commit d13fe8533e

View File

@ -642,3 +642,47 @@ def get_user(connection: Connection, uid: str) -> User:
first_name, last_name, display_name,
picture
)
def create_user(connection: Connection, user: User) -> None:
"""Creates an entry from the specified User object on the LDAP server.
Parameters
----------
Connection : ldap3.Connection
Bound Connection object to an LDAP server.
user : lumi2.usermodel.User
The User object from which a user LDAP entry will be created.
Raises
------
EntryExistsException
If a user entry with the same uid/username already exists in the DIT.
"""
_assert_is_valid_connection(connection)
if not isinstance(user, User):
raise TypeError(f"Expected a User but got: '{type(user)}'.")
try:
get_user(connection, user.username)
raise EntryExistsException("User already exists: '{user.username}'.")
except EntryNotFoundException:
pass
user_dn = f"uid={user.username},{current_app.config['LDAP_USERS_OU']}"
user_image_bytes = BytesIO()
user.picture.save(user_image_bytes, format="jpeg")
attributes = {
"uid": user.username,
"userPassword": "{SHA512}" + user.password_hash,
"cn": user.first_name,
"sn": user.last_name,
"displayName": user.display_name,
"mail": user.email,
"jpegPhoto": user_image_bytes.getvalue(),
}
connection.add(user_dn, "inetOrgPerson", attributes)