Search in sources :

Example 46 with UserIdentity

use of password.pwm.bean.UserIdentity 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() + ")");
}
Also used : LinkedHashSet(java.util.LinkedHashSet) SessionAuthenticator(password.pwm.ldap.auth.SessionAuthenticator) PwmOperationalException(password.pwm.error.PwmOperationalException) ErrorInformation(password.pwm.error.ErrorInformation) PasswordData(password.pwm.util.PasswordData) PwmPasswordPolicy(password.pwm.config.profile.PwmPasswordPolicy) List(java.util.List) ArrayList(java.util.ArrayList) ChaiOperationException(com.novell.ldapchai.exception.ChaiOperationException) ActionExecutor(password.pwm.util.operations.ActionExecutor) PwmApplication(password.pwm.PwmApplication) UserIdentity(password.pwm.bean.UserIdentity) NewUserProfile(password.pwm.config.profile.NewUserProfile) LdapProfile(password.pwm.config.profile.LdapProfile) ChaiConfiguration(com.novell.ldapchai.provider.ChaiConfiguration) ChaiProvider(com.novell.ldapchai.provider.ChaiProvider) ChaiUser(com.novell.ldapchai.ChaiUser) PwmSession(password.pwm.http.PwmSession)

Example 47 with UserIdentity

use of password.pwm.bean.UserIdentity in project pwm by pwm-project.

the class PeopleSearchDataReader method makeCacheKey.

private CacheKey makeCacheKey(final String operationIdentifier, final String dataIdentifier) throws PwmUnrecoverableException {
    final UserIdentity userIdentity;
    if (pwmRequest.isAuthenticated() && !useProxy()) {
        userIdentity = pwmRequest.getUserInfoIfLoggedIn();
    } else {
        userIdentity = null;
    }
    final String keyString = operationIdentifier + "|" + pwmRequest.getPwmApplication().getSecureService().hash(dataIdentifier);
    return CacheKey.makeCacheKey(this.getClass(), userIdentity, keyString);
}
Also used : UserIdentity(password.pwm.bean.UserIdentity)

Example 48 with UserIdentity

use of password.pwm.bean.UserIdentity in project pwm by pwm-project.

the class PeopleSearchDataReader method convertResultMapToBeans.

private Map<String, AttributeDetailBean> convertResultMapToBeans(final PwmRequest pwmRequest, final UserIdentity userIdentity, final List<FormConfiguration> detailForm, final Map<String, String> searchResults) throws ChaiUnavailableException, PwmUnrecoverableException {
    final Set<String> searchAttributes = getSearchAttributes(pwmRequest.getConfig());
    final Map<String, AttributeDetailBean> returnObj = new LinkedHashMap<>();
    for (final FormConfiguration formConfiguration : detailForm) {
        if (formConfiguration.isRequired() || searchResults.containsKey(formConfiguration.getName())) {
            final AttributeDetailBean bean = new AttributeDetailBean();
            bean.setName(formConfiguration.getName());
            bean.setLabel(formConfiguration.getLabel(pwmRequest.getLocale()));
            bean.setType(formConfiguration.getType());
            if (searchAttributes.contains(formConfiguration.getName())) {
                if (formConfiguration.getType() != FormConfiguration.Type.userDN) {
                    bean.setSearchable(true);
                }
            }
            if (formConfiguration.getType() == FormConfiguration.Type.userDN) {
                if (searchResults.containsKey(formConfiguration.getName())) {
                    final List<UserIdentity> identityValues = readUserDNAttributeValues(userIdentity, formConfiguration.getName());
                    final TreeMap<String, UserReferenceBean> userReferences = new TreeMap<>();
                    for (final UserIdentity loopIdentity : identityValues) {
                        final String displayValue = figureDisplaynameValue(pwmRequest, loopIdentity);
                        final UserReferenceBean userReference = new UserReferenceBean();
                        userReference.setUserKey(loopIdentity.toObfuscatedKey(pwmRequest.getPwmApplication()));
                        userReference.setDisplayName(displayValue);
                        userReferences.put(displayValue, userReference);
                    }
                    bean.setUserReferences(userReferences.values());
                }
            } else {
                if (formConfiguration.isMultivalue()) {
                    bean.setValues(readUserMultiAttributeValues(pwmRequest, userIdentity, formConfiguration.getName()));
                } else {
                    if (searchResults.containsKey(formConfiguration.getName())) {
                        bean.setValues(Collections.singletonList(searchResults.get(formConfiguration.getName())));
                    } else {
                        bean.setValues(Collections.<String>emptyList());
                    }
                }
            }
            returnObj.put(formConfiguration.getName(), bean);
        }
    }
    return returnObj;
}
Also used : UserIdentity(password.pwm.bean.UserIdentity) FormConfiguration(password.pwm.config.value.data.FormConfiguration) TreeMap(java.util.TreeMap) LinkedHashMap(java.util.LinkedHashMap)

