From 74886aec35e0b466705aca7e02d1363ccf05ea21 Mon Sep 17 00:00:00 2001 From: Mikel Larreategi Date: Tue, 19 Nov 2024 16:14:26 +0100 Subject: [PATCH] return a 400 Bad request when trying to change the username to an existing one --- src/plone/restapi/services/users/update.py | 27 +++++++++++++++++-- .../restapi/tests/test_services_users.py | 13 ++++++++- 2 files changed, 37 insertions(+), 3 deletions(-) diff --git a/src/plone/restapi/services/users/update.py b/src/plone/restapi/services/users/update.py index 3d7d3b724..e2fdb1960 100644 --- a/src/plone/restapi/services/users/update.py +++ b/src/plone/restapi/services/users/update.py @@ -107,7 +107,20 @@ def reply(self): if security.use_email_as_login and "email" in user_settings_to_update: value = user_settings_to_update["email"] pas = getToolByName(self.context, "acl_users") - pas.updateLoginName(user.getId(), value) + + try: + pas.updateLoginName(user.getId(), value) + except ValueError: + return self._error( + 400, + "Bad request", + _( + "Cannot update login name of user to '${new_email}'.", + mapping={ + "new_email": value, + }, + ), + ) roles = user_settings_to_update.get("roles", {}) if roles: @@ -149,7 +162,17 @@ def reply(self): if security.use_email_as_login and "email" in user_settings_to_update: value = user_settings_to_update["email"] - set_own_login_name(user, value) + try: + set_own_login_name(user, value) + except ValueError: + return self._error( + 400, + "Bad request", + _( + "Cannot update login name of user to '${new_email}'.", + mapping={"new_email": value}, + ), + ) else: if self._is_anonymous: diff --git a/src/plone/restapi/tests/test_services_users.py b/src/plone/restapi/tests/test_services_users.py index 7e7f26796..2352f62af 100644 --- a/src/plone/restapi/tests/test_services_users.py +++ b/src/plone/restapi/tests/test_services_users.py @@ -1714,6 +1714,12 @@ def test_manager_changes_email_to_existing_when_login_with_email(self): }, ) self.assertFalse(email_change_response.ok) + self.assertEqual(email_change_response.status_code, 400) + email_change_response_json = email_change_response.json() + self.assertEqual( + email_change_response_json.get("error", {}).get("message"), + "Cannot update login name of user to 'second@example.com'.", + ) # Email was not changed, so log in with the old one new_login_with_old_email_response = self.anon_api_session.post( @@ -1777,7 +1783,12 @@ def test_user_changes_email_to_existing_one_when_login_with_email(self): json={"email": "second@example.com"}, ) - self.assertFalse(email_change_response.ok) + self.assertEqual(email_change_response.status_code, 400) + email_change_response_json = email_change_response.json() + self.assertEqual( + email_change_response_json.get("error", {}).get("message"), + "Cannot update login name of user to 'second@example.com'.", + ) # email was not changed, so log in with the old one new_login_with_old_email_response = self.anon_api_session.post(