Search in sources :

Example 21 with TimeDuration

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

the class HelpdeskServlet method restVerifyVerificationTokenRequest.

@ActionHandler(action = "verifyVerificationToken")
private ProcessStatus restVerifyVerificationTokenRequest(final PwmRequest pwmRequest) throws IOException, PwmUnrecoverableException, ServletException {
    final Instant startTime = Instant.now();
    final HelpdeskVerificationRequestBean helpdeskVerificationRequestBean = JsonUtil.deserialize(pwmRequest.readRequestBodyAsString(), HelpdeskVerificationRequestBean.class);
    final String token = helpdeskVerificationRequestBean.getCode();
    final SecureService secureService = pwmRequest.getPwmApplication().getSecureService();
    final HelpdeskVerificationRequestBean.TokenData tokenData = secureService.decryptObject(helpdeskVerificationRequestBean.getTokenData(), HelpdeskVerificationRequestBean.TokenData.class);
    final UserIdentity userIdentity = UserIdentity.fromKey(helpdeskVerificationRequestBean.getUserKey(), pwmRequest.getPwmApplication());
    if (tokenData == null || tokenData.getIssueDate() == null || tokenData.getToken() == null || tokenData.getToken().isEmpty()) {
        final String errorMsg = "token data is corrupted";
        throw new PwmUnrecoverableException(new ErrorInformation(PwmError.ERROR_TOKEN_INCORRECT, errorMsg));
    }
    final TimeDuration maxTokenAge = new TimeDuration(Long.parseLong(pwmRequest.getConfig().readAppProperty(AppProperty.HELPDESK_TOKEN_MAX_AGE)) * 1000);
    final Date maxTokenAgeTimestamp = new Date(System.currentTimeMillis() - maxTokenAge.getTotalMilliseconds());
    if (tokenData.getIssueDate().before(maxTokenAgeTimestamp)) {
        final String errorMsg = "token is older than maximum issue time (" + maxTokenAge.asCompactString() + ")";
        throw new PwmUnrecoverableException(new ErrorInformation(PwmError.ERROR_TOKEN_EXPIRED, errorMsg));
    }
    final boolean passed = tokenData.getToken().equals(token);
    final HelpdeskVerificationStateBean verificationStateBean = HelpdeskVerificationStateBean.fromClientString(pwmRequest, helpdeskVerificationRequestBean.getVerificationState());
    if (passed) {
        final PwmSession pwmSession = pwmRequest.getPwmSession();
        final HelpdeskAuditRecord auditRecord = new AuditRecordFactory(pwmRequest).createHelpdeskAuditRecord(AuditEvent.HELPDESK_VERIFY_TOKEN, pwmSession.getUserInfo().getUserIdentity(), null, userIdentity, pwmSession.getSessionStateBean().getSrcAddress(), pwmSession.getSessionStateBean().getSrcHostname());
        pwmRequest.getPwmApplication().getAuditManager().submit(auditRecord);
        verificationStateBean.addRecord(userIdentity, IdentityVerificationMethod.TOKEN);
    } else {
        final PwmSession pwmSession = pwmRequest.getPwmSession();
        final HelpdeskAuditRecord auditRecord = new AuditRecordFactory(pwmRequest).createHelpdeskAuditRecord(AuditEvent.HELPDESK_VERIFY_TOKEN_INCORRECT, pwmSession.getUserInfo().getUserIdentity(), null, userIdentity, pwmSession.getSessionStateBean().getSrcAddress(), pwmSession.getSessionStateBean().getSrcHostname());
        pwmRequest.getPwmApplication().getAuditManager().submit(auditRecord);
    }
    // add a delay to prevent continuous checks
    final long delayMs = Long.parseLong(pwmRequest.getConfig().readAppProperty(AppProperty.HELPDESK_VERIFICATION_INVALID_DELAY_MS));
    while (TimeDuration.fromCurrent(startTime).isShorterThan(delayMs)) {
        JavaHelper.pause(100);
    }
    final HelpdeskVerificationResponseBean responseBean = new HelpdeskVerificationResponseBean(passed, verificationStateBean.toClientString(pwmRequest.getPwmApplication()));
    final RestResultBean restResultBean = RestResultBean.withData(responseBean);
    pwmRequest.outputJsonResult(restResultBean);
    return ProcessStatus.Halt;
}
Also used : SecureService(password.pwm.util.secure.SecureService) Instant(java.time.Instant) UserIdentity(password.pwm.bean.UserIdentity) PwmUnrecoverableException(password.pwm.error.PwmUnrecoverableException) Date(java.util.Date) HelpdeskAuditRecord(password.pwm.svc.event.HelpdeskAuditRecord) ErrorInformation(password.pwm.error.ErrorInformation) AuditRecordFactory(password.pwm.svc.event.AuditRecordFactory) TimeDuration(password.pwm.util.java.TimeDuration) PwmSession(password.pwm.http.PwmSession) RestResultBean(password.pwm.ws.server.RestResultBean)

