Search in sources :

Example 46 with FormConfiguration

use of password.pwm.config.value.data.FormConfiguration in project pwm by pwm-project.

the class FormUtility method validateFormValueUniqueness.

@SuppressWarnings("checkstyle:MethodLength")
public static void validateFormValueUniqueness(final PwmApplication pwmApplication, final Map<FormConfiguration, String> formValues, final Locale locale, final Collection<UserIdentity> excludeDN, final ValidationFlag... validationFlags) throws PwmDataValidationException, PwmUnrecoverableException {
    final boolean allowResultCaching = JavaHelper.enumArrayContainsValue(validationFlags, ValidationFlag.allowResultCaching);
    final boolean checkReadOnlyAndHidden = JavaHelper.enumArrayContainsValue(validationFlags, ValidationFlag.checkReadOnlyAndHidden);
    final Map<String, String> filterClauses = new HashMap<>();
    final Map<String, String> labelMap = new HashMap<>();
    for (final Map.Entry<FormConfiguration, String> entry : formValues.entrySet()) {
        final FormConfiguration formItem = entry.getKey();
        if (formItem.isUnique()) {
            if (checkReadOnlyAndHidden || formItem.isReadonly()) {
                if (checkReadOnlyAndHidden || (formItem.getType() != FormConfiguration.Type.hidden)) {
                    final String value = entry.getValue();
                    if (value != null && value.length() > 0) {
                        filterClauses.put(formItem.getName(), value);
                        labelMap.put(formItem.getName(), formItem.getLabel(locale));
                    }
                }
            }
        }
    }
    if (filterClauses.isEmpty()) {
        // nothing to search
        return;
    }
    final StringBuilder filter = new StringBuilder();
    {
        // outer;
        filter.append("(&");
        // object classes;
        filter.append("(|");
        for (final String objectClass : pwmApplication.getConfig().readSettingAsStringArray(PwmSetting.DEFAULT_OBJECT_CLASSES)) {
            filter.append("(objectClass=").append(objectClass).append(")");
        }
        filter.append(")");
        // attributes
        filter.append("(|");
        for (final Map.Entry<String, String> entry : filterClauses.entrySet()) {
            final String name = entry.getKey();
            final String value = entry.getValue();
            filter.append("(").append(name).append("=").append(StringUtil.escapeLdapFilter(value)).append(")");
        }
        filter.append(")");
        filter.append(")");
    }
    final CacheService cacheService = pwmApplication.getCacheService();
    final CacheKey cacheKey = CacheKey.makeCacheKey(Validator.class, null, "attr_unique_check_" + filter.toString());
    if (allowResultCaching && cacheService != null) {
        final String cacheValue = cacheService.get(cacheKey);
        if (cacheValue != null) {
            if (NEGATIVE_CACHE_HIT.equals(cacheValue)) {
                return;
            } else {
                final ErrorInformation errorInformation = JsonUtil.deserialize(cacheValue, ErrorInformation.class);
                throw new PwmDataValidationException(errorInformation);
            }
        }
    }
    final SearchHelper searchHelper = new SearchHelper();
    searchHelper.setFilterAnd(filterClauses);
    final SearchConfiguration searchConfiguration = SearchConfiguration.builder().filter(filter.toString()).build();
    final int resultSearchSizeLimit = 1 + (excludeDN == null ? 0 : excludeDN.size());
    final long cacheLifetimeMS = Long.parseLong(pwmApplication.getConfig().readAppProperty(AppProperty.CACHE_FORM_UNIQUE_VALUE_LIFETIME_MS));
    final CachePolicy cachePolicy = CachePolicy.makePolicyWithExpirationMS(cacheLifetimeMS);
    try {
        final UserSearchEngine userSearchEngine = pwmApplication.getUserSearchEngine();
        final Map<UserIdentity, Map<String, String>> results = new LinkedHashMap<>(userSearchEngine.performMultiUserSearch(searchConfiguration, resultSearchSizeLimit, Collections.emptyList(), SessionLabel.SYSTEM_LABEL));
        if (excludeDN != null && !excludeDN.isEmpty()) {
            for (final UserIdentity loopIgnoreIdentity : excludeDN) {
                results.keySet().removeIf(loopIgnoreIdentity::equals);
            }
        }
        if (!results.isEmpty()) {
            final UserIdentity userIdentity = results.keySet().iterator().next();
            if (labelMap.size() == 1) {
                // since only one value searched, it must be that one value
                final String attributeName = labelMap.values().iterator().next();
                LOGGER.trace("found duplicate value for attribute '" + attributeName + "' on entry " + userIdentity);
                final ErrorInformation error = new ErrorInformation(PwmError.ERROR_FIELD_DUPLICATE, null, new String[] { attributeName });
                throw new PwmDataValidationException(error);
            }
            // do a compare on a user values to find one that matches.
            for (final Map.Entry<String, String> entry : filterClauses.entrySet()) {
                final String name = entry.getKey();
                final String value = entry.getValue();
                final boolean compareResult;
                try {
                    final ChaiUser theUser = pwmApplication.getProxiedChaiUser(userIdentity);
                    compareResult = theUser.compareStringAttribute(name, value);
                } catch (ChaiOperationException | ChaiUnavailableException e) {
                    final PwmError error = PwmError.forChaiError(e.getErrorCode());
                    throw new PwmUnrecoverableException(error.toInfo());
                }
                if (compareResult) {
                    final String label = labelMap.get(name);
                    LOGGER.trace("found duplicate value for attribute '" + label + "' on entry " + userIdentity);
                    final ErrorInformation error = new ErrorInformation(PwmError.ERROR_FIELD_DUPLICATE, null, new String[] { label });
                    throw new PwmDataValidationException(error);
                }
            }
            // user didn't match on the compare.. shouldn't read here but just in case
            final ErrorInformation error = new ErrorInformation(PwmError.ERROR_FIELD_DUPLICATE, null);
            throw new PwmDataValidationException(error);
        }
    } catch (PwmOperationalException e) {
        if (cacheService != null) {
            final String jsonPayload = JsonUtil.serialize(e.getErrorInformation());
            cacheService.put(cacheKey, cachePolicy, jsonPayload);
        }
        throw new PwmDataValidationException(e.getErrorInformation());
    }
    if (allowResultCaching && cacheService != null) {
        cacheService.put(cacheKey, cachePolicy, NEGATIVE_CACHE_HIT);
    }
}
Also used : ChaiUnavailableException(com.novell.ldapchai.exception.ChaiUnavailableException) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) UserSearchEngine(password.pwm.ldap.search.UserSearchEngine) PwmUnrecoverableException(password.pwm.error.PwmUnrecoverableException) SearchHelper(com.novell.ldapchai.util.SearchHelper) LinkedHashMap(java.util.LinkedHashMap) PwmOperationalException(password.pwm.error.PwmOperationalException) ErrorInformation(password.pwm.error.ErrorInformation) FormConfiguration(password.pwm.config.value.data.FormConfiguration) ChaiOperationException(com.novell.ldapchai.exception.ChaiOperationException) CacheKey(password.pwm.svc.cache.CacheKey) CacheService(password.pwm.svc.cache.CacheService) UserIdentity(password.pwm.bean.UserIdentity) PwmError(password.pwm.error.PwmError) SearchConfiguration(password.pwm.ldap.search.SearchConfiguration) PwmDataValidationException(password.pwm.error.PwmDataValidationException) CachePolicy(password.pwm.svc.cache.CachePolicy) ChaiUser(com.novell.ldapchai.ChaiUser) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map)

