Search in sources :

Example 56 with PwmException

use of password.pwm.error.PwmException in project pwm by pwm-project.

the class ConfigGuideServlet method restLdapHealth.

@ActionHandler(action = "ldapHealth")
private ProcessStatus restLdapHealth(final PwmRequest pwmRequest) throws IOException, PwmUnrecoverableException {
    final ConfigGuideBean configGuideBean = getBean(pwmRequest);
    final StoredConfigurationImpl storedConfigurationImpl = ConfigGuideForm.generateStoredConfig(configGuideBean);
    final Configuration tempConfiguration = new Configuration(storedConfigurationImpl);
    final PwmApplication tempApplication = new PwmApplication(pwmRequest.getPwmApplication().getPwmEnvironment().makeRuntimeInstance(tempConfiguration));
    final LDAPStatusChecker ldapStatusChecker = new LDAPStatusChecker();
    final List<HealthRecord> records = new ArrayList<>();
    final LdapProfile ldapProfile = tempConfiguration.getDefaultLdapProfile();
    switch(configGuideBean.getStep()) {
        case LDAP_SERVER:
            {
                try {
                    ConfigGuideUtils.checkLdapServer(configGuideBean);
                    records.add(password.pwm.health.HealthRecord.forMessage(HealthMessage.LDAP_OK));
                } catch (Exception e) {
                    records.add(new HealthRecord(HealthStatus.WARN, HealthTopic.LDAP, "Can not connect to remote server: " + e.getMessage()));
                }
            }
            break;
        case LDAP_PROXY:
            {
                records.addAll(ldapStatusChecker.checkBasicLdapConnectivity(tempApplication, tempConfiguration, ldapProfile, false));
                if (records.isEmpty()) {
                    records.add(password.pwm.health.HealthRecord.forMessage(HealthMessage.LDAP_OK));
                }
            }
            break;
        case LDAP_CONTEXT:
            {
                records.addAll(ldapStatusChecker.checkBasicLdapConnectivity(tempApplication, tempConfiguration, ldapProfile, true));
                if (records.isEmpty()) {
                    records.add(new HealthRecord(HealthStatus.GOOD, HealthTopic.LDAP, "LDAP Contextless Login Root validated"));
                }
            }
            break;
        case LDAP_ADMINS:
            {
                try {
                    final UserMatchViewerFunction userMatchViewerFunction = new UserMatchViewerFunction();
                    final Collection<UserIdentity> results = userMatchViewerFunction.discoverMatchingUsers(pwmRequest.getPwmApplication(), 2, storedConfigurationImpl, PwmSetting.QUERY_MATCH_PWM_ADMIN, null);
                    if (results.isEmpty()) {
                        records.add(new HealthRecord(HealthStatus.WARN, HealthTopic.LDAP, "No matching admin users"));
                    } else {
                        records.add(new HealthRecord(HealthStatus.GOOD, HealthTopic.LDAP, "Admin group validated"));
                    }
                } catch (PwmException e) {
                    records.add(new HealthRecord(HealthStatus.WARN, HealthTopic.LDAP, "Error during admin group validation: " + e.getErrorInformation().toDebugStr()));
                } catch (Exception e) {
                    records.add(new HealthRecord(HealthStatus.WARN, HealthTopic.LDAP, "Error during admin group validation: " + e.getMessage()));
                }
            }
            break;
        case LDAP_TESTUSER:
            {
                final String testUserValue = configGuideBean.getFormData().get(ConfigGuideFormField.PARAM_LDAP_TEST_USER);
                if (testUserValue != null && !testUserValue.isEmpty()) {
                    records.addAll(ldapStatusChecker.checkBasicLdapConnectivity(tempApplication, tempConfiguration, ldapProfile, false));
                    records.addAll(ldapStatusChecker.doLdapTestUserCheck(tempConfiguration, ldapProfile, tempApplication));
                } else {
                    records.add(new HealthRecord(HealthStatus.CAUTION, HealthTopic.LDAP, "No test user specified"));
                }
            }
            break;
        case DATABASE:
            {
                records.addAll(DatabaseStatusChecker.checkNewDatabaseStatus(pwmRequest.getPwmApplication(), tempConfiguration));
            }
            break;
        default:
            JavaHelper.unhandledSwitchStatement(configGuideBean.getStep());
    }
    final HealthData jsonOutput = new HealthData();
    jsonOutput.records = password.pwm.ws.server.rest.bean.HealthRecord.fromHealthRecords(records, pwmRequest.getLocale(), tempConfiguration);
    jsonOutput.timestamp = Instant.now();
    jsonOutput.overall = HealthMonitor.getMostSevereHealthStatus(records).toString();
    final RestResultBean restResultBean = RestResultBean.withData(jsonOutput);
    pwmRequest.outputJsonResult(restResultBean);
    return ProcessStatus.Halt;
}
Also used : HealthData(password.pwm.ws.server.rest.bean.HealthData) ConfigGuideBean(password.pwm.http.bean.ConfigGuideBean) StoredConfigurationImpl(password.pwm.config.stored.StoredConfigurationImpl) PwmApplication(password.pwm.PwmApplication) Configuration(password.pwm.config.Configuration) UserMatchViewerFunction(password.pwm.config.function.UserMatchViewerFunction) ArrayList(java.util.ArrayList) LdapProfile(password.pwm.config.profile.LdapProfile) ServletException(javax.servlet.ServletException) PwmUnrecoverableException(password.pwm.error.PwmUnrecoverableException) PwmOperationalException(password.pwm.error.PwmOperationalException) ChaiUnavailableException(com.novell.ldapchai.exception.ChaiUnavailableException) PwmException(password.pwm.error.PwmException) IOException(java.io.IOException) PwmException(password.pwm.error.PwmException) HealthRecord(password.pwm.health.HealthRecord) Collection(java.util.Collection) LDAPStatusChecker(password.pwm.health.LDAPStatusChecker) RestResultBean(password.pwm.ws.server.RestResultBean)

