From 43541d3028d975fcdbf980bd75b1d001fbeac0f4 Mon Sep 17 00:00:00 2001 From: dcampagna Date: Fri, 18 Sep 2015 10:15:14 +0200 Subject: [PATCH] Show error when username already exists (KEYCLOAK-1857) --- .../requiredactions/UpdateProfile.java | 20 +++++++++++++++- .../RequiredActionUpdateProfileTest.java | 23 +++++++++++++++++++ 2 files changed, 42 insertions(+), 1 deletion(-) diff --git a/services/src/main/java/org/keycloak/authentication/requiredactions/UpdateProfile.java b/services/src/main/java/org/keycloak/authentication/requiredactions/UpdateProfile.java index ac7862b7ad..9630f3b10a 100755 --- a/services/src/main/java/org/keycloak/authentication/requiredactions/UpdateProfile.java +++ b/services/src/main/java/org/keycloak/authentication/requiredactions/UpdateProfile.java @@ -63,7 +63,25 @@ public class UpdateProfile implements RequiredActionProvider, RequiredActionFact } if (realm.isEditUsernameAllowed()) { - user.setUsername(formData.getFirst("username")); + String username = formData.getFirst("username"); + String oldUsername = user.getUsername(); + + boolean usernameChanged = oldUsername != null ? !oldUsername.equals(username) : username != null; + + if (usernameChanged) { + + if (session.users().getUserByUsername(username, realm) != null) { + Response challenge = context.form() + .setError(Messages.USERNAME_EXISTS) + .setFormData(formData) + .createResponse(UserModel.RequiredAction.UPDATE_PROFILE); + context.challenge(challenge); + return; + } + + user.setUsername(username); + } + } user.setFirstName(formData.getFirst("firstName")); diff --git a/testsuite/integration/src/test/java/org/keycloak/testsuite/actions/RequiredActionUpdateProfileTest.java b/testsuite/integration/src/test/java/org/keycloak/testsuite/actions/RequiredActionUpdateProfileTest.java index 531ee8a3a6..545ce0cf94 100755 --- a/testsuite/integration/src/test/java/org/keycloak/testsuite/actions/RequiredActionUpdateProfileTest.java +++ b/testsuite/integration/src/test/java/org/keycloak/testsuite/actions/RequiredActionUpdateProfileTest.java @@ -247,6 +247,29 @@ public class RequiredActionUpdateProfileTest { events.assertEmpty(); } + @Test + public void updateProfileDuplicateUsername() { + loginPage.open(); + + loginPage.login("john-doh@localhost", "password"); + + updateProfilePage.assertCurrent(); + + updateProfilePage.update("New first", "New last", "new@email.com", "test-user@localhost"); + + updateProfilePage.assertCurrent(); + + // assert that form holds submitted values during validation error + Assert.assertEquals("New first", updateProfilePage.getFirstName()); + Assert.assertEquals("New last", updateProfilePage.getLastName()); + Assert.assertEquals("new@email.com", updateProfilePage.getEmail()); + Assert.assertEquals("", updateProfilePage.getUsername()); + + Assert.assertEquals("Username already exists.", updateProfilePage.getError()); + + events.assertEmpty(); + } + @Test public void updateProfileDuplicatedEmail() { loginPage.open();