diff --git a/changes/7932.feature b/changes/7932.feature new file mode 100644 index 00000000000..2826ac9bcce --- /dev/null +++ b/changes/7932.feature @@ -0,0 +1,2 @@ +Introducing a new parameter to the user_create action - with_apitoken. +When set, this parameter triggers the creation of an API token for the user. diff --git a/ckan/logic/action/create.py b/ckan/logic/action/create.py index 37530170bb1..e4098343bf8 100644 --- a/ckan/logic/action/create.py +++ b/ckan/logic/action/create.py @@ -961,7 +961,9 @@ def user_create(context: Context, } } :type plugin_extras: dict - + :param with_apitoken: whether to create an API token for the user. + (Optional) + :type with_apitoken: bool :returns: the newly created user :rtype: dictionary @@ -970,6 +972,7 @@ def user_create(context: Context, model = context['model'] schema = context.get('schema') or ckan.logic.schema.default_user_schema() session = context['session'] + with_apitoken = data_dict.pop("with_apitoken", False) _check_access('user_create', context, data_dict) @@ -1028,10 +1031,21 @@ def user_create(context: Context, # Create dashboard for user. dashboard = model.Dashboard(user.id) + session.add(dashboard) if not context.get('defer_commit'): model.repo.commit() + if with_apitoken: + if not context['user']: + context["user"] = user.name + + # Create apitoken for user. + api_token = _get_action("api_token_create")( + context, {"user": user.name, "name": "default"} + ) + user_dict["token"] = api_token["token"] + log.debug('Created user {name}'.format(name=user.name)) return user_dict diff --git a/ckan/tests/logic/action/test_create.py b/ckan/tests/logic/action/test_create.py index a2676e825e2..c00531666fe 100644 --- a/ckan/tests/logic/action/test_create.py +++ b/ckan/tests/logic/action/test_create.py @@ -1270,6 +1270,41 @@ def test_user_create_defer_commit(self): with pytest.raises(logic.NotFound): helpers.call_action("user_show", id=user_dict["name"]) + def test_create_user_with_apitoken(self): + stub = factories.User.stub() + context = {"ignore_auth": True} + user_dict = { + "name": stub.name, + "email": stub.email, + "password": "test1234", + "with_apitoken": True + } + user = helpers.call_action("user_create", context={}, **user_dict) + assert user["token"] + + user_dict = {"user_id": user["name"]} + token = helpers.call_action( + "api_token_list", context=context, **user_dict + ) + assert len(token) == 1 + + def test_create_user_with_apitoken_missing_flag(self): + stub = factories.User.stub() + context = {"ignore_auth": True} + user_dict = { + "name": stub.name, + "email": stub.email, + "password": "test1234", + } + user = helpers.call_action("user_create", context={}, **user_dict) + assert "token" not in user + + user_dict = {"user_id": user["name"]} + token = helpers.call_action( + "api_token_list", context=context, **user_dict + ) + assert not token + @pytest.mark.usefixtures("clean_db") @pytest.mark.ckan_config("ckan.auth.create_user_via_web", True)