Search in sources :

Example 31 with TimeDuration

use of password.pwm.util.java.TimeDuration in project pwm by pwm-project.

the class CryptoCookieLoginImpl method checkIfRemoteLoginCookieIsValid.

private static void checkIfRemoteLoginCookieIsValid(final PwmRequest pwmRequest, final LoginInfoBean loginInfoBean) throws PwmOperationalException, PwmUnrecoverableException {
    if (loginInfoBean.isAuthenticated() && loginInfoBean.getAuthTime() == null) {
        final String errorMsg = "decrypted login cookie does not specify a local auth time";
        final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_BAD_SESSION, errorMsg);
        throw new PwmOperationalException(errorInformation);
    }
    if (loginInfoBean.getAuthTime() != null) {
        final long sessionMaxSeconds = pwmRequest.getConfig().readSettingAsLong(PwmSetting.SESSION_MAX_SECONDS);
        final TimeDuration sessionTotalAge = TimeDuration.fromCurrent(loginInfoBean.getAuthTime());
        final TimeDuration sessionMaxAge = new TimeDuration(sessionMaxSeconds, TimeUnit.SECONDS);
        if (sessionTotalAge.isLongerThan(sessionMaxAge)) {
            final String errorMsg = "decrypted login cookie age (" + sessionTotalAge.asCompactString() + ") is older than max session seconds (" + sessionMaxAge.asCompactString() + ")";
            final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_BAD_SESSION, errorMsg);
            throw new PwmOperationalException(errorInformation);
        }
    }
    if (loginInfoBean.getReqTime() == null) {
        final String errorMsg = "decrypted login cookie does not specify a issue time";
        final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_BAD_SESSION, errorMsg);
        throw new PwmOperationalException(errorInformation);
    }
    {
        final TimeDuration loginCookieIssueAge = TimeDuration.fromCurrent(loginInfoBean.getReqTime());
        final TimeDuration maxIdleDuration = IdleTimeoutCalculator.idleTimeoutForRequest(pwmRequest);
        if (loginCookieIssueAge.isLongerThan(maxIdleDuration)) {
            final String errorMsg = "decrypted login cookie issue time (" + loginCookieIssueAge.asCompactString() + ") is older than max idle seconds (" + maxIdleDuration.asCompactString() + ")";
            final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_BAD_SESSION, errorMsg);
            throw new PwmOperationalException(errorInformation);
        }
    }
}
Also used : ErrorInformation(password.pwm.error.ErrorInformation) TimeDuration(password.pwm.util.java.TimeDuration) PwmOperationalException(password.pwm.error.PwmOperationalException)

Example 32 with TimeDuration

use of password.pwm.util.java.TimeDuration in project pwm by pwm-project.

the class PeopleSearchDataReader method makeOrgChartData.

