@Override
  public Entity add(
      PersistencePackage persistencePackage, DynamicEntityDao dynamicEntityDao, RecordHelper helper)
      throws ServiceException {
    adminRemoteSecurityService.securityCheck(persistencePackage, EntityOperationType.ADD);
    Entity entity = persistencePackage.getEntity();
    try {
      PersistencePerspective persistencePerspective =
          persistencePackage.getPersistencePerspective();
      AdminUser adminInstance = (AdminUser) Class.forName(entity.getType()[0]).newInstance();
      Map<String, FieldMetadata> adminProperties =
          helper.getSimpleMergedProperties(AdminUser.class.getName(), persistencePerspective);
      adminInstance =
          (AdminUser) helper.createPopulatedInstance(adminInstance, entity, adminProperties, false);

      Entity errorEntity = validateLegalUsernameAndEmail(entity, adminInstance, true);
      if (errorEntity != null) {
        return errorEntity;
      }

      adminInstance.setUnencodedPassword(adminInstance.getPassword());
      adminInstance.setPassword(null);

      adminInstance = adminSecurityService.saveAdminUser(adminInstance);

      Entity adminEntity = helper.getRecord(adminProperties, adminInstance, null, null);

      return adminEntity;
    } catch (Exception e) {
      throw new ServiceException("Unable to add entity for " + entity.getType()[0], e);
    }
  }
  protected Entity validateLegalUsernameAndEmail(
      Entity entity, AdminUser adminInstance, boolean isAdd) {
    String login = entity.findProperty("login").getValue();
    String email = entity.findProperty("email").getValue();

    // We know the username/email is ok if we're doing an update and they're unchanged
    boolean skipLoginCheck = false;
    boolean skipEmailCheck = !getRequireUniqueEmailAddress();
    if (!isAdd) {
      if (StringUtils.equals(login, adminInstance.getLogin())) {
        skipLoginCheck = true;
      }

      if (!getRequireUniqueEmailAddress() || StringUtils.equals(email, adminInstance.getEmail())) {
        skipEmailCheck = true;
      }
    }

    if (!skipLoginCheck && adminSecurityService.readAdminUserByUserName(login) != null) {
      entity.addValidationError("login", "admin.nonUniqueUsernameError");
      return entity;
    }

    if (!skipEmailCheck
        && CollectionUtils.isNotEmpty(adminSecurityService.readAdminUsersByEmail(email))) {
      entity.addValidationError("email", "admin.nonUniqueEmailError");
      return entity;
    }

    return null;
  }
  @DataProvider(name = "setupAdminUser")
  public static Object[][] createAdminUser() {
    AdminUser adminUser = new AdminUserImpl();
    adminUser.setName("TestAdminUserName");
    adminUser.setLogin("TestAdminUserLogin");
    adminUser.setEmail("*****@*****.**");
    adminUser.setPassword("TestAdminUserPassword");

    return new Object[][] {new Object[] {adminUser}};
  }
 protected void validateUserUpdateSecurity(
     PersistencePackage persistencePackage, AdminUser changingUser) throws ServiceException {
   // The current user can update their data, but they cannot update other user's data.
   if (!adminRemoteSecurityService.getPersistentAdminUser().getId().equals(changingUser.getId())) {
     adminRemoteSecurityService.securityCheck(persistencePackage, EntityOperationType.UPDATE);
   }
 }
  @Override
  public void remove(
      PersistencePackage persistencePackage, DynamicEntityDao dynamicEntityDao, RecordHelper helper)
      throws ServiceException {
    Entity entity = persistencePackage.getEntity();
    String userLoginToRemove = entity.findProperty("login").getValue();

    AdminUser persistentAdminUser = adminRemoteSecurityService.getPersistentAdminUser();

    if (persistentAdminUser != null && persistentAdminUser.getLogin() != null) {
      if (persistentAdminUser.getLogin().equals(userLoginToRemove)) {
        throw new ValidationException(entity, "admin.cantDeleteCurrentUserError");
      }
    }

    OperationType removeType =
        persistencePackage.getPersistencePerspective().getOperationTypes().getRemoveType();
    helper.getCompatibleModule(removeType).remove(persistencePackage);
  }
 public void deleteAdminUser(AdminUser user) {
   if (!em.contains(user)) {
     user =
         em.find(
             entityConfiguration.lookupEntityClass(
                 "org.broadleafcommerce.openadmin.server.security.domain.AdminUser",
                 AdminUser.class),
             user.getId());
   }
   em.remove(user);
 }
  public org.broadleafcommerce.openadmin.client.security.AdminUser getAdminUser()
      throws ServiceException, ApplicationSecurityException {
    AdminUser persistentAdminUser = getPersistentAdminUser();
    if (persistentAdminUser != null) {
      org.broadleafcommerce.openadmin.client.security.AdminUser response =
          new org.broadleafcommerce.openadmin.client.security.AdminUser();
      for (AdminRole role : persistentAdminUser.getAllRoles()) {
        response.getRoles().add(role.getName());
        for (AdminPermission permission : role.getAllPermissions()) {
          response.getPermissions().add(permission.getName());
        }
      }
      response.setUserName(persistentAdminUser.getLogin());
      response.setCurrentSandBoxId(
          String.valueOf(SandBoxContext.getSandBoxContext().getSandBoxId()));
      return response;
    }

    return null;
  }
  @Override
  public Entity update(
      PersistencePackage persistencePackage, DynamicEntityDao dynamicEntityDao, RecordHelper helper)
      throws ServiceException {
    Entity entity = persistencePackage.getEntity();
    try {
      PersistencePerspective persistencePerspective =
          persistencePackage.getPersistencePerspective();
      Map<String, FieldMetadata> adminProperties =
          helper.getSimpleMergedProperties(AdminUser.class.getName(), persistencePerspective);
      Object primaryKey = helper.getPrimaryKey(entity, adminProperties);
      AdminUser adminInstance =
          (AdminUser) dynamicEntityDao.retrieve(Class.forName(entity.getType()[0]), primaryKey);

      Entity errorEntity = validateLegalUsernameAndEmail(entity, adminInstance, false);
      if (errorEntity != null) {
        return errorEntity;
      }

      String passwordBefore = adminInstance.getPassword();
      adminInstance.setPassword(null);
      adminInstance =
          (AdminUser) helper.createPopulatedInstance(adminInstance, entity, adminProperties, false);
      Property passwordProperty = entity.getPMap().get("password");
      if (passwordProperty != null) {
        if (StringUtils.isNotEmpty(passwordProperty.getValue())) {
          adminInstance.setUnencodedPassword(passwordProperty.getValue());
          adminInstance.setPassword(null);
        } else {
          adminInstance.setPassword(passwordBefore);
        }
      }

      validateUserUpdateSecurity(persistencePackage, adminInstance);

      adminInstance = adminSecurityService.saveAdminUser(adminInstance);
      Entity adminEntity = helper.getRecord(adminProperties, adminInstance, null, null);

      return adminEntity;

    } catch (Exception e) {
      throw new ServiceException("Unable to update entity for " + entity.getType()[0], e);
    }
  }