Example 47 with FormConfiguration

use of password.pwm.config.value.data.FormConfiguration in project pwm by pwm-project.

the class FormUtility method populateFormMapFromLdap.

public static void populateFormMapFromLdap(final List<FormConfiguration> formFields, final SessionLabel sessionLabel, final Map<FormConfiguration, String> formMap, final UserInfo userInfo) throws PwmUnrecoverableException {
    final Map<FormConfiguration, List<String>> valueMap = populateFormMapFromLdap(formFields, sessionLabel, userInfo);
    for (final FormConfiguration formConfiguration : formFields) {
        if (valueMap.containsKey(formConfiguration)) {
            final List<String> values = valueMap.get(formConfiguration);
            if (values != null && !values.isEmpty()) {
                final String value = values.iterator().next();
                formMap.put(formConfiguration, value);
            }
        }
    }
}
Also used : FormConfiguration(password.pwm.config.value.data.FormConfiguration) ArrayList(java.util.ArrayList) List(java.util.List)

Example 48 with FormConfiguration

use of password.pwm.config.value.data.FormConfiguration in project pwm by pwm-project.

the class FormUtility method populateFormMapFromLdap.

public static Map<FormConfiguration, List<String>> populateFormMapFromLdap(final List<FormConfiguration> formFields, final SessionLabel sessionLabel, final UserInfo userInfo, final Flag... flags) throws PwmUnrecoverableException {
    final boolean includeNulls = JavaHelper.enumArrayContainsValue(flags, Flag.ReturnEmptyValues);
    final List<String> formFieldNames = FormConfiguration.convertToListOfNames(formFields);
    LOGGER.trace(sessionLabel, "preparing to load form data from ldap for fields " + JsonUtil.serializeCollection(formFieldNames));
    final Map<String, List<String>> dataFromLdap = new LinkedHashMap<>();
    try {
        for (final FormConfiguration formConfiguration : formFields) {
            if (formConfiguration.getSource() == FormConfiguration.Source.ldap || formConfiguration.getSource() == null) {
                final String attribute = formConfiguration.getName();
                if (formConfiguration.isMultivalue()) {
                    final List<String> values = userInfo.readMultiStringAttribute(attribute);
                    if (includeNulls || (values != null && !values.isEmpty())) {
                        dataFromLdap.put(attribute, values);
                    }
                } else {
                    final String value = userInfo.readStringAttribute(attribute);
                    if (includeNulls || (value != null)) {
                        dataFromLdap.put(attribute, Collections.singletonList(value));
                    }
                }
            }
        }
    } catch (Exception e) {
        PwmError error = null;
        if (e instanceof ChaiException) {
            error = PwmError.forChaiError(((ChaiException) e).getErrorCode());
        }
        if (error == null || error == PwmError.ERROR_UNKNOWN) {
            error = PwmError.ERROR_LDAP_DATA_ERROR;
        }
        final ErrorInformation errorInformation = new ErrorInformation(error, "error reading current profile values: " + e.getMessage());
        LOGGER.error(sessionLabel, errorInformation.getDetailedErrorMsg());
        throw new PwmUnrecoverableException(errorInformation);
    }
    final Map<FormConfiguration, List<String>> returnMap = new LinkedHashMap<>();
    for (final FormConfiguration formItem : formFields) {
        final String attrName = formItem.getName();
        if (dataFromLdap.containsKey(attrName)) {
            final List<String> values = new ArrayList<>();
            for (final String value : dataFromLdap.get(attrName)) {
                final String parsedValue = parseInputValueToFormValue(formItem, value);
                values.add(parsedValue);
                LOGGER.trace(sessionLabel, "loaded value for form item '" + attrName + "' with value=" + value);
            }
            returnMap.put(formItem, values);
        }
    }
    return returnMap;
}
Also used : PwmError(password.pwm.error.PwmError) ArrayList(java.util.ArrayList) PwmUnrecoverableException(password.pwm.error.PwmUnrecoverableException) PwmUnrecoverableException(password.pwm.error.PwmUnrecoverableException) PwmDataValidationException(password.pwm.error.PwmDataValidationException) ChaiOperationException(com.novell.ldapchai.exception.ChaiOperationException) ChaiException(com.novell.ldapchai.exception.ChaiException) PwmOperationalException(password.pwm.error.PwmOperationalException) ChaiUnavailableException(com.novell.ldapchai.exception.ChaiUnavailableException) LinkedHashMap(java.util.LinkedHashMap) ErrorInformation(password.pwm.error.ErrorInformation) ArrayList(java.util.ArrayList) List(java.util.List) FormConfiguration(password.pwm.config.value.data.FormConfiguration) ChaiException(com.novell.ldapchai.exception.ChaiException)