Example 49 with UserIdentity

use of password.pwm.bean.UserIdentity in project pwm by pwm-project.

the class PeopleSearchDataReader method makeSearchResultsImpl.

private SearchResultBean makeSearchResultsImpl(final PwmRequest pwmRequest, final String username, final boolean includeDisplayName) throws ChaiUnavailableException, PwmUnrecoverableException {
    final Instant startTime = Instant.now();
    if (username == null || username.length() < 1) {
        return new SearchResultBean();
    }
    final boolean useProxy = useProxy();
    final UserSearchEngine userSearchEngine = pwmRequest.getPwmApplication().getUserSearchEngine();
    final SearchConfiguration searchConfiguration;
    {
        final SearchConfiguration.SearchConfigurationBuilder builder = SearchConfiguration.builder();
        builder.contexts(pwmRequest.getConfig().readSettingAsStringArray(PwmSetting.PEOPLE_SEARCH_SEARCH_BASE));
        builder.enableContextValidation(false);
        builder.username(username);
        builder.enableValueEscaping(false);
        builder.filter(getSearchFilter(pwmRequest.getConfig()));
        builder.enableSplitWhitespace(true);
        if (!useProxy) {
            builder.ldapProfile(pwmRequest.getPwmSession().getUserInfo().getUserIdentity().getLdapProfileID());
            builder.chaiProvider(pwmRequest.getPwmSession().getSessionManager().getChaiProvider());
        }
        searchConfiguration = builder.build();
    }
    final UserSearchResults results;
    final boolean sizeExceeded;
    try {
        final List<FormConfiguration> searchForm = pwmRequest.getConfig().readSettingAsForm(PwmSetting.PEOPLE_SEARCH_RESULT_FORM);
        final int maxResults = (int) pwmRequest.getConfig().readSettingAsLong(PwmSetting.PEOPLE_SEARCH_RESULT_LIMIT);
        final Locale locale = pwmRequest.getLocale();
        results = userSearchEngine.performMultiUserSearchFromForm(locale, searchConfiguration, maxResults, searchForm, pwmRequest.getSessionLabel());
        sizeExceeded = results.isSizeExceeded();
    } catch (PwmOperationalException e) {
        final ErrorInformation errorInformation = e.getErrorInformation();
        LOGGER.error(pwmRequest.getSessionLabel(), errorInformation.toDebugStr());
        throw new PwmUnrecoverableException(errorInformation);
    }
    final List<Map<String, Object>> resultOutput = new ArrayList<>(results.resultsAsJsonOutput(pwmRequest.getPwmApplication(), null));
    if (includeDisplayName) {
        for (final Map<String, Object> map : resultOutput) {
            final String userKey = (String) map.get("userKey");
            if (userKey != null) {
                final UserIdentity userIdentity = UserIdentity.fromKey(userKey, pwmRequest.getPwmApplication());
                final String displayValue = figureDisplaynameValue(pwmRequest, userIdentity);
                map.put("_displayName", displayValue);
            }
        }
    }
    final TimeDuration searchDuration = TimeDuration.fromCurrent(startTime);
    LOGGER.trace(pwmRequest.getPwmSession(), "finished rest peoplesearch search in " + searchDuration.asCompactString() + " not using cache, size=" + results.getResults().size());
    final SearchResultBean searchResultBean = new SearchResultBean();
    searchResultBean.setSearchResults(resultOutput);
    searchResultBean.setSizeExceeded(sizeExceeded);
    final String aboutMessage = LocaleHelper.getLocalizedMessage(pwmRequest.getLocale(), Display.Display_SearchResultsInfo.getKey(), pwmRequest.getConfig(), Display.class, new String[] { String.valueOf(results.getResults().size()), searchDuration.asLongString(pwmRequest.getLocale()) });
    searchResultBean.setAboutResultMessage(aboutMessage);
    return searchResultBean;
}
Also used : Locale(java.util.Locale) Instant(java.time.Instant) UserSearchEngine(password.pwm.ldap.search.UserSearchEngine) UserSearchResults(password.pwm.ldap.search.UserSearchResults) UserIdentity(password.pwm.bean.UserIdentity) ArrayList(java.util.ArrayList) SearchConfiguration(password.pwm.ldap.search.SearchConfiguration) PwmUnrecoverableException(password.pwm.error.PwmUnrecoverableException) PwmOperationalException(password.pwm.error.PwmOperationalException) ErrorInformation(password.pwm.error.ErrorInformation) FormConfiguration(password.pwm.config.value.data.FormConfiguration) TimeDuration(password.pwm.util.java.TimeDuration) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) TreeMap(java.util.TreeMap)

