Run validation of email addresses only for new and changed email addresses

Closes #29133

Signed-off-by: Alexander Schwartz <aschwart@redhat.com>
This commit is contained in:
Alexander Schwartz 2024-04-29 10:44:20 +02:00 committed by Pedro Igor
parent 17a700b6b9
commit d55a8b0b17

View file

@ -18,6 +18,7 @@ package org.keycloak.userprofile.validator;
import jakarta.ws.rs.core.Response;
import java.util.List;
import java.util.Objects;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.RealmModel;
@ -62,10 +63,11 @@ public class DuplicateEmailValidator implements SimpleValidator {
KeycloakSession session = context.getSession();
RealmModel realm = session.getContext().getRealm();
if (!realm.isDuplicateEmailsAllowed()) {
UserModel userByEmail = session.users().getUserByEmail(realm, value);
UserModel user = UserProfileAttributeValidationContext.from(context).getAttributeContext().getUser();
// Only check if duplicate email addresses are not allowed, and the user is either new or changed their email address
if (!realm.isDuplicateEmailsAllowed() && (user == null || !Objects.equals(user.getFirstAttribute(inputHint), value))) {
UserModel userByEmail = session.users().getUserByEmail(realm, value);
// check for duplicated email
if (userByEmail != null && (user == null || !userByEmail.getId().equals(user.getId()))) {
context.addError(new ValidationError(ID, inputHint, Messages.EMAIL_EXISTS)