use of password.pwm.http.PwmSession in project pwm by pwm-project.
the class NewUserServlet method nextStep.
@Override
protected void nextStep(final PwmRequest pwmRequest) throws IOException, ServletException, PwmUnrecoverableException, ChaiUnavailableException {
final NewUserBean newUserBean = getNewUserBean(pwmRequest);
final PwmApplication pwmApplication = pwmRequest.getPwmApplication();
final PwmSession pwmSession = pwmRequest.getPwmSession();
if (newUserBean.getProfileID() == null) {
final Set<String> newUserProfileIDs = pwmApplication.getConfig().getNewUserProfiles().keySet();
if (newUserProfileIDs.isEmpty()) {
pwmRequest.respondWithError(new ErrorInformation(PwmError.ERROR_INVALID_CONFIG, "no new user profiles are defined"));
return;
}
final LinkedHashMap<String, String> visibleProfiles = new LinkedHashMap<>(NewUserUtils.figureDisplayableProfiles(pwmRequest));
if (visibleProfiles.size() == 1) {
final String singleID = newUserProfileIDs.iterator().next();
LOGGER.trace(pwmRequest, "only one new user profile is defined, auto-selecting profile " + singleID);
newUserBean.setProfileID(singleID);
} else {
LOGGER.trace(pwmRequest, "new user profile not yet selected, redirecting to choice page");
pwmRequest.setAttribute(PwmRequestAttribute.NewUser_VisibleProfiles, visibleProfiles);
pwmRequest.forwardToJsp(JspUrl.NEW_USER_PROFILE_CHOICE);
return;
}
}
final NewUserProfile newUserProfile = getNewUserProfile(pwmRequest);
if (newUserBean.getCreateStartTime() != null) {
forwardToWait(pwmRequest, newUserProfile);
return;
}
// try to read the new user policy to make sure it's readable, that way an exception is thrown here instead of by the jsp
newUserProfile.getNewUserPasswordPolicy(pwmApplication, pwmSession.getSessionStateBean().getLocale());
if (!newUserBean.isFormPassed()) {
if (showFormPage(newUserProfile)) {
forwardToFormPage(pwmRequest, newUserBean);
return;
} else {
NewUserFormUtils.injectRemoteValuesIntoForm(newUserBean, newUserProfile);
try {
verifyForm(pwmRequest, newUserBean.getNewUserForm(), false);
} catch (PwmDataValidationException e) {
throw new PwmUnrecoverableException(e.getErrorInformation());
}
newUserBean.setFormPassed(true);
}
}
if (NewUserUtils.checkForTokenVerificationProgress(pwmRequest, newUserBean, newUserProfile) == ProcessStatus.Halt) {
return;
}
final String newUserAgreementText = newUserProfile.readSettingAsLocalizedString(PwmSetting.NEWUSER_AGREEMENT_MESSAGE, pwmSession.getSessionStateBean().getLocale());
if (!StringUtil.isEmpty(newUserAgreementText)) {
if (!newUserBean.isAgreementPassed()) {
final MacroMachine macroMachine = NewUserUtils.createMacroMachineForNewUser(pwmApplication, pwmRequest.getSessionLabel(), newUserBean.getNewUserForm(), null);
final String expandedText = macroMachine.expandMacros(newUserAgreementText);
pwmRequest.setAttribute(PwmRequestAttribute.AgreementText, expandedText);
pwmRequest.forwardToJsp(JspUrl.NEW_USER_AGREEMENT);
return;
}
}
// success so create the new user.
final String newUserDN = NewUserUtils.determineUserDN(pwmRequest, newUserBean.getNewUserForm());
try {
NewUserUtils.createUser(newUserBean.getNewUserForm(), pwmRequest, newUserDN);
newUserBean.setCreateStartTime(Instant.now());
forwardToWait(pwmRequest, newUserProfile);
} catch (PwmOperationalException e) {
LOGGER.error(pwmRequest, "error during user creation: " + e.getMessage());
if (newUserProfile.readSettingAsBoolean(PwmSetting.NEWUSER_DELETE_ON_FAIL)) {
NewUserUtils.deleteUserAccount(newUserDN, pwmRequest);
}
LOGGER.error(pwmSession, e.getErrorInformation().toDebugStr());
pwmRequest.respondWithError(e.getErrorInformation());
}
}
use of password.pwm.http.PwmSession in project pwm by pwm-project.
the class NewUserServlet method handleEnterCodeRequest.
@ActionHandler(action = "enterCode")
private ProcessStatus handleEnterCodeRequest(final PwmRequest pwmRequest) throws PwmUnrecoverableException, IOException, ServletException, ChaiUnavailableException {
final PwmSession pwmSession = pwmRequest.getPwmSession();
final NewUserBean newUserBean = getNewUserBean(pwmRequest);
final NewUserProfile newUserProfile = getNewUserProfile(pwmRequest);
final String userEnteredCode = pwmRequest.readParameterAsString(PwmConstants.PARAM_TOKEN);
final TokenDestinationItem tokenDestinationItem = NewUserUtils.tokenDestinationItemForCurrentValidation(pwmRequest, newUserBean, newUserProfile);
ErrorInformation errorInformation = null;
TokenPayload tokenPayload = null;
try {
tokenPayload = TokenUtil.checkEnteredCode(pwmRequest, userEnteredCode, tokenDestinationItem, null, TokenType.NEWUSER, TokenService.TokenEntryType.unauthenticated);
} catch (PwmUnrecoverableException e) {
LOGGER.debug(pwmRequest, "error while checking entered token: ");
errorInformation = e.getErrorInformation();
}
if (tokenPayload != null) {
try {
final NewUserTokenData newUserTokenData = NewUserFormUtils.fromTokenPayload(pwmRequest, tokenPayload);
newUserBean.setProfileID(newUserTokenData.getProfileID());
final NewUserForm newUserFormFromToken = newUserTokenData.getFormData();
final TokenDestinationItem.Type tokenType = tokenPayload.getDestination().getType();
if (tokenType == TokenDestinationItem.Type.email) {
try {
verifyForm(pwmRequest, newUserFormFromToken, false);
newUserBean.setRemoteInputData(newUserTokenData.getInjectionData());
newUserBean.setNewUserForm(newUserFormFromToken);
newUserBean.setProfileID(newUserTokenData.getProfileID());
newUserBean.setFormPassed(true);
newUserBean.getCompletedTokenFields().addAll(newUserTokenData.getCompletedTokenFields());
newUserBean.setCurrentTokenField(newUserTokenData.getCurrentTokenField());
} catch (PwmUnrecoverableException | PwmOperationalException e) {
LOGGER.error(pwmRequest, "while reading stored form data in token payload, form validation error occurred: " + e.getMessage());
errorInformation = e.getErrorInformation();
}
} else if (tokenType == TokenDestinationItem.Type.sms) {
if (newUserBean.getNewUserForm() == null || !newUserBean.getNewUserForm().isConsistentWith(newUserFormFromToken)) {
LOGGER.debug(pwmRequest, "token value is valid, but form data does not match current session form data");
final String errorMsg = "sms token does not match current session";
errorInformation = new ErrorInformation(PwmError.ERROR_TOKEN_INCORRECT, errorMsg);
}
}
} catch (PwmOperationalException e) {
errorInformation = e.getErrorInformation();
}
}
if (errorInformation != null) {
LOGGER.debug(pwmSession, errorInformation.toDebugStr());
setLastError(pwmRequest, errorInformation);
return ProcessStatus.Continue;
}
LOGGER.debug(pwmRequest, "marking token as passed " + JsonUtil.serialize(tokenDestinationItem));
newUserBean.getCompletedTokenFields().add(newUserBean.getCurrentTokenField());
newUserBean.setTokenSent(false);
newUserBean.setCurrentTokenField(null);
if (pwmRequest.getConfig().readSettingAsBoolean(PwmSetting.DISPLAY_TOKEN_SUCCESS_BUTTON)) {
pwmRequest.setAttribute(PwmRequestAttribute.TokenDestItems, tokenPayload.getDestination());
pwmRequest.forwardToJsp(JspUrl.NEW_USER_TOKEN_SUCCESS);
return ProcessStatus.Halt;
}
return ProcessStatus.Continue;
}
use of password.pwm.http.PwmSession in project pwm by pwm-project.
the class NewUserUtils method createUser.
@SuppressWarnings("checkstyle:MethodLength")
static void createUser(final NewUserForm newUserForm, final PwmRequest pwmRequest, final String newUserDN) throws PwmUnrecoverableException, ChaiUnavailableException, PwmOperationalException {
final PwmApplication pwmApplication = pwmRequest.getPwmApplication();
final PwmSession pwmSession = pwmRequest.getPwmSession();
final long startTime = System.currentTimeMillis();
// re-perform verification before proceeding
{
final PasswordUtility.PasswordCheckInfo passwordCheckInfo = NewUserServlet.verifyForm(pwmRequest, newUserForm, false);
passwordCheckInfoToException(passwordCheckInfo);
}
NewUserUtils.LOGGER.debug(pwmSession, "beginning createUser process for " + newUserDN);
final NewUserProfile newUserProfile = NewUserServlet.getNewUserProfile(pwmRequest);
final boolean promptForPassword = newUserProfile.readSettingAsBoolean(PwmSetting.NEWUSER_PROMPT_FOR_PASSWORD);
final PasswordData userPassword;
if (promptForPassword) {
userPassword = newUserForm.getNewUserPassword();
} else {
final PwmPasswordPolicy pwmPasswordPolicy = newUserProfile.getNewUserPasswordPolicy(pwmRequest.getPwmApplication(), pwmRequest.getLocale());
userPassword = RandomPasswordGenerator.createRandomPassword(pwmRequest.getSessionLabel(), pwmPasswordPolicy, pwmRequest.getPwmApplication());
}
// set up the user creation attributes
final Map<String, String> createAttributes = NewUserFormUtils.getLdapDataFromNewUserForm(NewUserServlet.getNewUserProfile(pwmRequest), newUserForm);
// read the creation object classes from configuration
final Set<String> createObjectClasses = new LinkedHashSet<>(pwmApplication.getConfig().readSettingAsStringArray(PwmSetting.DEFAULT_OBJECT_CLASSES));
// add the auto-add object classes
{
final LdapProfile defaultLDAPProfile = pwmApplication.getConfig().getDefaultLdapProfile();
createObjectClasses.addAll(defaultLDAPProfile.readSettingAsStringArray(PwmSetting.AUTO_ADD_OBJECT_CLASSES));
}
final ChaiProvider chaiProvider = pwmApplication.getConfig().getDefaultLdapProfile().getProxyChaiProvider(pwmApplication);
try {
// create the ldap entry
chaiProvider.createEntry(newUserDN, createObjectClasses, createAttributes);
NewUserUtils.LOGGER.info(pwmSession, "created user entry: " + newUserDN);
} catch (ChaiOperationException e) {
final String userMessage = "unexpected ldap error creating user entry: " + e.getMessage();
final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_NEW_USER_FAILURE, userMessage);
throw new PwmOperationalException(errorInformation);
}
final ChaiUser theUser = chaiProvider.getEntryFactory().newChaiUser(newUserDN);
final boolean useTempPw;
{
final String settingValue = pwmApplication.getConfig().readAppProperty(AppProperty.NEWUSER_LDAP_USE_TEMP_PW);
if ("auto".equalsIgnoreCase(settingValue)) {
useTempPw = chaiProvider.getDirectoryVendor() == DirectoryVendor.ACTIVE_DIRECTORY;
} else {
useTempPw = Boolean.parseBoolean(settingValue);
}
}
if (useTempPw) {
NewUserUtils.LOGGER.trace(pwmSession, "will use temporary password process for new user entry: " + newUserDN);
final PasswordData temporaryPassword;
{
final RandomPasswordGenerator.RandomGeneratorConfig randomGeneratorConfig = RandomPasswordGenerator.RandomGeneratorConfig.builder().passwordPolicy(newUserProfile.getNewUserPasswordPolicy(pwmApplication, pwmRequest.getLocale())).build();
temporaryPassword = RandomPasswordGenerator.createRandomPassword(pwmSession.getLabel(), randomGeneratorConfig, pwmApplication);
}
final ChaiUser proxiedUser = chaiProvider.getEntryFactory().newChaiUser(newUserDN);
try {
// set password as admin
proxiedUser.setPassword(temporaryPassword.getStringValue());
NewUserUtils.LOGGER.debug(pwmSession, "set temporary password for new user entry: " + newUserDN);
} catch (ChaiOperationException e) {
final String userMessage = "unexpected ldap error setting temporary password for new user entry: " + e.getMessage();
final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_NEW_USER_FAILURE, userMessage);
throw new PwmOperationalException(errorInformation);
}
// add AD-specific attributes
if (DirectoryVendor.ACTIVE_DIRECTORY == chaiProvider.getDirectoryVendor()) {
try {
NewUserUtils.LOGGER.debug(pwmSession, "setting userAccountControl attribute to enable account " + theUser.getEntryDN());
theUser.writeStringAttribute("userAccountControl", "512");
} catch (ChaiOperationException e) {
final String errorMsg = "error enabling AD account when writing userAccountControl attribute: " + e.getMessage();
final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_NEW_USER_FAILURE, errorMsg);
throw new PwmOperationalException(errorInformation);
}
}
try {
// bind as user
NewUserUtils.LOGGER.debug(pwmSession, "attempting bind as user to then allow changing to requested password for new user entry: " + newUserDN);
final ChaiConfiguration chaiConfiguration = ChaiConfiguration.builder(chaiProvider.getChaiConfiguration()).setSetting(ChaiSetting.BIND_DN, newUserDN).setSetting(ChaiSetting.BIND_PASSWORD, temporaryPassword.getStringValue()).build();
final ChaiProvider bindAsProvider = pwmApplication.getLdapConnectionService().getChaiProviderFactory().newProvider(chaiConfiguration);
final ChaiUser bindAsUser = bindAsProvider.getEntryFactory().newChaiUser(newUserDN);
bindAsUser.changePassword(temporaryPassword.getStringValue(), userPassword.getStringValue());
NewUserUtils.LOGGER.debug(pwmSession, "changed to user requested password for new user entry: " + newUserDN);
bindAsProvider.close();
} catch (ChaiOperationException e) {
final String userMessage = "unexpected ldap error setting user password for new user entry: " + e.getMessage();
final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_NEW_USER_FAILURE, userMessage);
throw new PwmOperationalException(errorInformation);
}
} else {
try {
// set password
theUser.setPassword(userPassword.getStringValue());
NewUserUtils.LOGGER.debug(pwmSession, "set user requested password for new user entry: " + newUserDN);
} catch (ChaiOperationException e) {
final String userMessage = "unexpected ldap error setting password for new user entry: " + e.getMessage();
final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_NEW_USER_FAILURE, userMessage);
throw new PwmOperationalException(errorInformation);
}
// add AD-specific attributes
if (DirectoryVendor.ACTIVE_DIRECTORY == chaiProvider.getDirectoryVendor()) {
try {
theUser.writeStringAttribute("userAccountControl", "512");
} catch (ChaiOperationException e) {
final String errorMsg = "error enabling AD account when writing userAccountControl attribute: " + e.getMessage();
final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_NEW_USER_FAILURE, errorMsg);
throw new PwmOperationalException(errorInformation);
}
}
}
NewUserUtils.LOGGER.trace(pwmSession, "new user ldap creation process complete, now authenticating user");
// write data to remote web service
remoteWriteFormData(pwmRequest, newUserForm);
// authenticate the user to pwm
final UserIdentity userIdentity = new UserIdentity(newUserDN, pwmApplication.getConfig().getDefaultLdapProfile().getIdentifier());
final SessionAuthenticator sessionAuthenticator = new SessionAuthenticator(pwmApplication, pwmSession, PwmAuthenticationSource.NEW_USER_REGISTRATION);
sessionAuthenticator.authenticateUser(userIdentity, userPassword);
{
// execute configured actions
final List<ActionConfiguration> actions = newUserProfile.readSettingAsAction(PwmSetting.NEWUSER_WRITE_ATTRIBUTES);
if (actions != null && !actions.isEmpty()) {
NewUserUtils.LOGGER.debug(pwmSession, "executing configured actions to user " + theUser.getEntryDN());
final ActionExecutor actionExecutor = new ActionExecutor.ActionExecutorSettings(pwmApplication, userIdentity).setExpandPwmMacros(true).setMacroMachine(pwmSession.getSessionManager().getMacroMachine(pwmApplication)).createActionExecutor();
actionExecutor.executeActions(actions, pwmSession.getLabel());
}
}
// send user email
sendNewUserEmailConfirmation(pwmRequest);
// add audit record
pwmApplication.getAuditManager().submit(AuditEvent.CREATE_USER, pwmSession.getUserInfo(), pwmSession);
// increment the new user creation statistics
pwmApplication.getStatisticsManager().incrementValue(Statistic.NEW_USERS);
NewUserUtils.LOGGER.debug(pwmSession, "completed createUser process for " + newUserDN + " (" + TimeDuration.fromCurrent(startTime).asCompactString() + ")");
}
use of password.pwm.http.PwmSession in project pwm by pwm-project.
the class UpdateProfileServlet method nextStep.
protected void nextStep(final PwmRequest pwmRequest) throws IOException, ServletException, PwmUnrecoverableException {
final PwmApplication pwmApplication = pwmRequest.getPwmApplication();
final UpdateProfileBean updateProfileBean = getBean(pwmRequest);
final UpdateProfileProfile updateProfileProfile = getProfile(pwmRequest);
final PwmSession pwmSession = pwmRequest.getPwmSession();
{
final String updateProfileAgreementText = updateProfileProfile.readSettingAsLocalizedString(PwmSetting.UPDATE_PROFILE_AGREEMENT_MESSAGE, pwmSession.getSessionStateBean().getLocale());
if (!StringUtil.isEmpty(updateProfileAgreementText)) {
if (!updateProfileBean.isAgreementPassed()) {
final MacroMachine macroMachine = pwmRequest.getPwmSession().getSessionManager().getMacroMachine(pwmRequest.getPwmApplication());
final String expandedText = macroMachine.expandMacros(updateProfileAgreementText);
pwmRequest.setAttribute(PwmRequestAttribute.AgreementText, expandedText);
pwmRequest.forwardToJsp(JspUrl.UPDATE_ATTRIBUTES_AGREEMENT);
return;
}
}
}
// make sure there is form data in the bean.
if (!updateProfileBean.isFormLdapLoaded()) {
updateProfileBean.getFormData().clear();
updateProfileBean.getFormData().putAll((UpdateProfileUtil.formDataFromLdap(pwmRequest, updateProfileProfile)));
updateProfileBean.setFormLdapLoaded(true);
UpdateProfileUtil.forwardToForm(pwmRequest, updateProfileProfile, updateProfileBean);
return;
}
if (!updateProfileBean.isFormSubmitted()) {
UpdateProfileUtil.forwardToForm(pwmRequest, updateProfileProfile, updateProfileBean);
return;
}
// validate the form data.
try {
// verify form meets the form requirements
final List<FormConfiguration> formFields = updateProfileProfile.readSettingAsForm(PwmSetting.UPDATE_PROFILE_FORM);
final Map<FormConfiguration, String> formValues = FormUtility.readFormValuesFromMap(updateProfileBean.getFormData(), formFields, pwmRequest.getLocale());
UpdateProfileUtil.verifyFormAttributes(pwmRequest.getPwmApplication(), pwmRequest.getUserInfoIfLoggedIn(), pwmRequest.getLocale(), formValues, true);
} catch (PwmException e) {
LOGGER.error(pwmSession, e.getMessage());
setLastError(pwmRequest, e.getErrorInformation());
UpdateProfileUtil.forwardToForm(pwmRequest, updateProfileProfile, updateProfileBean);
return;
}
{
final boolean requireConfirmation = updateProfileProfile.readSettingAsBoolean(PwmSetting.UPDATE_PROFILE_SHOW_CONFIRMATION);
if (requireConfirmation && !updateProfileBean.isConfirmationPassed()) {
UpdateProfileUtil.forwardToConfirmForm(pwmRequest, updateProfileProfile, updateProfileBean);
return;
}
}
if (UpdateProfileUtil.checkForTokenVerificationProgress(pwmRequest, updateProfileBean, updateProfileProfile) == ProcessStatus.Halt) {
return;
}
try {
// write the form values
final ChaiUser theUser = pwmSession.getSessionManager().getActor(pwmApplication);
UpdateProfileUtil.doProfileUpdate(pwmRequest.getPwmApplication(), pwmRequest.getSessionLabel(), pwmRequest.getLocale(), pwmSession.getUserInfo(), pwmSession.getSessionManager().getMacroMachine(pwmApplication), updateProfileProfile, updateProfileBean.getFormData(), theUser);
// re-populate the uiBean because we have changed some values.
pwmSession.reloadUserInfoBean(pwmApplication);
// clear cached read attributes.
pwmRequest.getPwmSession().reloadUserInfoBean(pwmApplication);
// mark the event log
pwmApplication.getAuditManager().submit(AuditEvent.UPDATE_PROFILE, pwmSession.getUserInfo(), pwmSession);
// clear the bean
pwmApplication.getSessionStateService().clearBean(pwmRequest, UpdateProfileBean.class);
pwmRequest.getPwmResponse().forwardToSuccessPage(Message.Success_UpdateProfile);
return;
} catch (PwmException e) {
LOGGER.error(pwmSession, e.getMessage());
setLastError(pwmRequest, e.getErrorInformation());
} catch (ChaiException e) {
final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_UPDATE_ATTRS_FAILURE, e.toString());
LOGGER.error(pwmSession, errorInformation.toDebugStr());
setLastError(pwmRequest, errorInformation);
}
UpdateProfileUtil.forwardToForm(pwmRequest, updateProfileProfile, updateProfileBean);
}
use of password.pwm.http.PwmSession in project pwm by pwm-project.
the class PwmIfTag method doStartTag.
@Override
public int doStartTag() throws JspException {
boolean showBody = false;
if (PwmApplicationMode.determineMode((HttpServletRequest) pageContext.getRequest()) != PwmApplicationMode.ERROR) {
if (test != null) {
try {
final PwmRequest pwmRequest = PwmRequest.forRequest((HttpServletRequest) pageContext.getRequest(), (HttpServletResponse) pageContext.getResponse());
final PwmSession pwmSession = pwmRequest.getPwmSession();
final PwmIfTest testEnum = test;
if (testEnum != null) {
try {
final PwmIfOptions options = new PwmIfOptions(negate, permission, setting, requestFlag);
showBody = testEnum.passed(pwmRequest, options);
} catch (ChaiUnavailableException e) {
LOGGER.error("error testing jsp if '" + testEnum.toString() + "', error: " + e.getMessage());
}
} else {
final String errorMsg = "unknown test name '" + test + "' in pwm:If jsp tag!";
LOGGER.warn(pwmSession, errorMsg);
}
} catch (PwmUnrecoverableException e) {
LOGGER.error("error executing PwmIfTag for test '" + test + "', error: " + e.getMessage());
}
}
}
if (negate) {
showBody = !showBody;
}
return showBody ? EVAL_BODY_INCLUDE : SKIP_BODY;
}
Aggregations