Search in sources :

Example 41 with ChaiUser

use of com.novell.ldapchai.ChaiUser in project pwm by pwm-project.

the class UserSearchEngine method resolveUserDN.

private UserIdentity resolveUserDN(final String userDN) throws PwmUnrecoverableException, ChaiUnavailableException, PwmOperationalException {
    final Collection<LdapProfile> ldapProfiles = pwmApplication.getConfig().getLdapProfiles().values();
    for (final LdapProfile ldapProfile : ldapProfiles) {
        final ChaiProvider provider = pwmApplication.getProxyChaiProvider(ldapProfile.getIdentifier());
        final ChaiUser user = provider.getEntryFactory().newChaiUser(userDN);
        if (user.exists()) {
            try {
                return new UserIdentity(user.readCanonicalDN(), ldapProfile.getIdentifier());
            } catch (ChaiOperationException e) {
                LOGGER.error("unexpected error reading canonical userDN for '" + userDN + "', error: " + e.getMessage());
            }
        }
    }
    throw new PwmOperationalException(new ErrorInformation(PwmError.ERROR_CANT_MATCH_USER));
}
Also used : ErrorInformation(password.pwm.error.ErrorInformation) ChaiProvider(com.novell.ldapchai.provider.ChaiProvider) ChaiUser(com.novell.ldapchai.ChaiUser) UserIdentity(password.pwm.bean.UserIdentity) ChaiOperationException(com.novell.ldapchai.exception.ChaiOperationException) LdapProfile(password.pwm.config.profile.LdapProfile) PwmOperationalException(password.pwm.error.PwmOperationalException)

Example 42 with ChaiUser

use of com.novell.ldapchai.ChaiUser in project pwm by pwm-project.

the class LdapPermissionTester method testQueryMatch.

public static boolean testQueryMatch(final PwmApplication pwmApplication, final SessionLabel pwmSession, final UserIdentity userIdentity, final String filterString) throws PwmUnrecoverableException {
    final Instant startTime = Instant.now();
    if (userIdentity == null) {
        return false;
    }
    LOGGER.trace(pwmSession, "begin check for ldapQuery match for " + userIdentity + " using queryMatch: " + filterString);
    boolean result = false;
    if (filterString == null || filterString.length() < 1) {
        LOGGER.trace(pwmSession, "missing queryMatch value, skipping check");
    } else if ("(objectClass=*)".equalsIgnoreCase(filterString) || "objectClass=*".equalsIgnoreCase(filterString)) {
        LOGGER.trace(pwmSession, "queryMatch check is guaranteed to be true, skipping ldap query");
        result = true;
    } else {
        try {
            LOGGER.trace(pwmSession, "checking ldap to see if " + userIdentity + " matches '" + filterString + "'");
            final ChaiUser theUser = pwmApplication.getProxiedChaiUser(userIdentity);
            final Map<String, Map<String, String>> results = theUser.getChaiProvider().search(theUser.getEntryDN(), filterString, Collections.emptySet(), SearchScope.BASE);
            if (results.size() == 1 && results.keySet().contains(theUser.getEntryDN())) {
                result = true;
            }
        } catch (ChaiException e) {
            LOGGER.warn(pwmSession, "LDAP error during check for " + userIdentity + " using " + filterString + ", error:" + e.getMessage());
        }
    }
    final String logMsg = "user " + userIdentity.toDisplayString() + " is " + (result ? "" : "not ") + "a match for filter '" + filterString + "'" + " (" + TimeDuration.fromCurrent(startTime).asCompactString() + ")";
    LOGGER.debug(pwmSession, logMsg);
    return result;
}
Also used : ChaiUser(com.novell.ldapchai.ChaiUser) Instant(java.time.Instant) ChaiException(com.novell.ldapchai.exception.ChaiException) TreeMap(java.util.TreeMap) Map(java.util.Map)

Example 43 with ChaiUser

use of com.novell.ldapchai.ChaiUser in project pwm by pwm-project.

the class PwNotifyEngine method processUserIdentity.