Example 49 with FormConfiguration

use of password.pwm.config.value.data.FormConfiguration in project pwm by pwm-project.

the class FormUtility method asStringMap.

public static Map<String, String> asStringMap(final Map<FormConfiguration, String> input) {
    final Map<String, String> returnObj = new LinkedHashMap<>();
    for (final Map.Entry<FormConfiguration, String> entry : input.entrySet()) {
        final FormConfiguration formConfiguration = entry.getKey();
        returnObj.put(formConfiguration.getName(), entry.getValue());
        if (formConfiguration.isConfirmationRequired()) {
            final String confirmFieldName = formConfiguration.getName() + Validator.PARAM_CONFIRM_SUFFIX;
            returnObj.put(confirmFieldName, input.get(formConfiguration));
        }
    }
    return returnObj;
}
Also used : FormConfiguration(password.pwm.config.value.data.FormConfiguration) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) LinkedHashMap(java.util.LinkedHashMap)

Example 50 with FormConfiguration

use of password.pwm.config.value.data.FormConfiguration in project pwm by pwm-project.

the class FormUtility method validateFormValues.

/**
 * Validates each of the parameters in the supplied map against the vales in the embedded config
 * and checks to make sure the ParamConfig value meets the requirements of the ParamConfig itself.
 *
 * @param formValues - a Map containing String keys of parameter names and ParamConfigs as values
 * @throws password.pwm.error.PwmDataValidationException - If there is a problem with any of the fields
 * @throws password.pwm.error.PwmUnrecoverableException  if an unexpected error occurs
 */