Example 22 with TimeDuration

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

the class SessionFilter method processFilter.

public void processFilter(final PwmApplicationMode mode, final PwmRequest pwmRequest, final PwmFilterChain chain) throws IOException, ServletException, PwmUnrecoverableException {
    final int requestID = REQUEST_COUNTER.incrementAndGet();
    // output request information to debug log
    final Instant startTime = Instant.now();
    pwmRequest.debugHttpRequestToLog("requestID=" + requestID);
    final PwmURL pwmURL = pwmRequest.getURL();
    if (!pwmURL.isRestService() && !pwmURL.isResourceURL()) {
        if (handleStandardRequestOperations(pwmRequest) == ProcessStatus.Halt) {
            return;
        }
    }
    try {
        chain.doFilter();
    } catch (IOException e) {
        LOGGER.trace(pwmRequest.getPwmSession(), "IO exception during servlet processing: " + e.getMessage());
        throw new ServletException(e);
    } catch (Throwable e) {
        if (e instanceof ServletException && e.getCause() != null && e.getCause() instanceof NoClassDefFoundError && e.getCause().getMessage() != null && e.getCause().getMessage().contains("JaxbAnnotationIntrospector")) {
            // this is a jersey 1.18 bug that occurs once per execution
            LOGGER.debug("ignoring JaxbAnnotationIntrospector NoClassDefFoundError: " + e.getMessage());
        } else {
            LOGGER.warn(pwmRequest.getPwmSession(), "unhandled exception " + e.getMessage(), e);
        }
        throw new ServletException(e);
    }
    final TimeDuration requestExecuteTime = TimeDuration.fromCurrent(startTime);
    pwmRequest.debugHttpRequestToLog("completed requestID=" + requestID + " in " + requestExecuteTime.asCompactString());
}
Also used : ServletException(javax.servlet.ServletException) Instant(java.time.Instant) PwmURL(password.pwm.http.PwmURL) TimeDuration(password.pwm.util.java.TimeDuration) IOException(java.io.IOException)

Example 23 with TimeDuration

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

the class AdminServlet method restAuditDataHandler.

@ActionHandler(action = "auditData")
private ProcessStatus restAuditDataHandler(final PwmRequest pwmRequest) throws PwmUnrecoverableException, IOException {
    final Instant startTime = Instant.now();
    final TimeDuration maxSearchTime = new TimeDuration(10, TimeUnit.SECONDS);
    final int max = readMaxParameter(pwmRequest, 100, 10 * 1000);
    final AuditEvent.Type auditDataType = AuditEvent.Type.valueOf(pwmRequest.readParameterAsString("type", AuditEvent.Type.USER.name()));
    final ArrayList<AuditRecord> records = new ArrayList<>();
    final Iterator<AuditRecord> iterator = pwmRequest.getPwmApplication().getAuditManager().readVault();
    while (iterator.hasNext() && records.size() < max && TimeDuration.fromCurrent(startTime).isShorterThan(maxSearchTime)) {
        final AuditRecord loopRecord = iterator.next();
        if (auditDataType == loopRecord.getType()) {
            records.add(loopRecord);
        }
    }
    final HashMap<String, Object> resultData = new HashMap<>(Collections.singletonMap("records", records));
    final RestResultBean restResultBean = RestResultBean.withData(resultData);
    LOGGER.debug(pwmRequest.getPwmSession(), "output " + records.size() + " audit records.");
    pwmRequest.outputJsonResult(restResultBean);
    return ProcessStatus.Halt;
}
Also used : HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Instant(java.time.Instant) ArrayList(java.util.ArrayList) TimeDuration(password.pwm.util.java.TimeDuration) AuditEvent(password.pwm.svc.event.AuditEvent) AuditRecord(password.pwm.svc.event.AuditRecord) RestResultBean(password.pwm.ws.server.RestResultBean)