OrgChartDataBean makeOrgChartData(final UserIdentity userIdentity, final boolean noChildren) throws PwmUnrecoverableException {
    final Instant startTime = Instant.now();
    final CacheKey cacheKey = makeCacheKey(OrgChartDataBean.class.getSimpleName(), userIdentity.toDelimitedKey() + "|" + noChildren);
    {
        // if value is cached then return;
        final String cachedOutput = pwmRequest.getPwmApplication().getCacheService().get(cacheKey);
        if (cachedOutput != null) {
            StatisticsManager.incrementStat(pwmRequest, Statistic.PEOPLESEARCH_CACHE_HITS);
            LOGGER.trace(pwmRequest, "completed makeOrgChartData of " + userIdentity.toDisplayString() + " from cache");
            return JsonUtil.deserialize(cachedOutput, OrgChartDataBean.class);
        } else {
            StatisticsManager.incrementStat(pwmRequest, Statistic.PEOPLESEARCH_CACHE_MISSES);
        }
    }
    final OrgChartDataBean orgChartData = new OrgChartDataBean();
    // make self reference
    orgChartData.setSelf(makeOrgChartReferenceForIdentity(userIdentity));
    {
        // make parent reference
        final List<UserIdentity> parentIdentities = readUserDNAttributeValues(userIdentity, peopleSearchConfiguration.getOrgChartParentAttr());
        if (parentIdentities != null && !parentIdentities.isEmpty()) {
            final UserIdentity parentIdentity = parentIdentities.iterator().next();
            orgChartData.setParent(makeOrgChartReferenceForIdentity(parentIdentity));
        }
    }
    int childCount = 0;
    if (!noChildren) {
        // make children reference
        final Map<String, OrgChartReferenceBean> sortedChildren = new TreeMap<>();
        final List<UserIdentity> childIdentities = readUserDNAttributeValues(userIdentity, peopleSearchConfiguration.getOrgChartChildAttr());
        for (final UserIdentity childIdentity : childIdentities) {
            final OrgChartReferenceBean childReference = makeOrgChartReferenceForIdentity(childIdentity);
            if (childReference != null) {
                if (childReference.getDisplayNames() != null && !childReference.getDisplayNames().isEmpty()) {
                    final String firstDisplayName = childReference.getDisplayNames().iterator().next();
                    sortedChildren.put(firstDisplayName, childReference);
                } else {
                    sortedChildren.put(String.valueOf(childCount), childReference);
                }
                childCount++;
            }
        }
        orgChartData.setChildren(Collections.unmodifiableList(new ArrayList<>(sortedChildren.values())));
    }
    if (!StringUtil.isEmpty(peopleSearchConfiguration.getOrgChartAssistantAttr())) {
        final List<UserIdentity> assistantIdentities = readUserDNAttributeValues(userIdentity, peopleSearchConfiguration.getOrgChartAssistantAttr());
        if (assistantIdentities != null && !assistantIdentities.isEmpty()) {
            final UserIdentity assistantIdentity = assistantIdentities.iterator().next();
            final OrgChartReferenceBean assistantReference = makeOrgChartReferenceForIdentity(assistantIdentity);
            if (assistantReference != null) {
                orgChartData.setAssistant(assistantReference);
            }
        }
    }
    final TimeDuration totalTime = TimeDuration.fromCurrent(startTime);
    storeDataInCache(pwmRequest.getPwmApplication(), cacheKey, orgChartData);
    LOGGER.trace(pwmRequest, "completed makeOrgChartData in " + totalTime.asCompactString() + " with " + childCount + " children");
    return orgChartData;
}
Also used : Instant(java.time.Instant) UserIdentity(password.pwm.bean.UserIdentity) ArrayList(java.util.ArrayList) TreeMap(java.util.TreeMap) ArrayList(java.util.ArrayList) List(java.util.List) TimeDuration(password.pwm.util.java.TimeDuration) CacheKey(password.pwm.svc.cache.CacheKey)

Example 33 with TimeDuration

use of password.pwm.util.java.TimeDuration in project pwm by pwm-project.

the class TokenService method init.