Example 57 with PwmException

use of password.pwm.error.PwmException in project pwm by pwm-project.

the class ConfigGuideServlet method restGotoStep.

@ActionHandler(action = "gotoStep")
private ProcessStatus restGotoStep(final PwmRequest pwmRequest) throws PwmUnrecoverableException, IOException, ServletException {
    final ConfigGuideBean configGuideBean = getBean(pwmRequest);
    final String requestedStep = pwmRequest.readParameterAsString("step");
    GuideStep step = GuideStep.START;
    if (requestedStep != null && requestedStep.length() > 0) {
        try {
            step = GuideStep.valueOf(requestedStep);
        } catch (IllegalArgumentException e) {
            final String errorMsg = "unknown goto step request: " + requestedStep;
            LOGGER.error(pwmRequest, errorMsg);
        }
    }
    if (step == GuideStep.START) {
        configGuideBean.getFormData().clear();
        configGuideBean.getFormData().putAll(ConfigGuideForm.defaultForm());
    } else if (step == GuideStep.NEXT) {
        step = configGuideBean.getStep().next();
        while (step != GuideStep.FINISH && !step.visible(configGuideBean)) {
            step = step.next();
        }
    } else if (step == GuideStep.PREVIOUS) {
        step = configGuideBean.getStep().previous();
        while (step != GuideStep.START && !step.visible(configGuideBean)) {
            step = step.previous();
        }
    }
    if (step == GuideStep.FINISH) {
        final ContextManager contextManager = ContextManager.getContextManager(pwmRequest);
        try {
            ConfigGuideUtils.writeConfig(contextManager, configGuideBean);
            pwmRequest.getPwmSession().getSessionStateBean().setTheme(null);
        } catch (PwmException e) {
            final RestResultBean restResultBean = RestResultBean.fromError(e.getErrorInformation(), pwmRequest);
            pwmRequest.outputJsonResult(restResultBean);
            return ProcessStatus.Halt;
        } catch (Exception e) {
            final RestResultBean restResultBean = RestResultBean.fromError(new ErrorInformation(PwmError.ERROR_UNKNOWN, "error during save: " + e.getMessage()), pwmRequest);
            pwmRequest.outputJsonResult(restResultBean);
            return ProcessStatus.Halt;
        }
        final HashMap<String, String> resultData = new HashMap<>();
        resultData.put("serverRestart", "true");
        pwmRequest.outputJsonResult(RestResultBean.withData(resultData));
        pwmRequest.invalidateSession();
    } else {
        configGuideBean.setStep(step);
        pwmRequest.outputJsonResult(RestResultBean.forSuccessMessage(pwmRequest, Message.Success_Unknown));
        LOGGER.trace("setting current step to: " + step);
    }
    return ProcessStatus.Continue;
}
Also used : PwmException(password.pwm.error.PwmException) ConfigGuideBean(password.pwm.http.bean.ConfigGuideBean) ErrorInformation(password.pwm.error.ErrorInformation) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) ContextManager(password.pwm.http.ContextManager) ServletException(javax.servlet.ServletException) PwmUnrecoverableException(password.pwm.error.PwmUnrecoverableException) PwmOperationalException(password.pwm.error.PwmOperationalException) ChaiUnavailableException(com.novell.ldapchai.exception.ChaiUnavailableException) PwmException(password.pwm.error.PwmException) IOException(java.io.IOException) RestResultBean(password.pwm.ws.server.RestResultBean)

