From 80ba5da9c80c54eb62f3f929602984ec783b000b Mon Sep 17 00:00:00 2001 From: Davor Date: Tue, 19 Jul 2022 16:48:22 +0200 Subject: [PATCH] added more information about user batch creation --- areas/users/user_service.py | 43 +++++++++++++++++++++++++++++-------- 1 file changed, 34 insertions(+), 9 deletions(-) diff --git a/areas/users/user_service.py b/areas/users/user_service.py index a0abfda..2ad5a73 100644 --- a/areas/users/user_service.py +++ b/areas/users/user_service.py @@ -5,6 +5,8 @@ from helpers import KratosApi from flask import current_app +from helpers.error_handler import KratosError + class UserService: no_access_role_id = 3 @@ -101,21 +103,44 @@ class UserService: # for every item in array call Kratos - check if there can be batch create on Kratos # - if yes, what happens with the batch if there is at least one existing email created_users = [] - not_created_users = [] + existing_users = [] + creation_failed_users = [] for user_data in data['users']: - user_mail = user_data["email"] - if not user_mail: + user_email = user_data["email"] + if not user_email: return try: - user = UserService.post_user(user_data) - current_app.logger.info(f"Batch create user: {user_mail}") - created_users.append(user) + UserService.post_user(user_data) + current_app.logger.info(f"Batch create user: {user_email}") + created_users.append(user_email) + except KratosError as err: + status_code = err.args[1] + if status_code == 409: + existing_users.append(user_email) + elif status_code == 400: + creation_failed_users.append(user_email) + current_app.logger.error( + f"Exception calling Kratos: {err} on creating user: {user_email} {status_code}") except Exception as error: - current_app.logger.error(f"Exception calling Kratos: {error} on creating user: {user_mail}") - not_created_users.append(user_mail) + current_app.logger.error( + f"Exception: {error} on creating user: {user_email}") + creation_failed_users.append(user_email) - return {"created_users": created_users, "not_created_users": not_created_users} + success_response = {} + existing_response = {} + failed_response = {} + if created_users: + success_response = {"users": created_users, + "message": f"{len(created_users)} users created"} + if existing_users: + existing_response = { + "users": existing_users, "message": f"{len(existing_users)} users already exist: {', '.join(existing_users)}"} + if creation_failed_users: + failed_response = {"users": creation_failed_users, + "message": f"{len(creation_failed_users)} users failed to create: {', '.join(creation_failed_users)}"} + + return {"success": success_response, "existing": existing_response, "failed": failed_response} @staticmethod def __insertAppRoleToUser(userId, userRes):