public void init(final PwmApplication pwmApplication) throws PwmException {
    LOGGER.trace("opening");
    status = STATUS.OPENING;
    this.pwmApplication = pwmApplication;
    this.configuration = pwmApplication.getConfig();
    storageMethod = configuration.getTokenStorageMethod();
    if (storageMethod == null) {
        final String errorMsg = "no storage method specified";
        errorInformation = new ErrorInformation(PwmError.ERROR_INVALID_CONFIG, errorMsg);
        status = STATUS.CLOSED;
        throw new PwmOperationalException(errorInformation);
    }
    try {
        DataStorageMethod usedStorageMethod = null;
        switch(storageMethod) {
            case STORE_LOCALDB:
                {
                    final DataStore dataStore = new LocalDBDataStore(pwmApplication.getLocalDB(), LocalDB.DB.TOKENS);
                    tokenMachine = new DataStoreTokenMachine(pwmApplication, this, dataStore);
                    usedStorageMethod = DataStorageMethod.LOCALDB;
                    break;
                }
            case STORE_DB:
                {
                    final DataStore dataStore = new DatabaseDataStore(pwmApplication.getDatabaseService(), DatabaseTable.TOKENS);
                    tokenMachine = new DataStoreTokenMachine(pwmApplication, this, dataStore);
                    usedStorageMethod = DataStorageMethod.DB;
                    break;
                }
            case STORE_CRYPTO:
                tokenMachine = new CryptoTokenMachine(this);
                usedStorageMethod = DataStorageMethod.CRYPTO;
                break;
            case STORE_LDAP:
                tokenMachine = new LdapTokenMachine(this, pwmApplication);
                usedStorageMethod = DataStorageMethod.LDAP;
                break;
            default:
                JavaHelper.unhandledSwitchStatement(storageMethod);
        }
        serviceInfo = new ServiceInfoBean(Collections.singletonList(usedStorageMethod));
    } catch (PwmException e) {
        final String errorMsg = "unable to start token manager: " + e.getErrorInformation().getDetailedErrorMsg();
        final ErrorInformation newErrorInformation = new ErrorInformation(e.getError(), errorMsg);
        errorInformation = newErrorInformation;
        LOGGER.error(newErrorInformation.toDebugStr());
        status = STATUS.CLOSED;
        return;
    }
    executorService = Executors.newSingleThreadScheduledExecutor(JavaHelper.makePwmThreadFactory(JavaHelper.makeThreadName(pwmApplication, this.getClass()) + "-", true));
    final TimerTask cleanerTask = new CleanerTask();
    {
        final int cleanerFrequencySeconds = Integer.parseInt(configuration.readAppProperty(AppProperty.TOKEN_CLEANER_INTERVAL_SECONDS));
        final TimeDuration cleanerFrequency = new TimeDuration(cleanerFrequencySeconds, TimeUnit.SECONDS);
        executorService.scheduleAtFixedRate(cleanerTask, 10, cleanerFrequencySeconds, TimeUnit.SECONDS);
        LOGGER.trace("token cleanup will occur every " + cleanerFrequency.asCompactString());
    }
    verifyPwModifyTime = Boolean.parseBoolean(configuration.readAppProperty(AppProperty.TOKEN_VERIFY_PW_MODIFY_TIME));
    status = STATUS.OPEN;
    LOGGER.debug("open");
}
Also used : DataStorageMethod(password.pwm.config.option.DataStorageMethod) PwmOperationalException(password.pwm.error.PwmOperationalException) PwmException(password.pwm.error.PwmException) ErrorInformation(password.pwm.error.ErrorInformation) LocalDBDataStore(password.pwm.util.localdb.LocalDBDataStore) DatabaseDataStore(password.pwm.util.db.DatabaseDataStore) TimerTask(java.util.TimerTask) DataStore(password.pwm.util.DataStore) LocalDBDataStore(password.pwm.util.localdb.LocalDBDataStore) DatabaseDataStore(password.pwm.util.db.DatabaseDataStore) TimeDuration(password.pwm.util.java.TimeDuration)

Example 34 with TimeDuration

use of password.pwm.util.java.TimeDuration in project pwm by pwm-project.

the class TokenUtil method initializeAndSendToken.

