From f2c00afacd0fc1e834be55208116d0e3b50d40ab Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Thorsten=20Ro=C3=9Fner?= <thorsten.rossner.extern@zendis.de>
Date: Tue, 1 Oct 2024 19:54:29 +0200
Subject: [PATCH] feat: Support for schematic usernames and default
 `udm_api_username` to "Administrator".

BREAKING CHANGE: Default import username has changed.
---
 Dockerfile                  |  1 +
 lib/random_user.py          | 22 +++++++++++++++++-----
 user_import_udm_rest_api.py |  8 +++++---
 3 files changed, 23 insertions(+), 8 deletions(-)

diff --git a/Dockerfile b/Dockerfile
index e3199b7..35c8af1 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -7,6 +7,7 @@ RUN apk add --no-cache \
     python3=3.12.6-r0 \
     py3-pip=24.0-r2 \
     bash=5.2.26-r0 \
+    kubectl=1.30.0-r3 \
   && addgroup -S "app" \
   && adduser -D -G "app" -h "/app" -s "/bin/bash" -u 1000 -S "app"
 
diff --git a/lib/random_user.py b/lib/random_user.py
index 406dddf..967becf 100644
--- a/lib/random_user.py
+++ b/lib/random_user.py
@@ -10,7 +10,9 @@ import string
 
 class RandomUser:
 
-    def __init__(self, callback, create_admins = False, amount = 100, password_reset_mail = 'not_provided@opendesk.internal'):
+    def __init__(self, callback, create_admins = False, amount = 100, password_reset_mail = 'not_provided@opendesk.internal', randomize='True'):
+        self.usercounter = 0
+        self.randomize=randomize
         self.input_dir_imgs_base = "./data/images_"
         self.input_files_list = {
             "firstname": "./data/firstname_gender.tsv",
@@ -24,6 +26,7 @@ class RandomUser:
         }
         self.lists = {}
         for _ in list(range(amount)):
+            self.usercounter += 1
             person = {}
 
             for category in list(self.input_files_list.keys()):
@@ -39,7 +42,7 @@ class RandomUser:
             person['is_admin'] = False
             callback(person)
             if create_admins:
-                person['username'] = person['username']+'-admin'
+                person['username'] = self.__get_username(person["firstname"], person["lastname"], admin=True)
                 person['is_admin'] = True
                 callback(person)
 
@@ -54,9 +57,18 @@ class RandomUser:
             self.lists[category] = [entry for entry in lines_with_comments if not entry.startswith('#')]
         return random.choice(self.lists[category])
 
-    def __get_username(self, firstname, lastname):
-        username = unicodedata.normalize('NFKD', firstname+"."+lastname).encode('ascii', 'ignore')
-        return username.decode().lower()
+    def __get_username(self, firstname, lastname, admin=False):
+        if self.randomize == 'True':
+            username = unicodedata.normalize('NFKD', firstname+"."+lastname).encode('ascii', 'ignore')
+            if admin:
+                return username.decode().lower()+"-admin"
+            else:
+                return username.decode().lower()
+        else:
+            if admin:
+                return 'admin.'+str(self.usercounter)
+            else:
+                return 'user.'+str(self.usercounter)
 
     def __get_title(self, gender = 'f'):
         gen_title = 'Frau' if gender == 'f' else 'Herr'
diff --git a/user_import_udm_rest_api.py b/user_import_udm_rest_api.py
index d27ac7e..84c594f 100755
--- a/user_import_udm_rest_api.py
+++ b/user_import_udm_rest_api.py
@@ -15,8 +15,9 @@ from lib.random_user import RandomUser
 from lib.import_user import ImportUser
 
 non_reconcile_groups = [
-    "cn=Domain Admins,cn=groups,dc=swp-ldap,dc=internal"
+    "cn=Domain Admins,cn=groups,dc=swp-ldap,dc=internal",
     "cn=Domain Users,cn=groups,dc=swp-ldap,dc=internal",
+    "cn=IAM API - Full Access,cn=groups,dc=swp-ldap,dc=internal",
     "cn=managed-by-attribute-Fileshare,cn=groups,dc=swp-ldap,dc=internal",
     "cn=managed-by-attribute-FileshareAdmin,cn=groups,dc=swp-ldap,dc=internal",
     "cn=managed-by-attribute-Groupware,cn=groups,dc=swp-ldap,dc=internal",
@@ -45,6 +46,7 @@ p.add('--import_filename', env_var='IMPORT_FILENAME', required=False, default=No
 p.add('--import_use_images', env_var='IMPORT_USE_IMAGES', default=False, 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', default=10, help='The number of random accounts to import if the "import_filename" was not set or found.')
+p.add('--import_random_usernames', env_var='IMPORT_RANDOM_USERNAMES', default=True, 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, 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"')
@@ -53,7 +55,7 @@ p.add('--reconcile_groups', env_var='RECONCILE_GROUPS', default=False, help='Opt
 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', 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='default.admin', help='User to authentication against the UDM REST API with.')
+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
@@ -92,7 +94,7 @@ ucs = Ucs(adm_username=options.udm_api_username, adm_password=options.udm_api_pa
 
 if not options.import_filename:
     logging.info(f"Starting random user import, as no file for import was defined.")
-    RandomUser(import_callback, create_admins=options.create_admin_accounts, amount=int(options.import_random_amount), password_reset_mail=options.password_recovery_email)
+    RandomUser(import_callback, create_admins=options.create_admin_accounts, amount=int(options.import_random_amount), password_reset_mail=options.password_recovery_email, randomize=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}'")
-- 
GitLab