Example 58 with PwmException

use of password.pwm.error.PwmException in project pwm by pwm-project.

the class ConfigManagerLocalDBServlet method restUploadLocalDB.

void restUploadLocalDB(final PwmRequest pwmRequest) throws IOException, ServletException, PwmUnrecoverableException {
    final PwmApplication pwmApplication = pwmRequest.getPwmApplication();
    final HttpServletRequest req = pwmRequest.getHttpServletRequest();
    if (pwmApplication.getApplicationMode() == PwmApplicationMode.RUNNING) {
        final String errorMsg = "database upload is not permitted when in running mode";
        final ErrorInformation errorInformation = new ErrorInformation(PwmError.CONFIG_UPLOAD_FAILURE, errorMsg, new String[] { errorMsg });
        pwmRequest.respondWithError(errorInformation, true);
        return;
    }
    if (!ServletFileUpload.isMultipartContent(req)) {
        final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_UNKNOWN, "no file found in upload");
        pwmRequest.outputJsonResult(RestResultBean.fromError(errorInformation, pwmRequest));
        LOGGER.error(pwmRequest, "error during database import: " + errorInformation.toDebugStr());
        return;
    }
    final InputStream inputStream = pwmRequest.readFileUploadStream(PwmConstants.PARAM_FILE_UPLOAD);
    final ContextManager contextManager = ContextManager.getContextManager(pwmRequest);
    LocalDB localDB = null;
    try {
        final File localDBLocation = pwmApplication.getLocalDB().getFileLocation();
        final Configuration configuration = pwmApplication.getConfig();
        contextManager.shutdown();
        localDB = LocalDBFactory.getInstance(localDBLocation, false, null, configuration);
        final LocalDBUtility localDBUtility = new LocalDBUtility(localDB);
        LOGGER.info(pwmRequest, "beginning LocalDB import");
        localDBUtility.importLocalDB(inputStream, LOGGER.asAppendable(PwmLogLevel.DEBUG, pwmRequest.getSessionLabel()));
        LOGGER.info(pwmRequest, "completed LocalDB import");
    } catch (Exception e) {
        final ErrorInformation errorInformation = e instanceof PwmException ? ((PwmException) e).getErrorInformation() : new ErrorInformation(PwmError.ERROR_UNKNOWN, e.getMessage());
        pwmRequest.outputJsonResult(RestResultBean.fromError(errorInformation, pwmRequest));
        LOGGER.error(pwmRequest, "error during LocalDB import: " + errorInformation.toDebugStr());
        return;
    } finally {
        if (localDB != null) {
            try {
                localDB.close();
            } catch (Exception e) {
                LOGGER.error(pwmRequest, "error closing LocalDB after import process: " + e.getMessage());
            }
        }
        contextManager.initialize();
    }
    pwmRequest.outputJsonResult(RestResultBean.forSuccessMessage(pwmRequest, Message.Success_Unknown));
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) PwmException(password.pwm.error.PwmException) ErrorInformation(password.pwm.error.ErrorInformation) PwmApplication(password.pwm.PwmApplication) Configuration(password.pwm.config.Configuration) LocalDBUtility(password.pwm.util.localdb.LocalDBUtility) InputStream(java.io.InputStream) ContextManager(password.pwm.http.ContextManager) LocalDB(password.pwm.util.localdb.LocalDB) File(java.io.File) ServletException(javax.servlet.ServletException) PwmUnrecoverableException(password.pwm.error.PwmUnrecoverableException) PwmException(password.pwm.error.PwmException) IOException(java.io.IOException) ChaiUnavailableException(com.novell.ldapchai.exception.ChaiUnavailableException)