public static void validateFormValues(final Configuration configuration, final Map<FormConfiguration, String> formValues, final Locale locale) throws PwmUnrecoverableException, PwmDataValidationException {
    for (final Map.Entry<FormConfiguration, String> entry : formValues.entrySet()) {
        final FormConfiguration formItem = entry.getKey();
        final String value = entry.getValue();
        formItem.checkValue(configuration, value, locale);
    }
}
Also used : FormConfiguration(password.pwm.config.value.data.FormConfiguration) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map)

Aggregations

FormConfiguration (password.pwm.config.value.data.FormConfiguration)63 LinkedHashMap (java.util.LinkedHashMap)26 ErrorInformation (password.pwm.error.ErrorInformation)23 Map (java.util.Map)19 PwmUnrecoverableException (password.pwm.error.PwmUnrecoverableException)15 ArrayList (java.util.ArrayList)14 HashMap (java.util.HashMap)14 PwmOperationalException (password.pwm.error.PwmOperationalException)14 List (java.util.List)13 UserIdentity (password.pwm.bean.UserIdentity)13 PwmApplication (password.pwm.PwmApplication)11 UserInfo (password.pwm.ldap.UserInfo)10 ChaiUser (com.novell.ldapchai.ChaiUser)9 Locale (java.util.Locale)9 PwmSession (password.pwm.http.PwmSession)9 SearchConfiguration (password.pwm.ldap.search.SearchConfiguration)9 ChaiOperationException (com.novell.ldapchai.exception.ChaiOperationException)8 Configuration (password.pwm.config.Configuration)7 PwmDataValidationException (password.pwm.error.PwmDataValidationException)7 UserSearchEngine (password.pwm.ldap.search.UserSearchEngine)7