public static void initializeAndSendToken(final PwmRequest pwmRequest, final TokenInitAndSendRequest tokenInitAndSendRequest) throws PwmUnrecoverableException {
    final Configuration config = pwmRequest.getConfig();
    final UserInfo userInfo = tokenInitAndSendRequest.getUserInfo();
    final Map<String, String> tokenMapData = new LinkedHashMap<>();
    final MacroMachine macroMachine;
    {
        if (tokenInitAndSendRequest.getMacroMachine() != null) {
            macroMachine = tokenInitAndSendRequest.getMacroMachine();
        } else if (tokenInitAndSendRequest.getUserInfo() != null) {
            macroMachine = MacroMachine.forUser(pwmRequest, userInfo.getUserIdentity(), makeTokenDestStringReplacer(tokenInitAndSendRequest.getTokenDestinationItem()));
        } else {
            macroMachine = null;
        }
    }
    if (userInfo != null) {
        final Instant userLastPasswordChange = userInfo.getPasswordLastModifiedTime();
        if (userLastPasswordChange != null) {
            final String userChangeString = JavaHelper.toIsoDate(userLastPasswordChange);
            tokenMapData.put(PwmConstants.TOKEN_KEY_PWD_CHG_DATE, userChangeString);
        }
    }
    if (tokenInitAndSendRequest.getInputTokenData() != null) {
        tokenMapData.putAll(tokenInitAndSendRequest.getInputTokenData());
    }
    final String tokenKey;
    final TokenPayload tokenPayload;
    {
        final TimeDuration tokenLifetime = tokenInitAndSendRequest.getTokenLifetime() == null ? new TimeDuration(config.readSettingAsLong(PwmSetting.TOKEN_LIFETIME), TimeUnit.SECONDS) : tokenInitAndSendRequest.getTokenLifetime();
        try {
            tokenPayload = pwmRequest.getPwmApplication().getTokenService().createTokenPayload(tokenInitAndSendRequest.getTokenType(), tokenLifetime, tokenMapData, userInfo == null ? null : userInfo.getUserIdentity(), tokenInitAndSendRequest.getTokenDestinationItem());
            tokenKey = pwmRequest.getPwmApplication().getTokenService().generateNewToken(tokenPayload, pwmRequest.getSessionLabel());
        } catch (PwmOperationalException e) {
            throw new PwmUnrecoverableException(e.getErrorInformation());
        }
    }
    final EmailItemBean emailItemBean = tokenInitAndSendRequest.getEmailToSend() == null ? null : config.readSettingAsEmail(tokenInitAndSendRequest.getEmailToSend(), pwmRequest.getLocale());
    final String smsMessage = tokenInitAndSendRequest.getSmsToSend() == null ? null : config.readSettingAsLocalizedString(tokenInitAndSendRequest.getSmsToSend(), pwmRequest.getLocale());
    TokenService.TokenSender.sendToken(TokenService.TokenSendInfo.builder().pwmApplication(pwmRequest.getPwmApplication()).userInfo(userInfo).macroMachine(macroMachine).configuredEmailSetting(emailItemBean).tokenDestinationItem(tokenInitAndSendRequest.getTokenDestinationItem()).smsMessage(smsMessage).tokenKey(tokenKey).sessionLabel(pwmRequest.getSessionLabel()).build());
}
Also used : Configuration(password.pwm.config.Configuration) EmailItemBean(password.pwm.bean.EmailItemBean) Instant(java.time.Instant) MacroMachine(password.pwm.util.macro.MacroMachine) UserInfo(password.pwm.ldap.UserInfo) TimeDuration(password.pwm.util.java.TimeDuration) PwmUnrecoverableException(password.pwm.error.PwmUnrecoverableException) LinkedHashMap(java.util.LinkedHashMap) PwmOperationalException(password.pwm.error.PwmOperationalException)

Example 35 with TimeDuration

use of password.pwm.util.java.TimeDuration in project pwm by pwm-project.

the class Populator method flushBuffer.

private void flushBuffer() throws LocalDBException {
    final long startTime = System.currentTimeMillis();
    // add the elements
    localDB.putAll(rootWordlist.getWordlistDB(), bufferedWords);
    if (abortFlag) {
        return;
    }
    // mark how long the buffer close took
    final long commitTime = System.currentTimeMillis() - startTime;
    transactionCalculator.recordLastTransactionDuration(commitTime);
    if (bufferedWords.size() > 0) {
        final StringBuilder sb = new StringBuilder();
        sb.append(rootWordlist.debugLabel).append(" ");
        sb.append("read ").append(loopLines).append(", ");
        sb.append("saved ");
        sb.append(bufferedWords.size()).append(" words");
        sb.append(" (").append(new TimeDuration(commitTime).asCompactString()).append(")");
        LOGGER.trace(sb.toString());
    }
    // clear the buffers.
    bufferedWords.clear();
    loopLines = 0;
}
Also used : TimeDuration(password.pwm.util.java.TimeDuration)

Aggregations

TimeDuration (password.pwm.util.java.TimeDuration)75 Instant (java.time.Instant)28 PwmUnrecoverableException (password.pwm.error.PwmUnrecoverableException)22 ErrorInformation (password.pwm.error.ErrorInformation)19 PwmException (password.pwm.error.PwmException)14 ArrayList (java.util.ArrayList)12 LinkedHashMap (java.util.LinkedHashMap)12 IOException (java.io.IOException)9 Configuration (password.pwm.config.Configuration)8 PwmOperationalException (password.pwm.error.PwmOperationalException)8 ChaiUnavailableException (com.novell.ldapchai.exception.ChaiUnavailableException)7 Map (java.util.Map)7 UserIdentity (password.pwm.bean.UserIdentity)7 HashMap (java.util.HashMap)6 HashSet (java.util.HashSet)6 List (java.util.List)6 MacroMachine (password.pwm.util.macro.MacroMachine)6 BigDecimal (java.math.BigDecimal)5 Date (java.util.Date)5 Locale (java.util.Locale)5