Example 59 with PwmException

use of password.pwm.error.PwmException in project pwm by pwm-project.

the class OAuthConsumerServlet method processAction.

@Override
@SuppressWarnings("checkstyle:MethodLength")
protected void processAction(final PwmRequest pwmRequest) throws ServletException, IOException, PwmUnrecoverableException {
    final PwmApplication pwmApplication = pwmRequest.getPwmApplication();
    final Configuration config = pwmRequest.getConfig();
    final PwmSession pwmSession = pwmRequest.getPwmSession();
    final boolean userIsAuthenticated = pwmSession.isAuthenticated();
    final Optional<OAuthRequestState> oAuthRequestState = OAuthMachine.readOAuthRequestState(pwmRequest);
    final OAuthUseCase oAuthUseCaseCase = oAuthRequestState.isPresent() ? oAuthRequestState.get().getoAuthState().getUseCase() : OAuthUseCase.Authentication;
    LOGGER.trace(pwmRequest, "processing oauth return request, useCase=" + oAuthUseCaseCase + ", incoming oAuthRequestState=" + (oAuthRequestState.isPresent() ? JsonUtil.serialize(oAuthRequestState.get()) : "none"));
    // make sure it's okay to be processing this request.
    switch(oAuthUseCaseCase) {
        case Authentication:
            {
                if (!userIsAuthenticated && !pwmSession.getSessionStateBean().isOauthInProgress()) {
                    if (oAuthRequestState.isPresent()) {
                        final String nextUrl = oAuthRequestState.get().getoAuthState().getNextUrl();
                        LOGGER.debug(pwmSession, "received unrecognized oauth response, ignoring authcode and redirecting to embedded next url: " + nextUrl);
                        pwmRequest.sendRedirect(nextUrl);
                        return;
                    }
                    final String errorMsg = "oauth consumer reached, but oauth authentication has not yet been initiated.";
                    final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_OAUTH_ERROR, errorMsg);
                    pwmRequest.respondWithError(errorInformation);
                    LOGGER.error(pwmSession, errorMsg);
                    return;
                }
            }
            break;
        default:
            // for non-auth requests its okay to continue
            break;
    }
    // check if there is an "error" on the request sent from the oauth server., if there is then halt.
    {
        final String oauthRequestError = pwmRequest.readParameterAsString("error");
        if (oauthRequestError != null && !oauthRequestError.isEmpty()) {
            final String errorMsg = "incoming request from remote oauth server is indicating an error: " + oauthRequestError;
            final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_OAUTH_ERROR, errorMsg, "Remote Error: " + oauthRequestError, null);
            LOGGER.error(pwmSession, errorMsg);
            pwmRequest.respondWithError(errorInformation);
            return;
        }
    }
    // check if user is already authenticated - shouldn't be in nominal usage.
    if (userIsAuthenticated) {
        switch(oAuthUseCaseCase) {
            case Authentication:
                LOGGER.debug(pwmSession, "oauth consumer reached, but user is already authenticated; will proceed and verify authcode matches current user identity.");
                break;
            case ForgottenPassword:
                final String errorMsg = "oauth consumer reached via " + OAuthUseCase.ForgottenPassword + ", but user is already authenticated";
                final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_OAUTH_ERROR, errorMsg);
                pwmRequest.respondWithError(errorInformation);
                LOGGER.error(pwmSession, errorMsg);
                return;
            default:
                JavaHelper.unhandledSwitchStatement(oAuthUseCaseCase);
        }
    }
    // mark the inprogress flag to false, if we get this far and fail user needs to start over.
    pwmSession.getSessionStateBean().setOauthInProgress(false);
    if (!oAuthRequestState.isPresent()) {
        final String errorMsg = "state parameter is missing from oauth request";
        final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_OAUTH_ERROR, errorMsg);
        LOGGER.error(pwmSession, errorMsg);
        pwmRequest.respondWithError(errorInformation);
        return;
    }
    final OAuthState oauthState = oAuthRequestState.get().getoAuthState();
    final OAuthSettings oAuthSettings = makeOAuthSettings(pwmRequest, oauthState);
    final OAuthMachine oAuthMachine = new OAuthMachine(oAuthSettings);
    // make sure request was initiated in users current session
    if (!oAuthRequestState.get().isSessionMatch()) {
        try {
            switch(oAuthUseCaseCase) {
                case Authentication:
                    LOGGER.debug(pwmSession, "oauth consumer reached but response is not for a request issued during the current session," + " will redirect back to oauth server for verification update");
                    final String nextURL = oauthState.getNextUrl();
                    oAuthMachine.redirectUserToOAuthServer(pwmRequest, nextURL, null, null);
                    return;
                case ForgottenPassword:
                    LOGGER.debug(pwmSession, "oauth consumer reached but response is not for a request issued during the current session," + " will redirect back to forgotten password servlet");
                    pwmRequest.sendRedirect(PwmServletDefinition.ForgottenPassword);
                    return;
                default:
                    JavaHelper.unhandledSwitchStatement(oAuthUseCaseCase);
            }
        } catch (PwmUnrecoverableException e) {
            final String errorMsg = "unexpected error redirecting user to oauth page: " + e.toString();
            final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_OAUTH_ERROR, errorMsg);
            setLastError(pwmRequest, errorInformation);
            LOGGER.error(errorInformation.toDebugStr());
        }
    }
    final String requestCodeStr = pwmRequest.readParameterAsString(config.readAppProperty(AppProperty.HTTP_PARAM_OAUTH_CODE));
    LOGGER.trace(pwmSession, "received code from oauth server: " + requestCodeStr);
    final OAuthResolveResults resolveResults;
    try {
        resolveResults = oAuthMachine.makeOAuthResolveRequest(pwmRequest, requestCodeStr);
    } catch (PwmException e) {
        final String errorMsg = "unexpected error communicating with oauth server: " + e.toString();
        final ErrorInformation errorInformation = new ErrorInformation(e.getError(), errorMsg);
        setLastError(pwmRequest, errorInformation);
        LOGGER.error(errorInformation.toDebugStr());
        return;
    }
    if (resolveResults == null || resolveResults.getAccessToken() == null || resolveResults.getAccessToken().isEmpty()) {
        final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_OAUTH_ERROR, "browser redirect from oauth server did not include an access token");
        LOGGER.error(pwmRequest, errorInformation);
        pwmRequest.respondWithError(errorInformation);
        return;
    }
    if (resolveResults.getExpiresSeconds() > 0) {
        if (resolveResults.getRefreshToken() == null || resolveResults.getRefreshToken().isEmpty()) {
            final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_OAUTH_ERROR, "oauth server gave expiration for access token, but did not provide a refresh token");
            LOGGER.error(pwmRequest, errorInformation);
            pwmRequest.respondWithError(errorInformation);
            return;
        }
    }
    final String oauthSuppliedUsername;
    {
        final String getAttributeResponseBodyStr = oAuthMachine.makeOAuthGetAttributeRequest(pwmRequest, resolveResults.getAccessToken());
        final Map<String, String> getAttributeResultValues = JsonUtil.deserializeStringMap(getAttributeResponseBodyStr);
        oauthSuppliedUsername = getAttributeResultValues.get(oAuthSettings.getDnAttributeName());
        if (oauthSuppliedUsername == null || oauthSuppliedUsername.isEmpty()) {
            final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_OAUTH_ERROR, "OAuth server did not respond with an username attribute value");
            LOGGER.error(pwmRequest, errorInformation);
            pwmRequest.respondWithError(errorInformation);
            return;
        }
    }
    LOGGER.debug(pwmSession, "received user login id value from OAuth server: " + oauthSuppliedUsername);
    if (oAuthUseCaseCase == OAuthUseCase.ForgottenPassword) {
        redirectToForgottenPasswordServlet(pwmRequest, oauthSuppliedUsername);
        return;
    }
    if (userIsAuthenticated) {
        try {
            final UserSearchEngine userSearchEngine = pwmApplication.getUserSearchEngine();
            final UserIdentity resolvedIdentity = userSearchEngine.resolveUsername(oauthSuppliedUsername, null, null, pwmSession.getLabel());
            if (resolvedIdentity != null && resolvedIdentity.canonicalEquals(pwmSession.getUserInfo().getUserIdentity(), pwmApplication)) {
                LOGGER.debug(pwmSession, "verified incoming oauth code for already authenticated session does resolve to same as logged in user");
            } else {
                final String errorMsg = "incoming oauth code for already authenticated session does not resolve to same as logged in user ";
                final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_OAUTH_ERROR, errorMsg);
                LOGGER.error(pwmSession, errorMsg);
                pwmRequest.respondWithError(errorInformation);
                pwmSession.unauthenticateUser(pwmRequest);
                return;
            }
        } catch (PwmOperationalException e) {
            final String errorMsg = "error while examining incoming oauth code for already authenticated session: " + e.getMessage();
            final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_OAUTH_ERROR, errorMsg);
            LOGGER.error(pwmSession, errorMsg);
            pwmRequest.respondWithError(errorInformation);
            return;
        }
    }
    try {
        if (!userIsAuthenticated) {
            final SessionAuthenticator sessionAuthenticator = new SessionAuthenticator(pwmApplication, pwmSession, PwmAuthenticationSource.OAUTH);
            sessionAuthenticator.authUserWithUnknownPassword(oauthSuppliedUsername, AuthenticationType.AUTH_WITHOUT_PASSWORD);
        }
        // recycle the session to prevent session fixation attack.
        pwmRequest.getPwmSession().getSessionStateBean().setSessionIdRecycleNeeded(true);
        // forward to nextUrl
        final String nextUrl = oauthState.getNextUrl();
        LOGGER.debug(pwmSession, "oauth authentication completed, redirecting to originally requested URL: " + nextUrl);
        pwmRequest.sendRedirect(nextUrl);
    } catch (PwmException e) {
        LOGGER.error(pwmSession, "error during OAuth authentication attempt: " + e.getMessage());
        final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_OAUTH_ERROR, e.getMessage());
        pwmRequest.respondWithError(errorInformation);
        return;
    }
    LOGGER.trace(pwmSession, "OAuth login sequence successfully completed");
}
Also used : PwmApplication(password.pwm.PwmApplication) Configuration(password.pwm.config.Configuration) SessionAuthenticator(password.pwm.ldap.auth.SessionAuthenticator) UserSearchEngine(password.pwm.ldap.search.UserSearchEngine) UserIdentity(password.pwm.bean.UserIdentity) PwmUnrecoverableException(password.pwm.error.PwmUnrecoverableException) PwmOperationalException(password.pwm.error.PwmOperationalException) PwmException(password.pwm.error.PwmException) ErrorInformation(password.pwm.error.ErrorInformation) PwmSession(password.pwm.http.PwmSession) HashMap(java.util.HashMap) Map(java.util.Map)

