From 9f1b89910718d414fb45af4264378366b08f1412 Mon Sep 17 00:00:00 2001
From: Philip Gaber <gaber@b1-systems.de>
Date: Tue, 12 Nov 2024 12:20:41 +0100
Subject: [PATCH] chore: Removed unused imports & casts, adjusted default
 values & formatting

---
 lib/ucs.py                  |   1 -
 user_import_udm_rest_api.py | 112 +++++++++++++++++++++++++++++-------
 2 files changed, 92 insertions(+), 21 deletions(-)

diff --git a/lib/ucs.py b/lib/ucs.py
index 37d369b..f999c0c 100644
--- a/lib/ucs.py
+++ b/lib/ucs.py
@@ -9,7 +9,6 @@ import urllib.parse
 import logging
 import pandas as pd
 
-from pathlib import Path
 from requests.auth import HTTPBasicAuth
 
 class Ucs:
diff --git a/user_import_udm_rest_api.py b/user_import_udm_rest_api.py
index 7c49c1e..b320e3a 100755
--- a/user_import_udm_rest_api.py
+++ b/user_import_udm_rest_api.py
@@ -29,17 +29,6 @@ non_reconcile_groups = [
 ]
 
 p = configargparse.ArgParser()
-p.add('--import_domain', env_var='IMPORT_DOMAIN', required=True, help='The domain name of your openDesk instance - omit the "portal." or other service specific hostnames.')
-p.add('--import_filename', env_var='IMPORT_FILENAME', required=False, default=None, help='The filename containing the user account details for the import - see template.ods for reference. If filename is not provided or related file is not found random users will be imported.')
-p.add('--import_maildomain', env_var='IMPORT_MAILDOMAIN', required=False, help='Optional: If you are using a different maildomain please specify it, otherwise `IMPORT_DOMAIN` is used.')
-p.add('--loglevel', env_var='LOGLEVEL', default='INFO', help='Set the loglevel: DEBUG, INFO, WARNING, ERROR, CRITICAL. Default: WARNING')
-p.add('--logpath', env_var='LOGPATH', default='./logs', help='Path where the script write its logfile to. Default: ./logs')
-p.add('--output_accounts_filename', env_var='OUTPUT_ACCOUNTS_FILENAME', required=False, default=None, help='The filename to write the created accounts (username<tab>password) into, appends if file exists). If none is provided the default name will be "users-<import_domain>-<timestamp>.txt"')
-p.add('--password_recovery_email', env_var='PASSWORD_RECOVERY_EMAIL', help='Optional: When creating random accounts this password recovery email is used.')
-p.add('--reconcile_groups', env_var='RECONCILE_GROUPS', default=False, help='Optional: Set to "True" if groups on the users should be reconciled based on the input file. Will remove all groups from the user not defined in sheet except for the standard groups: '+', '.join(non_reconcile_groups))
-p.add('--set_default_password', env_var='SET_DEFAULT_PASSWORD', default='', help='Optional: When set the given password is used on the newly created accounts, otherwise a random one will be created.')
-p.add('--udm_api_password', env_var='UDM_API_PASSWORD', required=True, help='Password for the UDM REST API user.')
-p.add('--udm_api_username', env_var='UDM_API_USERNAME', default='Administrator', help='User to authentication against the UDM REST API with.')
 # p.add('--admin_enable_chat', env_var='ADMIN_ENABLE_CHAT', default=False, type=opt2bool, help='Optional: Set to "True" if users should get functional admin permissions for chat component - Requires openDesk Enterprise.')
 p.add(
     "--admin_enable_fileshare",
@@ -132,6 +121,18 @@ p.add(
     type=int,
     help="Optional: Set the default OX context ID to use when creating users. Default: 1",
 )
+p.add(
+    "--import_domain",
+    env_var="IMPORT_DOMAIN",
+    required=True,
+    help='The domain name of your openDesk instance - omit the "portal." or other service specific hostnames.',
+)
+p.add(
+    "--import_filename",
+    env_var="IMPORT_FILENAME",
+    required=False,
+    help="The filename containing the user account details for the import - see template.ods for reference. If filename is not provided or related file is not found random users will be imported.",
+)
 p.add(
     "--import_use_images",
     env_var="IMPORT_USE_IMAGES",
@@ -139,6 +140,12 @@ p.add(
     type=opt2bool,
     help='Optional: Set to "True" if each user should be uploaded with a random profile picture when "import_filename" was set.',
 )
+p.add(
+    "--import_maildomain",
+    env_var="IMPORT_MAILDOMAIN",
+    required=False,
+    help="Optional: If you are using a different maildomain please specify it, otherwise `IMPORT_DOMAIN` is used.",
+)
 p.add(
     "--import_random_amount",
     env_var="IMPORT_RANDOM_AMOUNT",
@@ -153,6 +160,29 @@ p.add(
     type=opt2bool,
     help='If set to "False" the imported usernames of the imported follow the format user.N and admin.N.',
 )
+p.add(
+    "--loglevel",
+    env_var="LOGLEVEL",
+    default="INFO",
+    help="Set the loglevel: DEBUG, INFO, WARNING, ERROR, CRITICAL. Default: WARNING",
+)
+p.add(
+    "--logpath",
+    env_var="LOGPATH",
+    default="./logs",
+    help="Path where the script write its logfile to. Default: ./logs",
+)
+p.add(
+    "--output_accounts_filename",
+    env_var="OUTPUT_ACCOUNTS_FILENAME",
+    required=False,
+    help='The filename to write the created accounts (username<tab>password) into, appends if file exists). If none is provided the default name will be "users-<import_domain>-<timestamp>.txt"',
+)
+p.add(
+    "--password_recovery_email",
+    env_var="PASSWORD_RECOVERY_EMAIL",
+    help="Optional: When creating random accounts this password recovery email is used.",
+)
 p.add(
     "--reconcile_groups",
     env_var="RECONCILE_GROUPS",
@@ -160,6 +190,12 @@ p.add(
     type=opt2bool,
     help=f'Optional: Set to "True" if groups on the users should be reconciled based on the input file. Will remove all groups from the user not defined in sheet except for the standard groups: {"; ".join(non_reconcile_groups)}'
 )
+p.add(
+    "--set_default_password",
+    env_var="SET_DEFAULT_PASSWORD",
+    default="",
+    help="Optional: When set the given password is used on the newly created accounts, otherwise a random one will be created.",
+)
 p.add(
     "--trigger_invitation_mail",
     env_var="TRIGGER_INVITATION_MAIL",
@@ -167,6 +203,18 @@ p.add(
     type=opt2bool,
     help='Optional: Set to "True" if you want invitation mail (same as password recovery mail) being trigger for each created user.',
 )
+p.add(
+    "--udm_api_password",
+    env_var="UDM_API_PASSWORD",
+    required=True,
+    help="Password for the UDM REST API user.",
+)
+p.add(
+    "--udm_api_username",
+    env_var="UDM_API_USERNAME",
+    default="Administrator",
+    help="User to authentication against the UDM REST API with.",
+)
 options = p.parse_args()
 
 new_user_password = options.set_default_password
@@ -177,7 +225,9 @@ logFormatter = logging.Formatter("%(asctime)s %(levelname)-5.5s %(message)s")
 rootLogger = logging.getLogger()
 rootLogger.setLevel(options.loglevel)
 
-fileHandler = logging.FileHandler("{0}/{1}.log".format(options.logpath, os.path.basename(__file__)))
+fileHandler = logging.FileHandler(
+    "{0}/{1}.log".format(options.logpath, os.path.basename(__file__))
+)
 fileHandler.setFormatter(logFormatter)
 rootLogger.addHandler(fileHandler)
 
@@ -189,35 +239,57 @@ logging.info("Running with settings:")
 for option, setting in vars(options).items():
     logging.info(f"> {option}: {setting if not 'password' in option else '<redacted>'}")
 
+
 def import_callback(person):
     global new_user_password
-    if 'password' in person and len(str(person['password'])) >= 8:
+    if "password" in person and len(str(person["password"])) >= 8:
         logging.debug("Using predefined password for user.")
     elif new_user_password is None or len(new_user_password) < 8:
-        person['password'] = ''.join((secrets.choice('öäüÄÖÜß-+<>".,;:0123456789!$%&/()=[]{}<>|_#+*~?') for _ in range(16)))
+        person["password"] = "".join(
+            (
+                secrets.choice('öäüÄÖÜß-+<>".,;:0123456789!$%&/()=[]{}<>|_#+*~?')
+                for _ in range(16)
+            )
+        )
     else:
-        person['password'] = new_user_password
+        person["password"] = new_user_password
     ucs.set_user(person)
 
-import_maildomain = options.import_domain if not options.import_maildomain else options.import_maildomain
 
-ucs = Ucs(adm_username=options.udm_api_username, adm_password=options.udm_api_password, base_url=options.import_domain, maildomain=import_maildomain, options_object=options)
+import_maildomain = (
+    options.import_domain
+    if not options.import_maildomain
+    else options.import_maildomain
+)
+
+ucs = Ucs(
+    adm_username=options.udm_api_username,
+    adm_password=options.udm_api_password,
+    base_url=options.import_domain,
+    maildomain=import_maildomain,
+    options_object=options,
+)
 
 if not options.import_filename:
     logging.info(f"Starting random user import, as no file for import was defined.")
     RandomUser(
         import_callback,
         create_admin_accounts=options.create_admin_accounts,
-        amount=int(options.import_random_amount),
+        amount=options.import_random_amount,
         password_reset_mail=options.password_recovery_email,
-        randomize=options.import_random_usernames,
+        randomize_username=options.import_random_usernames,
     )
     logging.info(
         f"Accounts that have been created:\n{ucs.get_imported_credentials_list()}"
     )
 elif os.path.isfile(options.import_filename):
     logging.info(f"Importing users from '{options.import_filename}'")
-    ImportUser(import_callback, import_filename=options.import_filename, create_admin_accounts=options.create_admin_accounts, use_images=options.import_use_images)
+    ImportUser(
+        import_callback,
+        import_filename=options.import_filename,
+        create_admin_accounts=options.create_admin_accounts,
+        use_images=options.import_use_images,
+    )
 else:
     logging.error(f"File to import from '{options.import_filename}' was not found.")
 
-- 
GitLab