diff --git a/README.md b/README.md index c2af7fc..095782b 100644 --- a/README.md +++ b/README.md @@ -54,6 +54,7 @@ The documentation for python-keycloak is available on [readthedocs](http://pytho * [Josha Inglis](https://bitbucket.org/joshainglis/) * [Alex](https://bitbucket.org/alex_zel/) * [Ewan Jone](https://bitbucket.org/kisamoto/) +* [Lukas Martini](https://github.com/lutoma) ## Usage @@ -125,6 +126,15 @@ new_user = keycloak_admin.create_user({"email": "example@example.com", "enabled": True, "firstName": "Example", "lastName": "Example"}) + +# Add user and raise exception if username already exists +# exist_ok currently defaults to True for backwards compatibility reasons +new_user = keycloak_admin.create_user({"email": "example@example.com", + "username": "example@example.com", + "enabled": True, + "firstName": "Example", + "lastName": "Example"}, + exist_ok=False) # Add user and set password new_user = keycloak_admin.create_user({"email": "example@example.com", diff --git a/keycloak/keycloak_admin.py b/keycloak/keycloak_admin.py index 9ec625a..a597be8 100644 --- a/keycloak/keycloak_admin.py +++ b/keycloak/keycloak_admin.py @@ -362,7 +362,7 @@ class KeycloakAdmin: data_raw = self.raw_delete(URL_ADMIN_IDP.format(**params_path)) return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204]) - def create_user(self, payload): + def create_user(self, payload, exist_ok=True): """ Create a new user. Username must be unique @@ -370,15 +370,17 @@ class KeycloakAdmin: https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_userrepresentation :param payload: UserRepresentation + :param exist_ok: If False, raise KeycloakGetError if username already exists. Otherwise, return existing user ID. :return: UserRepresentation """ params_path = {"realm-name": self.realm_name} - exists = self.get_user_id(username=payload['username']) + if exist_ok: + exists = self.get_user_id(username=payload['username']) - if exists is not None: - return str(exists) + if exists is not None: + return str(exists) data_raw = self.raw_post(URL_ADMIN_USERS.format(**params_path), data=json.dumps(payload))