Example 50 with UserIdentity

use of password.pwm.bean.UserIdentity in project pwm by pwm-project.

the class UpdateProfileUtil method doProfileUpdate.

@SuppressWarnings("checkstyle:ParameterNumber")
public static void doProfileUpdate(final PwmApplication pwmApplication, final SessionLabel sessionLabel, final Locale locale, final UserInfo userInfo, final MacroMachine macroMachine, final UpdateProfileProfile updateProfileProfile, final Map<String, String> formValues, final ChaiUser theUser) throws PwmUnrecoverableException, ChaiUnavailableException, PwmOperationalException {
    final List<FormConfiguration> formFields = updateProfileProfile.readSettingAsForm(PwmSetting.UPDATE_PROFILE_FORM);
    final Map<FormConfiguration, String> formMap = FormUtility.readFormValuesFromMap(formValues, formFields, locale);
    // verify form meets the form requirements (may be redundant, but shouldn't hurt)
    verifyFormAttributes(pwmApplication, userInfo.getUserIdentity(), locale, formMap, false);
    // write values.
    LOGGER.info("updating profile for " + userInfo.getUserIdentity());
    LdapOperationsHelper.writeFormValuesToLdap(pwmApplication, macroMachine, theUser, formMap, false);
    final UserIdentity userIdentity = userInfo.getUserIdentity();
    {
        // execute configured actions
        final List<ActionConfiguration> actions = updateProfileProfile.readSettingAsAction(PwmSetting.UPDATE_PROFILE_WRITE_ATTRIBUTES);
        if (actions != null && !actions.isEmpty()) {
            LOGGER.debug(sessionLabel, "executing configured actions to user " + userIdentity);
            final ActionExecutor actionExecutor = new ActionExecutor.ActionExecutorSettings(pwmApplication, userIdentity).setExpandPwmMacros(true).setMacroMachine(macroMachine).createActionExecutor();
            actionExecutor.executeActions(actions, sessionLabel);
        }
    }
    sendProfileUpdateEmailNotice(pwmApplication, macroMachine, userInfo, locale, sessionLabel);
    // success, so forward to success page
    pwmApplication.getStatisticsManager().incrementValue(Statistic.UPDATE_ATTRIBUTES);
}
Also used : ActionExecutor(password.pwm.util.operations.ActionExecutor) UserIdentity(password.pwm.bean.UserIdentity) FormConfiguration(password.pwm.config.value.data.FormConfiguration) ArrayList(java.util.ArrayList) List(java.util.List)

Aggregations

UserIdentity (password.pwm.bean.UserIdentity)101 ErrorInformation (password.pwm.error.ErrorInformation)62 PwmUnrecoverableException (password.pwm.error.PwmUnrecoverableException)48 PwmOperationalException (password.pwm.error.PwmOperationalException)45 ChaiUser (com.novell.ldapchai.ChaiUser)30 PwmApplication (password.pwm.PwmApplication)27 Map (java.util.Map)21 PwmSession (password.pwm.http.PwmSession)20 UserSearchEngine (password.pwm.ldap.search.UserSearchEngine)19 PwmException (password.pwm.error.PwmException)18 ChaiUnavailableException (com.novell.ldapchai.exception.ChaiUnavailableException)17 LinkedHashMap (java.util.LinkedHashMap)17 HelpdeskProfile (password.pwm.config.profile.HelpdeskProfile)17 ChaiOperationException (com.novell.ldapchai.exception.ChaiOperationException)16 Instant (java.time.Instant)16 FormConfiguration (password.pwm.config.value.data.FormConfiguration)16 SearchConfiguration (password.pwm.ldap.search.SearchConfiguration)16 ArrayList (java.util.ArrayList)15 UserInfo (password.pwm.ldap.UserInfo)15 RestResultBean (password.pwm.ws.server.RestResultBean)15