Browse Source

Add exist_ok attribute to KeycloakAdmin.create_user

This attribute allows configuration of the behaviour of create_user when a user
with the passed username already exists. If set to False, an exception will be
raised (passed through) from the API. If set to True (default), the existing
user ID will silently be returned.
master
Lukas Martini 3 years ago
parent
commit
6ed65ea4e5
No known key found for this signature in database GPG Key ID: F828A0C8C9E1BD2C
  1. 10
      README.md
  2. 10
      keycloak/keycloak_admin.py

10
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",

10
keycloak/keycloak_admin.py

@ -361,7 +361,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
@ -369,15 +369,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))

Loading…
Cancel
Save