protected UserModel validateAndProxyUser(RealmModel realm, UserModel user) {
    UserModel managed = managedUsers.get(user.getId());
    if (managed != null) {
      return managed;
    }

    UserFederationProvider link = getFederationLink(realm, user);
    if (link != null) {
      UserModel validatedProxyUser = link.validateAndProxy(realm, user);
      if (validatedProxyUser != null) {
        managedUsers.put(user.getId(), validatedProxyUser);
        return validatedProxyUser;
      } else {
        deleteInvalidUser(realm, user);
        return null;
      }
    }
    return user;
  }
  protected void validateUser(RealmModel realm, UserModel user) {
    if (managedUsers.containsKey(user.getId())) {
      return;
    }

    UserFederationProvider link = getFederationLink(realm, user);
    if (link != null && !link.isValid(realm, user)) {
      deleteInvalidUser(realm, user);
      throw new IllegalStateException("Federated user no longer valid");
    }
  }
 protected UserModel registerWithFederation(RealmModel realm, UserModel user) {
   for (UserFederationProviderModel federation : realm.getUserFederationProviders()) {
     UserFederationProvider fed = getFederationProvider(federation);
     if (fed.synchronizeRegistrations()) {
       user.setFederationLink(federation.getId());
       UserModel registered = fed.register(realm, user);
       managedUsers.put(registered.getId(), registered);
       return registered;
     }
   }
   return user;
 }
 protected void deleteInvalidUser(RealmModel realm, UserModel user) {
   KeycloakSession tx = session.getKeycloakSessionFactory().create();
   try {
     tx.getTransaction().begin();
     RealmModel realmModel = tx.realms().getRealm(realm.getId());
     if (realmModel == null) return;
     UserModel deletedUser = tx.userStorage().getUserById(user.getId(), realmModel);
     tx.userStorage().removeUser(realmModel, deletedUser);
     logger.infof("Removed invalid user '%s'", user.getUsername());
     tx.getTransaction().commit();
   } finally {
     tx.close();
   }
 }
 @Override
 public boolean removeUser(RealmModel realm, UserModel user) {
   UserFederationProvider link = getFederationLink(realm, user);
   if (link != null) {
     boolean fedRemoved = link.removeUser(realm, user);
     if (fedRemoved) {
       boolean localRemoved = session.userStorage().removeUser(realm, user);
       managedUsers.remove(user.getId());
       if (!localRemoved) {
         logger.warn(
             "User removed from federation provider, but failed to remove him from keycloak model");
       }
       return localRemoved;
     } else {
       logger.warn("Failed to remove user from federation provider");
       return false;
     }
   }
   return session.userStorage().removeUser(realm, user);
 }