Example 60 with PwmException

use of password.pwm.error.PwmException in project pwm by pwm-project.

the class HelpdeskServlet method restSendVerificationTokenRequest.

@ActionHandler(action = "sendVerificationToken")
private ProcessStatus restSendVerificationTokenRequest(final PwmRequest pwmRequest) throws IOException, PwmUnrecoverableException, ServletException, ChaiUnavailableException {
    final HelpdeskProfile helpdeskProfile = getHelpdeskProfile(pwmRequest);
    final Instant startTime = Instant.now();
    final Configuration config = pwmRequest.getConfig();
    final Map<String, String> bodyParams = pwmRequest.readBodyAsJsonStringMap();
    final UserIdentity userIdentity = UserIdentity.fromKey(bodyParams.get(PwmConstants.PARAM_USERKEY), pwmRequest.getPwmApplication());
    final UserInfo userInfo = UserInfoFactory.newUserInfo(pwmRequest.getPwmApplication(), pwmRequest.getSessionLabel(), pwmRequest.getLocale(), userIdentity, getChaiUser(pwmRequest, helpdeskProfile, userIdentity).getChaiProvider());
    final TokenDestinationItem tokenDestinationItem;
    {
        final MessageSendMethod effectiveSendMethod;
        {
            final MessageSendMethod configuredSendMethod = helpdeskProfile.readSettingAsEnum(PwmSetting.HELPDESK_TOKEN_SEND_METHOD, MessageSendMethod.class);
            if (configuredSendMethod == MessageSendMethod.CHOICE_SMS_EMAIL) {
                final String methodParamName = "method";
                final String methodParam = bodyParams.getOrDefault(methodParamName, "");
                switch(methodParam) {
                    case "sms":
                        effectiveSendMethod = MessageSendMethod.SMSONLY;
                        break;
                    case "email":
                        effectiveSendMethod = MessageSendMethod.EMAILONLY;
                        break;
                    default:
                        throw new UnsupportedOperationException("unknown tokenSendMethod: " + methodParam);
                }
            } else {
                effectiveSendMethod = configuredSendMethod;
            }
        }
        switch(effectiveSendMethod) {
            case SMSONLY:
                tokenDestinationItem = TokenDestinationItem.builder().id("0").display(userInfo.getUserSmsNumber()).value(userInfo.getUserSmsNumber()).type(TokenDestinationItem.Type.sms).build();
                break;
            case EMAILONLY:
                tokenDestinationItem = TokenDestinationItem.builder().id("0").display(userInfo.getUserEmailAddress()).value(userInfo.getUserEmailAddress()).type(TokenDestinationItem.Type.email).build();
                break;
            default:
                throw new UnsupportedOperationException("unknown tokenSendMethod: " + effectiveSendMethod);
        }
    }
    final HelpdeskDetailInfoBean helpdeskDetailInfoBean = HelpdeskDetailInfoBean.makeHelpdeskDetailInfo(pwmRequest, helpdeskProfile, userIdentity);
    if (helpdeskDetailInfoBean == null) {
        final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_MISSING_PARAMETER, "unable to read helpdesk detail data for specified user");
        LOGGER.error(pwmRequest, errorInformation);
        pwmRequest.outputJsonResult(RestResultBean.fromError(errorInformation, pwmRequest));
        return ProcessStatus.Halt;
    }
    final MacroMachine macroMachine = MacroMachine.forUser(pwmRequest.getPwmApplication(), pwmRequest.getSessionLabel(), userInfo, null);
    final String configuredTokenString = config.readAppProperty(AppProperty.HELPDESK_TOKEN_VALUE);
    final String tokenKey = macroMachine.expandMacros(configuredTokenString);
    final EmailItemBean emailItemBean = config.readSettingAsEmail(PwmSetting.EMAIL_HELPDESK_TOKEN, pwmRequest.getLocale());
    LOGGER.debug(pwmRequest, "generated token code for " + userIdentity.toDelimitedKey());
    final String smsMessage = config.readSettingAsLocalizedString(PwmSetting.SMS_HELPDESK_TOKEN_TEXT, pwmRequest.getLocale());
    try {
        TokenService.TokenSender.sendToken(TokenService.TokenSendInfo.builder().pwmApplication(pwmRequest.getPwmApplication()).userInfo(userInfo).macroMachine(macroMachine).configuredEmailSetting(emailItemBean).tokenDestinationItem(tokenDestinationItem).smsMessage(smsMessage).tokenKey(tokenKey).sessionLabel(pwmRequest.getSessionLabel()).build());
    } catch (PwmException e) {
        LOGGER.error(pwmRequest, e.getErrorInformation());
        pwmRequest.outputJsonResult(RestResultBean.fromError(e.getErrorInformation(), pwmRequest));
        return ProcessStatus.Halt;
    }
    StatisticsManager.incrementStat(pwmRequest, Statistic.HELPDESK_TOKENS_SENT);
    final HelpdeskVerificationRequestBean helpdeskVerificationRequestBean = new HelpdeskVerificationRequestBean();
    helpdeskVerificationRequestBean.setDestination(tokenDestinationItem.getDisplay());
    helpdeskVerificationRequestBean.setUserKey(bodyParams.get(PwmConstants.PARAM_USERKEY));
    final HelpdeskVerificationRequestBean.TokenData tokenData = new HelpdeskVerificationRequestBean.TokenData();
    tokenData.setToken(tokenKey);
    tokenData.setIssueDate(new Date());
    final SecureService secureService = pwmRequest.getPwmApplication().getSecureService();
    helpdeskVerificationRequestBean.setTokenData(secureService.encryptObjectToString(tokenData));
    final RestResultBean restResultBean = RestResultBean.withData(helpdeskVerificationRequestBean);
    pwmRequest.outputJsonResult(restResultBean);
    LOGGER.debug(pwmRequest, "helpdesk operator " + pwmRequest.getUserInfoIfLoggedIn().toDisplayString() + " issued token for verification against user " + userIdentity.toDisplayString() + " sent to destination(s) " + tokenDestinationItem.getDisplay() + " (" + TimeDuration.fromCurrent(startTime).asCompactString() + ")");
    return ProcessStatus.Halt;
}
Also used : SecureService(password.pwm.util.secure.SecureService) FormConfiguration(password.pwm.config.value.data.FormConfiguration) SearchConfiguration(password.pwm.ldap.search.SearchConfiguration) ActionConfiguration(password.pwm.config.value.data.ActionConfiguration) Configuration(password.pwm.config.Configuration) EmailItemBean(password.pwm.bean.EmailItemBean) Instant(java.time.Instant) UserIdentity(password.pwm.bean.UserIdentity) HelpdeskProfile(password.pwm.config.profile.HelpdeskProfile) UserInfo(password.pwm.ldap.UserInfo) MessageSendMethod(password.pwm.config.option.MessageSendMethod) TokenDestinationItem(password.pwm.bean.TokenDestinationItem) Date(java.util.Date) PwmException(password.pwm.error.PwmException) ErrorInformation(password.pwm.error.ErrorInformation) MacroMachine(password.pwm.util.macro.MacroMachine) RestResultBean(password.pwm.ws.server.RestResultBean)

Aggregations

PwmException (password.pwm.error.PwmException)63 ErrorInformation (password.pwm.error.ErrorInformation)42 PwmUnrecoverableException (password.pwm.error.PwmUnrecoverableException)38 IOException (java.io.IOException)19 PwmOperationalException (password.pwm.error.PwmOperationalException)19 PwmApplication (password.pwm.PwmApplication)16 ChaiUnavailableException (com.novell.ldapchai.exception.ChaiUnavailableException)13 UserIdentity (password.pwm.bean.UserIdentity)13 RestResultBean (password.pwm.ws.server.RestResultBean)13 ServletException (javax.servlet.ServletException)12 LinkedHashMap (java.util.LinkedHashMap)9 PwmSession (password.pwm.http.PwmSession)9 Instant (java.time.Instant)8 TimeDuration (password.pwm.util.java.TimeDuration)8 MacroMachine (password.pwm.util.macro.MacroMachine)8 Configuration (password.pwm.config.Configuration)7 PwmRequest (password.pwm.http.PwmRequest)7 UserInfo (password.pwm.ldap.UserInfo)7 PasswordData (password.pwm.util.PasswordData)7 ArrayList (java.util.ArrayList)6