private boolean processUserIdentity(final UserIdentity userIdentity) throws PwmUnrecoverableException {
    if (!LdapPermissionTester.testUserPermissions(pwmApplication, SessionLabel.SYSTEM_LABEL, userIdentity, permissionList)) {
        return false;
    }
    final ChaiUser theUser = pwmApplication.getProxiedChaiUser(userIdentity);
    final Instant passwordExpirationTime = LdapOperationsHelper.readPasswordExpirationTime(theUser);
    if (passwordExpirationTime == null || passwordExpirationTime.isBefore(Instant.now())) {
        return false;
    }
    final int nextDayInterval = figureNextDayInterval(passwordExpirationTime);
    if (nextDayInterval < 1) {
        return false;
    }
    if (checkIfNoticeAlreadySent(userIdentity, passwordExpirationTime, nextDayInterval)) {
        log("notice for interval " + nextDayInterval + " already sent for " + userIdentity.toDisplayString());
        return false;
    }
    log("sending notice to " + userIdentity.toDisplayString() + " for interval " + nextDayInterval);
    {
        final PwNotifyDbStorageService dbStorage = new PwNotifyDbStorageService(pwmApplication);
        dbStorage.writeStoredState(userIdentity, SESSION_LABEL, new StoredNotificationState(passwordExpirationTime, Instant.now(), nextDayInterval));
    }
    sendNoticeEmail(userIdentity);
    return true;
}
Also used : ChaiUser(com.novell.ldapchai.ChaiUser) Instant(java.time.Instant)

Example 44 with ChaiUser

use of com.novell.ldapchai.ChaiUser 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 45 with ChaiUser

use of com.novell.ldapchai.ChaiUser in project pwm by pwm-project.

the class LdapTokenMachine method removeToken.

public void removeToken(final TokenKey tokenKey) throws PwmOperationalException, PwmUnrecoverableException {
    final TokenPayload payload = retrieveToken(tokenKey);
    if (payload != null) {
        final UserIdentity userIdentity = payload.getUserIdentity();
        try {
            final ChaiUser chaiUser = pwmApplication.getProxiedChaiUser(userIdentity);
            chaiUser.deleteAttribute(tokenAttribute, null);
        } catch (ChaiException e) {
            final String errorMsg = "unexpected ldap error removing token: " + e.getMessage();
            final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_UNKNOWN, errorMsg);
            throw new PwmOperationalException(errorInformation);
        }
    }
}
Also used : ErrorInformation(password.pwm.error.ErrorInformation) ChaiUser(com.novell.ldapchai.ChaiUser) UserIdentity(password.pwm.bean.UserIdentity) ChaiException(com.novell.ldapchai.exception.ChaiException) PwmOperationalException(password.pwm.error.PwmOperationalException)

Aggregations

ChaiUser (com.novell.ldapchai.ChaiUser)69 ErrorInformation (password.pwm.error.ErrorInformation)38 UserIdentity (password.pwm.bean.UserIdentity)30 PwmUnrecoverableException (password.pwm.error.PwmUnrecoverableException)27 ChaiOperationException (com.novell.ldapchai.exception.ChaiOperationException)25 PwmOperationalException (password.pwm.error.PwmOperationalException)23 ChaiUnavailableException (com.novell.ldapchai.exception.ChaiUnavailableException)21 ChaiException (com.novell.ldapchai.exception.ChaiException)18 ChaiProvider (com.novell.ldapchai.provider.ChaiProvider)18 PwmApplication (password.pwm.PwmApplication)16 PwmSession (password.pwm.http.PwmSession)12 UserInfo (password.pwm.ldap.UserInfo)12 Instant (java.time.Instant)10 FormConfiguration (password.pwm.config.value.data.FormConfiguration)10 PasswordData (password.pwm.util.PasswordData)10 MacroMachine (password.pwm.util.macro.MacroMachine)10 ArrayList (java.util.ArrayList)9 List (java.util.List)9 LdapProfile (password.pwm.config.profile.LdapProfile)9 Locale (java.util.Locale)8