Example 24 with TimeDuration

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

the class ReportStatusBean method makeReportStatusData.

public static ReportStatusBean makeReportStatusData(final ReportService reportService, final Locale locale) throws LocalDBException {
    final PwmNumberFormat numberFormat = PwmNumberFormat.forLocale(locale);
    final ReportStatusBean returnMap = new ReportStatusBean();
    final ReportStatusInfo reportInfo = reportService.getReportStatusInfo();
    final LinkedHashMap<String, Object> presentableMap = new LinkedHashMap<>();
    final Set<ReportService.ReportCommand> availableCommands = new HashSet<>();
    presentableMap.put("Job Engine", reportInfo.getCurrentProcess().getLabel());
    switch(reportInfo.getCurrentProcess()) {
        case RollOver:
            {
                presentableMap.put("Users Processed", numberFormat.format(reportService.getSummaryData().getTotalUsers()) + " of " + numberFormat.format(reportService.getTotalRecords()));
                availableCommands.add(ReportService.ReportCommand.Stop);
            }
            break;
        case ReadData:
            {
                presentableMap.put("Users Processed", numberFormat.format(reportInfo.getCount()));
                presentableMap.put("Users Remaining", numberFormat.format(reportService.getWorkQueueSize()));
                if (reportInfo.getJobDuration() != null) {
                    presentableMap.put("Job Time", reportInfo.getJobDuration().asLongString(locale));
                }
                if (reportInfo.getCount() > 0) {
                    final BigDecimal eventRate = reportService.getEventRate().setScale(2, RoundingMode.UP);
                    presentableMap.put("Users/Second", eventRate);
                    if (!eventRate.equals(BigDecimal.ZERO)) {
                        final int usersRemaining = reportService.getWorkQueueSize();
                        final float secondsRemaining = usersRemaining / eventRate.floatValue();
                        final TimeDuration remainingDuration = new TimeDuration(((int) secondsRemaining) * 1000);
                        presentableMap.put("Estimated Time Remaining", remainingDuration.asLongString(locale));
                    }
                }
                availableCommands.add(ReportService.ReportCommand.Stop);
            }
            break;
        case None:
            {
                if (reportInfo.getFinishDate() != null) {
                    presentableMap.put("Last Job Completed", reportInfo.getFinishDate());
                }
                availableCommands.add(ReportService.ReportCommand.Start);
                if (reportService.getTotalRecords() > 0) {
                    availableCommands.add(ReportService.ReportCommand.Clear);
                }
            }
            break;
        default:
            break;
    }
    {
        if (reportInfo.getErrors() > 0) {
            presentableMap.put("Error Count", numberFormat.format(reportInfo.getErrors()));
        }
        if (reportInfo.getLastError() != null) {
            presentableMap.put("Last Error", reportInfo.getLastError().toDebugStr());
        }
        final int totalRecords = reportService.getTotalRecords();
        presentableMap.put("Records in Cache", numberFormat.format(totalRecords));
        if (totalRecords > 0) {
            presentableMap.put("Mean Record Cache Time", reportService.getSummaryData().getMeanCacheTime());
        }
    }
    returnMap.setControllable(true);
    returnMap.setRaw(reportInfo);
    returnMap.setPresentable(presentableMap);
    returnMap.setAvailableCommands(availableCommands);
    return returnMap;
}
Also used : PwmNumberFormat(password.pwm.util.java.PwmNumberFormat) ReportStatusInfo(password.pwm.svc.report.ReportStatusInfo) TimeDuration(password.pwm.util.java.TimeDuration) BigDecimal(java.math.BigDecimal) LinkedHashMap(java.util.LinkedHashMap) HashSet(java.util.HashSet)

