protected UserModel importUserFromLDAP(
      KeycloakSession session, RealmModel realm, LDAPObject ldapUser) {
    String ldapUsername = LDAPUtils.getUsername(ldapUser, ldapIdentityStore.getConfig());
    LDAPUtils.checkUuid(ldapUser, ldapIdentityStore.getConfig());

    UserModel imported = session.userStorage().addUser(realm, ldapUsername);
    imported.setEnabled(true);

    Set<UserFederationMapperModel> federationMappers =
        realm.getUserFederationMappersByFederationProvider(getModel().getId());
    for (UserFederationMapperModel mapperModel : federationMappers) {
      if (logger.isTraceEnabled()) {
        logger.tracef("Using mapper %s during import user from LDAP", mapperModel);
      }
      LDAPFederationMapper ldapMapper = getMapper(mapperModel);
      ldapMapper.onImportUserFromLDAP(mapperModel, this, ldapUser, imported, realm, true);
    }

    String userDN = ldapUser.getDn().toString();
    imported.setFederationLink(model.getId());
    imported.setSingleAttribute(LDAPConstants.LDAP_ID, ldapUser.getUuid());
    imported.setSingleAttribute(LDAPConstants.LDAP_ENTRY_DN, userDN);

    logger.debugf(
        "Imported new user from LDAP to Keycloak DB. Username: [%s], Email: [%s], LDAP_ID: [%s], LDAP Entry DN: [%s]",
        imported.getUsername(), imported.getEmail(), ldapUser.getUuid(), userDN);
    return proxy(realm, imported, ldapUser);
  }
  public static void removeAllLDAPUsers(LDAPFederationProvider ldapProvider, RealmModel realm) {
    LDAPIdentityStore ldapStore = ldapProvider.getLdapIdentityStore();
    LDAPQuery ldapQuery = LDAPUtils.createQueryForUserSearch(ldapProvider, realm);
    List<LDAPObject> allUsers = ldapQuery.getResultList();

    for (LDAPObject ldapUser : allUsers) {
      ldapStore.remove(ldapUser);
    }
  }
  @Override
  public void updateCredential(UserCredentialModel cred) {
    if (!provider.getSupportedCredentialTypes(delegate).contains(cred.getType())) {
      delegate.updateCredential(cred);
      return;
    }

    if (cred.getType().equals(UserCredentialModel.PASSWORD)) {
      LDAPIdentityStore ldapIdentityStore = provider.getLdapIdentityStore();
      String password = cred.getValue();
      ldapIdentityStore.updatePassword(ldapObject, password);
    } else {
      logger.warnf(
          "Don't know how to update credential of type [%s] for user [%s]",
          cred.getType(), delegate.getUsername());
    }
  }
 public boolean validPassword(RealmModel realm, UserModel user, String password) {
   if (kerberosConfig.isAllowKerberosAuthentication()
       && kerberosConfig.isUseKerberosForPasswordAuthentication()) {
     // Use Kerberos JAAS (Krb5LoginModule)
     KerberosUsernamePasswordAuthenticator authenticator =
         factory.createKerberosUsernamePasswordAuthenticator(kerberosConfig);
     return authenticator.validUser(user.getUsername(), password);
   } else {
     // Use Naming LDAP API
     LDAPObject ldapUser = loadAndValidateUser(realm, user);
     return ldapIdentityStore.validatePassword(ldapUser, password);
   }
 }
  @Override
  public UserModel register(RealmModel realm, UserModel user) {
    if (editMode == EditMode.READ_ONLY || editMode == EditMode.UNSYNCED)
      throw new IllegalStateException("Registration is not supported by this ldap server");
    if (!synchronizeRegistrations())
      throw new IllegalStateException("Registration is not supported by this ldap server");

    LDAPObject ldapUser = LDAPUtils.addUserToLDAP(this, realm, user);
    LDAPUtils.checkUuid(ldapUser, ldapIdentityStore.getConfig());
    user.setSingleAttribute(LDAPConstants.LDAP_ID, ldapUser.getUuid());
    user.setSingleAttribute(LDAPConstants.LDAP_ENTRY_DN, ldapUser.getDn().toString());

    return proxy(realm, user, ldapUser);
  }
  /**
   * @param local
   * @return ldapUser corresponding to local user or null if user is no longer in LDAP
   */
  protected LDAPObject loadAndValidateUser(RealmModel realm, UserModel local) {
    LDAPObject ldapUser = loadLDAPUserByUsername(realm, local.getUsername());
    if (ldapUser == null) {
      return null;
    }
    LDAPUtils.checkUuid(ldapUser, ldapIdentityStore.getConfig());

    if (ldapUser.getUuid().equals(local.getFirstAttribute(LDAPConstants.LDAP_ID))) {
      return ldapUser;
    } else {
      logger.warnf(
          "LDAP User invalid. ID doesn't match. ID from LDAP [%s], LDAP ID from local DB: [%s]",
          ldapUser.getUuid(), local.getFirstAttribute(LDAPConstants.LDAP_ID));
      return null;
    }
  }
  public LDAPFederationProvider(
      LDAPFederationProviderFactory factory,
      KeycloakSession session,
      UserFederationProviderModel model,
      LDAPIdentityStore ldapIdentityStore) {
    this.factory = factory;
    this.session = session;
    this.model = model;
    this.ldapIdentityStore = ldapIdentityStore;
    this.kerberosConfig = new LDAPProviderKerberosConfig(model);
    this.editMode = ldapIdentityStore.getConfig().getEditMode();

    supportedCredentialTypes.add(UserCredentialModel.PASSWORD);
    if (kerberosConfig.isAllowKerberosAuthentication()) {
      supportedCredentialTypes.add(UserCredentialModel.KERBEROS);
    }
  }
  @Override
  public boolean removeUser(RealmModel realm, UserModel user) {
    if (editMode == EditMode.READ_ONLY || editMode == EditMode.UNSYNCED) {
      logger.warnf(
          "User '%s' can't be deleted in LDAP as editMode is '%s'",
          user.getUsername(), editMode.toString());
      return false;
    }

    LDAPObject ldapObject = loadAndValidateUser(realm, user);
    if (ldapObject == null) {
      logger.warnf(
          "User '%s' can't be deleted from LDAP as it doesn't exist here", user.getUsername());
      return false;
    }

    ldapIdentityStore.remove(ldapObject);
    return true;
  }
  @Override
  public UserModel getUserByEmail(RealmModel realm, String email) {
    LDAPObject ldapUser = queryByEmail(realm, email);
    if (ldapUser == null) {
      return null;
    }

    // Check here if user already exists
    String ldapUsername = LDAPUtils.getUsername(ldapUser, ldapIdentityStore.getConfig());
    if (session.userStorage().getUserByUsername(ldapUsername, realm) != null) {
      throw new ModelDuplicateException(
          "User with username '"
              + ldapUsername
              + "' already exists in Keycloak. It conflicts with LDAP user with email '"
              + email
              + "'");
    }

    return importUserFromLDAP(session, realm, ldapUser);
  }