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);
}
}
}
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;
}
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");
}
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());
}
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;
}
Aggregations