Example 25 with TimeDuration

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

the class ChangePasswordServlet method processCompleteAction.

@ActionHandler(action = "complete")
public ProcessStatus processCompleteAction(final PwmRequest pwmRequest) throws ServletException, PwmUnrecoverableException, IOException {
    final ChangePasswordBean cpb = pwmRequest.getPwmApplication().getSessionStateService().getBean(pwmRequest, ChangePasswordBean.class);
    final PasswordChangeProgressChecker.ProgressTracker progressTracker = cpb.getChangeProgressTracker();
    boolean isComplete = true;
    if (progressTracker != null) {
        final PasswordChangeProgressChecker checker = new PasswordChangeProgressChecker(pwmRequest.getPwmApplication(), pwmRequest.getPwmSession().getUserInfo().getUserIdentity(), pwmRequest.getSessionLabel(), pwmRequest.getLocale());
        final PasswordChangeProgressChecker.PasswordChangeProgress passwordChangeProgress = checker.figureProgress(progressTracker);
        isComplete = passwordChangeProgress.isComplete();
    }
    if (isComplete) {
        if (progressTracker != null) {
            final TimeDuration totalTime = TimeDuration.fromCurrent(progressTracker.getBeginTime());
            try {
                pwmRequest.getPwmApplication().getStatisticsManager().updateAverageValue(Statistic.AVG_PASSWORD_SYNC_TIME, totalTime.getTotalMilliseconds());
                LOGGER.trace(pwmRequest, "password sync process marked completed (" + totalTime.asCompactString() + ")");
            } catch (Exception e) {
                LOGGER.error(pwmRequest, "unable to update average password sync time statistic: " + e.getMessage());
            }
        }
        cpb.setChangeProgressTracker(null);
        final Locale locale = pwmRequest.getLocale();
        final String completeMessage = pwmRequest.getConfig().readSettingAsLocalizedString(PwmSetting.PASSWORD_COMPLETE_MESSAGE, locale);
        pwmRequest.getPwmApplication().getSessionStateService().clearBean(pwmRequest, ChangePasswordBean.class);
        if (completeMessage != null && !completeMessage.isEmpty()) {
            final MacroMachine macroMachine = pwmRequest.getPwmSession().getSessionManager().getMacroMachine(pwmRequest.getPwmApplication());
            final String expandedText = macroMachine.expandMacros(completeMessage);
            pwmRequest.setAttribute(PwmRequestAttribute.CompleteText, expandedText);
            pwmRequest.forwardToJsp(JspUrl.PASSWORD_COMPLETE);
        } else {
            pwmRequest.getPwmResponse().forwardToSuccessPage(Message.Success_PasswordChange);
        }
    } else {
        forwardToWaitPage(pwmRequest);
    }
    return ProcessStatus.Halt;
}
Also used : Locale(java.util.Locale) ChangePasswordBean(password.pwm.http.bean.ChangePasswordBean) MacroMachine(password.pwm.util.macro.MacroMachine) TimeDuration(password.pwm.util.java.TimeDuration) PasswordChangeProgressChecker(password.pwm.ldap.PasswordChangeProgressChecker) ServletException(javax.servlet.ServletException) PwmUnrecoverableException(password.pwm.error.PwmUnrecoverableException) PwmDataValidationException(password.pwm.error.PwmDataValidationException) PwmOperationalException(password.pwm.error.PwmOperationalException) ChaiUnavailableException(com.novell.ldapchai.exception.ChaiUnavailableException) IOException(java.io.IOException)

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