Allow updating the username when registration as email is enabled during LDAP updates

Closes #34560

Signed-off-by: Pedro Igor <pigor.craveiro@gmail.com>
This commit is contained in:
Pedro Igor
2024-11-14 10:35:01 -03:00
committed by Marek Posolda
parent 5d600be6f2
commit dfe2f2bb54
2 changed files with 41 additions and 0 deletions

View File

@@ -187,6 +187,9 @@ public class UserAttributeLDAPStorageMapper extends AbstractLDAPStorageMapper {
UserModel.USERNAME);
}
} else if (usernameChanged) {
if (realm.isRegistrationEmailAsUsername() && username.equals(user.getEmail())) {
return;
}
throw new ModelException("Cannot change username if the realm is not configured to allow edit the usernames");
}
}

View File

@@ -37,6 +37,7 @@ import org.keycloak.component.PrioritizedComponentModel;
import org.keycloak.models.LDAPConstants;
import org.keycloak.models.RealmModel;
import org.keycloak.models.UserModel;
import org.keycloak.representations.idm.RealmRepresentation;
import org.keycloak.representations.idm.UserProfileAttributeMetadata;
import org.keycloak.representations.idm.UserRepresentation;
import org.keycloak.representations.userprofile.config.UPAttribute;
@@ -396,6 +397,43 @@ public class LDAPUserProfileTest extends AbstractLDAPTest {
appPage.assertCurrent();
}
@Test
public void testUpdateEmailWhenEmailAsUsernameEnabledAndEditUsernameDisabled() {
String username = "johnkeycloak";
UserResource johnResource = ApiUtil.findUserByUsernameId(testRealm(), username);
UserRepresentation john = johnResource.toRepresentation(true);
String email = "john@email.org";
assertUser(john, username, email, "John", "Doe", "1234");
// enable email as username
RealmRepresentation realm = testRealm().toRepresentation();
boolean initialEditUserNameAllowed = realm.isEditUsernameAllowed();
boolean initialEmailUsernameEnabled = realm.isRegistrationEmailAsUsername();
realm.setEditUsernameAllowed(false);
realm.setRegistrationEmailAsUsername(true);
testRealm().update(realm);
// update the user to force updating the username as the email
john.setEmail("john@newemail.org");
johnResource.update(john);
john = johnResource.toRepresentation(true);
assertUser(john, "john@newemail.org", "john@newemail.org", "John", "Doe", "1234");
getCleanup().addCleanup(() -> {
try {
realm.setEditUsernameAllowed(initialEditUserNameAllowed);
realm.setRegistrationEmailAsUsername(initialEmailUsernameEnabled);
testRealm().update(realm);
UserRepresentation user = johnResource.toRepresentation(true);
user.setUsername(username);
user.setEmail(email);
johnResource.update(user);
} finally {
testRealm().update(realm);
}
});
}
private void setLDAPReadOnly() {
testingClient.server().run(session -> {
LDAPTestContext ctx = LDAPTestContext.init(session, "test-ldap");