/** * checks if the user is able to upload * * @return true if user is authorized false if the user is not */ public boolean shouldRenderUpload() { if (recipe != null && ui.isIsUserAuthenticated()) { return recipe.getCreator().getUserName().equals(ui.getUser().getUserName()); } else { return false; } }
@Test public void create_user_without_email() throws Exception { UserIdentity underTest = UserIdentity.builder().setProviderLogin("john").setLogin("1234").setName("John").build(); assertThat(underTest.getEmail()).isNull(); }
public UserIdentity getIdentityById(long id) { for (UserIdentity identity : identities) { if (identity.getId() == id) { return identity; } } return null; }
/** * returns the rating of this recipe * * @return integer rating from 1-5 */ public Integer getRating() { if (recipe != null && ui.isIsUserAuthenticated()) { RecipeRating temp = ratingEJB.findByUserAndRecipe(ui.getUser(), recipe); if (temp != null) { rating = temp.getRatingValue().getValue(); } } return rating; }
public boolean isEditAuthorized() { Users user = ui.getUser(); boolean editAuthorized = false; if (user != null && recipe != null) { editAuthorized = recipe.getCreator().getUserName().equals(user.getUserName()) || ui.isIsAdmin(); } return editAuthorized; }
@JsonIgnore public boolean isApiKeySet() { for (UserIdentity identity : identities) { if (identity.getType() == IdentityType.API) { return true; } } return false; }
/** * Returns true if the user has already favorited this recipe, false otherwise * * @return true if already favorited, false otherwise */ public boolean isAlreadyFavorited() { if (ui.isIsUserAuthenticated()) { Users user = ui.getUser(); if (user.getFavorites() != null) { return user.getFavorites().contains(recipe); } else { return false; } } else { return false; } }
/** deletes a comment */ public void doDeleteComment() { if (ui.isIsUserAuthenticated()) { Users u = ui.getUser(); if (isEditAuthorized() || ui.isIsAdmin()) { try { recipesEJB.removeCommentFromRecipe(recipe, deleteComment); this.commentModel = new LazyCommentDataModel(recipe, recipesEJB); } catch (javax.ejb.EJBAccessException ejbae) { FacesContext.getCurrentInstance() .addMessage(null, new FacesMessage("Only registered users can post comments.")); } } } }
@Test public void create_user_with_groups() throws Exception { UserIdentity underTest = UserIdentity.builder() .setProviderLogin("john") .setLogin("1234") .setName("John") .setEmail("*****@*****.**") .setGroups(newHashSet("admin", "user")) .build(); assertThat(underTest.shouldSyncGroups()).isTrue(); assertThat(underTest.getGroups()).containsOnly("admin", "user"); }
/** * returns true if it has been reviewed and false if it has not been reviewed by a professional; */ public boolean isHasAlreadyReviewed() { boolean result = false; if (ui.isIsUserAuthenticated() && professionalStatus.isIsProfessional()) { Users user = ui.getUser(); if (recipe != null) { for (Review rev : recipe.getReviews()) { if (rev.getReviewer().getUserName().equals(user.getUserName())) { result = true; break; } } // end for } } // end value != null return result; }
/** This method is called AFTER the bean is constructed */ @PostConstruct private void init() { if (!FacesContext.getCurrentInstance().isPostback()) { // TODO: view counter ++ } // Get the recipe String value = qm.get("recipe"); if (value != null) { recipe = recipesEJB.findRecipe(Integer.parseInt(value)); } // init some fields tags = new DefaultTagCloudModel(); newComment = new Comment(); newRating = new RecipeRating(); tags = new DefaultTagCloudModel(); if (recipe != null) { this.commentModel = new LazyCommentDataModel(recipe, recipesEJB); this.totalRatings = ratingEJB.countTotalRatings(recipe); Users user = ui.getUser(); getNutritionixIngredientInfo(recipe); recipesEJB.incrementViews(recipe); // Get the recipe's tags ArrayList<Tag> tagList = new ArrayList<Tag>(recipe.getTags()); if (!tagList.isEmpty()) { ListIterator i = tagList.listIterator(); while (i.hasNext()) { Tag t = (Tag) i.next(); String url = "search.xhtml?searchArg=" + t.getTagName(); this.tags.addTag(new DefaultTagCloudItem(t.getTagName(), url, tagEJB.getWeight(t))); } } else { this.tags.addTag(new DefaultTagCloudItem("#tagMe", 1)); } // Get related recipes relatedRecipes = search.getSearchRecipes(recipe); } // end if recipe is null else { this.tags.addTag(new DefaultTagCloudItem("#tagMe", 1)); } if (ui.isIsUserAuthenticated()) { user = ui.getUser(); } }
/** For canceling a rating event */ public void oncancel() { Users user = ui.getUser(); newRating = ratingEJB.findByUserAndRecipe(user, recipe); if (newRating != null) { ratingEJB.removeRecipeRating(newRating); } }
/** * Returns true if the user is the creator for this recipe * * @return boolean */ public boolean isIsCreator() { if (ui.isIsUserAuthenticated() && recipe != null) { if (recipe.getCreator() == user) return true; else return false; } else { return false; } }
@Test public void fail_when_name_is_null() throws Exception { thrown.expect(IllegalArgumentException.class); thrown.expectMessage("User name must not be blank"); UserIdentity.builder() .setProviderLogin("john") .setLogin("1234") .setEmail("*****@*****.**") .build(); }
@Test public void fail_when_email_is_loo_long() throws Exception { thrown.expect(IllegalArgumentException.class); thrown.expectMessage("User email size is too big (100 characters max)"); UserIdentity.builder() .setProviderLogin("john") .setLogin("1234") .setName("John") .setEmail(Strings.repeat("1", 101)) .build(); }
@Test public void fail_when_login_is_too_small() throws Exception { thrown.expect(IllegalArgumentException.class); thrown.expectMessage("User login size is incorrect (Between 2 and 255 characters)"); UserIdentity.builder() .setProviderLogin("john") .setLogin("j") .setName("John") .setEmail("*****@*****.**") .build(); }
@Test public void fail_when_login_is_empty() throws Exception { thrown.expect(IllegalArgumentException.class); thrown.expectMessage("User login must not be blank"); UserIdentity.builder() .setProviderLogin("john") .setLogin("") .setName("John") .setEmail("*****@*****.**") .build(); }
@Test public void fail_when_provider_login_is_too_long() throws Exception { thrown.expect(IllegalArgumentException.class); thrown.expectMessage("Provider login size is incorrect (maximum 255 characters)"); UserIdentity.builder() .setProviderLogin(Strings.repeat("1", 256)) .setLogin("1234") .setName("John") .setEmail("*****@*****.**") .build(); }
@Test public void fail_when_groups_contain_null_group_name() throws Exception { thrown.expect(IllegalArgumentException.class); thrown.expectMessage("Group name cannot be empty"); UserIdentity.builder() .setProviderLogin("john") .setLogin("1234") .setName("John") .setEmail("*****@*****.**") .setGroups(newHashSet((String) null)); }
@Test public void fail_when_groups_contain_too_long_group_name() throws Exception { thrown.expect(IllegalArgumentException.class); thrown.expectMessage("Group name cannot be longer than 255 characters"); UserIdentity.builder() .setProviderLogin("john") .setLogin("1234") .setName("John") .setEmail("*****@*****.**") .setGroups(newHashSet(Strings.repeat("group", 300))); }
@Test public void fail_when_groups_contain_anyone() throws Exception { thrown.expect(IllegalArgumentException.class); thrown.expectMessage("Anyone group cannot be used"); UserIdentity.builder() .setProviderLogin("john") .setLogin("1234") .setName("John") .setEmail("*****@*****.**") .setGroups(newHashSet("Anyone")); }
@Test public void fail_when_groups_are_null() throws Exception { thrown.expect(NullPointerException.class); thrown.expectMessage( "Groups cannot be null, please don't use this method if groups should not be synchronized."); UserIdentity.builder() .setProviderLogin("john") .setLogin("1234") .setName("John") .setEmail("*****@*****.**") .setGroups(null); }
private static Date determinePwdLastModified( final PwmApplication pwmApplication, final SessionLabel sessionLabel, final ChaiUser theUser, final UserIdentity userIdentity) throws ChaiUnavailableException, PwmUnrecoverableException { // fetch last password modification time from pwm last update attribute operation try { final Date chaiReadDate = theUser.readPasswordModificationDate(); if (chaiReadDate != null) { LOGGER.trace( sessionLabel, "read last user password change timestamp (via chai) as: " + PwmConstants.DEFAULT_DATETIME_FORMAT.format(chaiReadDate)); return chaiReadDate; } } catch (ChaiOperationException e) { LOGGER.error( sessionLabel, "unexpected error reading password last modified timestamp: " + e.getMessage()); } final LdapProfile ldapProfile = pwmApplication.getConfig().getLdapProfiles().get(userIdentity.getLdapProfileID()); final String pwmLastSetAttr = ldapProfile.readSettingAsString(PwmSetting.PASSWORD_LAST_UPDATE_ATTRIBUTE); if (pwmLastSetAttr != null && pwmLastSetAttr.length() > 0) { try { final Date pwmPwdLastModified = theUser.readDateAttribute(pwmLastSetAttr); LOGGER.trace( sessionLabel, "read pwmPasswordChangeTime as: " + (pwmPwdLastModified == null ? "n/a" : PwmConstants.DEFAULT_DATETIME_FORMAT.format(pwmPwdLastModified))); return pwmPwdLastModified; } catch (ChaiOperationException e) { LOGGER.error( sessionLabel, "error parsing password last modified PWM password value for user " + theUser.getEntryDN() + "; error: " + e.getMessage()); } } LOGGER.debug(sessionLabel, "unable to determine time of user's last password modification"); return null; }
@Test public void create_user() throws Exception { UserIdentity underTest = UserIdentity.builder() .setProviderLogin("john") .setLogin("1234") .setName("John") .setEmail("*****@*****.**") .build(); assertThat(underTest.getProviderLogin()).isEqualTo("john"); assertThat(underTest.getLogin()).isEqualTo("1234"); assertThat(underTest.getName()).isEqualTo("John"); assertThat(underTest.getEmail()).isEqualTo("*****@*****.**"); assertThat(underTest.shouldSyncGroups()).isFalse(); assertThat(underTest.getGroups()).isEmpty(); }
/** * Creates a comment and redirects back to the recipe page * * @return the string navigation outcome */ public String doCreateComment() { Users commenter = ui.getUser(); try { this.newComment.setRecipe(this.recipe); this.newComment.setCommenter(commenter); this.newComment.setDateCommented(new Date().getTime()); List<Comment> c = recipe.getComments(); c.add(newComment); this.recipe.setComments(c); recipesEJB.editRecipe(recipe); } catch (javax.ejb.EJBAccessException ejbae) { FacesContext.getCurrentInstance() .addMessage(null, new FacesMessage("Only registered users can post comments.")); } return "/recipe.xhtml?recipe=" + qm.get("recipe"); }
/** This method is intended to be used as an actionListener for rating */ public void handleRating() { Users rater = ui.getUser(); newRating = ratingEJB.findByUserAndRecipe(rater, recipe); boolean edit = false; // determine whether we need to edit // No rating for this user exists if (newRating == null && rating > 0 && rating <= 5) { newRating = new RecipeRating(); newRating.setRater(rater); newRating.setRecipe(recipe); newRating.setRatingDate(new Date().getTime()); } // A rating exists else { edit = true; } switch (rating) { case 1: this.newRating.setRatingValue(RatingValue.ONE_STAR); break; case 2: this.newRating.setRatingValue(RatingValue.TWO_STARS); break; case 3: this.newRating.setRatingValue(RatingValue.THREE_STARS); break; case 4: this.newRating.setRatingValue(RatingValue.FOUR_STARS); break; case 5: this.newRating.setRatingValue(RatingValue.FIVE_STARS); break; } // end switch if (edit) { this.newRating = ratingEJB.editRecipeRating(newRating); } else { this.newRating = ratingEJB.createRecipeRating(newRating); } }
public static Map<String, Date> readIndividualReplicaLastPasswordTimes( final PwmApplication pwmApplication, final SessionLabel sessionLabel, final UserIdentity userIdentity) throws PwmUnrecoverableException { final Map<String, Date> returnValue = new LinkedHashMap<>(); final ChaiProvider chaiProvider = pwmApplication.getProxyChaiProvider(userIdentity.getLdapProfileID()); final Collection<ChaiConfiguration> perReplicaConfigs = ChaiUtility.splitConfigurationPerReplica( chaiProvider.getChaiConfiguration(), Collections.singletonMap(ChaiSetting.FAILOVER_CONNECT_RETRIES, "1")); for (final ChaiConfiguration loopConfiguration : perReplicaConfigs) { final String loopReplicaUrl = loopConfiguration.getSetting(ChaiSetting.BIND_DN); ChaiProvider loopProvider = null; try { loopProvider = ChaiProviderFactory.createProvider(loopConfiguration); final Date lastModifiedDate = determinePwdLastModified(pwmApplication, sessionLabel, userIdentity); returnValue.put(loopReplicaUrl, lastModifiedDate); } catch (ChaiUnavailableException e) { LOGGER.error(sessionLabel, "unreachable server during replica password sync check"); e.printStackTrace(); } finally { if (loopProvider != null) { try { loopProvider.close(); } catch (Exception e) { final String errorMsg = "error closing loopProvider to " + loopReplicaUrl + " while checking individual password sync status"; LOGGER.error(sessionLabel, errorMsg); } } } } return returnValue; }
public static void helpdeskSetUserPassword( final PwmSession pwmSession, final ChaiUser chaiUser, final UserIdentity userIdentity, final PwmApplication pwmApplication, final PasswordData newPassword) throws ChaiUnavailableException, PwmUnrecoverableException, PwmOperationalException { final SessionLabel sessionLabel = pwmSession.getLabel(); if (!pwmSession.isAuthenticated()) { final String errorMsg = "attempt to helpdeskSetUserPassword, but user is not authenticated"; final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_UNAUTHORIZED, errorMsg); throw new PwmOperationalException(errorInformation); } final HelpdeskProfile helpdeskProfile = pwmSession.getSessionManager().getHelpdeskProfile(pwmApplication); if (helpdeskProfile == null) { final String errorMsg = "attempt to helpdeskSetUserPassword, but user does not have helpdesk permission"; final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_UNAUTHORIZED, errorMsg); throw new PwmOperationalException(errorInformation); } try { chaiUser.setPassword(newPassword.getStringValue()); } catch (ChaiPasswordPolicyException e) { final String errorMsg = "error setting password for user '" + chaiUser.getEntryDN() + "'' " + e.toString(); final PwmError pwmError = PwmError.forChaiError(e.getErrorCode()); final ErrorInformation error = new ErrorInformation( pwmError == null ? PwmError.PASSWORD_UNKNOWN_VALIDATION : pwmError, errorMsg); throw new PwmOperationalException(error); } catch (ChaiOperationException e) { final String errorMsg = "error setting password for user '" + chaiUser.getEntryDN() + "'' " + e.getMessage(); final PwmError pwmError = PwmError.forChaiError(e.getErrorCode()) == null ? PwmError.ERROR_UNKNOWN : PwmError.forChaiError(e.getErrorCode()); final ErrorInformation error = new ErrorInformation(pwmError, errorMsg); throw new PwmOperationalException(error); } // at this point the password has been changed, so log it. LOGGER.info( sessionLabel, "user '" + pwmSession.getUserInfoBean().getUserIdentity() + "' successfully changed password for " + chaiUser.getEntryDN()); // create a proxy user object for pwm to update/read the user. final ChaiUser proxiedUser = pwmApplication.getProxiedChaiUser(userIdentity); // mark the event log { final HelpdeskAuditRecord auditRecord = pwmApplication .getAuditManager() .createHelpdeskAuditRecord( AuditEvent.HELPDESK_SET_PASSWORD, pwmSession.getUserInfoBean().getUserIdentity(), null, userIdentity, pwmSession.getSessionStateBean().getSrcAddress(), pwmSession.getSessionStateBean().getSrcHostname()); pwmApplication.getAuditManager().submit(auditRecord); } // update statistics pwmApplication.getStatisticsManager().updateEps(Statistic.EpsType.PASSWORD_CHANGES, 1); pwmApplication.getStatisticsManager().incrementValue(Statistic.HELPDESK_PASSWORD_SET); // create a uib for end user final UserInfoBean userInfoBean = new UserInfoBean(); final UserStatusReader userStatusReader = new UserStatusReader(pwmApplication, pwmSession.getLabel()); userStatusReader.populateUserInfoBean( userInfoBean, pwmSession.getSessionStateBean().getLocale(), userIdentity, proxiedUser.getChaiProvider()); { // execute configured actions LOGGER.debug( sessionLabel, "executing changepassword and helpdesk post password change writeAttributes to user " + userIdentity); final List<ActionConfiguration> actions = new ArrayList<>(); actions.addAll( pwmApplication .getConfig() .readSettingAsAction(PwmSetting.CHANGE_PASSWORD_WRITE_ATTRIBUTES)); actions.addAll( helpdeskProfile.readSettingAsAction( PwmSetting.HELPDESK_POST_SET_PASSWORD_WRITE_ATTRIBUTES)); if (!actions.isEmpty()) { final ActionExecutor actionExecutor = new ActionExecutor.ActionExecutorSettings(pwmApplication, userIdentity) .setMacroMachine( MacroMachine.forUser( pwmApplication, pwmSession.getSessionStateBean().getLocale(), sessionLabel, userIdentity)) .setExpandPwmMacros(true) .createActionExecutor(); actionExecutor.executeActions(actions, pwmSession); } } final HelpdeskClearResponseMode settingClearResponses = HelpdeskClearResponseMode.valueOf( helpdeskProfile.readSettingAsString(PwmSetting.HELPDESK_CLEAR_RESPONSES)); if (settingClearResponses == HelpdeskClearResponseMode.yes) { final String userGUID = LdapOperationsHelper.readLdapGuidValue(pwmApplication, sessionLabel, userIdentity, false); pwmApplication.getCrService().clearResponses(pwmSession, proxiedUser, userGUID); // mark the event log final HelpdeskAuditRecord auditRecord = pwmApplication .getAuditManager() .createHelpdeskAuditRecord( AuditEvent.HELPDESK_CLEAR_RESPONSES, pwmSession.getUserInfoBean().getUserIdentity(), null, userIdentity, pwmSession.getSessionStateBean().getSrcAddress(), pwmSession.getSessionStateBean().getSrcHostname()); pwmApplication.getAuditManager().submit(auditRecord); } // send email notification sendChangePasswordHelpdeskEmailNotice(pwmSession, pwmApplication, userInfoBean); // expire if so configured if (helpdeskProfile.readSettingAsBoolean(PwmSetting.HELPDESK_FORCE_PW_EXPIRATION)) { LOGGER.trace( pwmSession, "preparing to expire password for user " + userIdentity.toDisplayString()); try { proxiedUser.expirePassword(); } catch (ChaiOperationException e) { LOGGER.warn( pwmSession, "error while forcing password expiration for user " + userIdentity.toDisplayString() + ", error: " + e.getMessage()); e.printStackTrace(); } } // send password final boolean sendPassword = helpdeskProfile.readSettingAsBoolean(PwmSetting.HELPDESK_SEND_PASSWORD); if (sendPassword) { final MessageSendMethod messageSendMethod; { final String profileID = ProfileUtility.discoverProfileIDforUser( pwmApplication, sessionLabel, userIdentity, ProfileType.ForgottenPassword); final ForgottenPasswordProfile forgottenPasswordProfile = pwmApplication.getConfig().getForgottenPasswordProfiles().get(profileID); messageSendMethod = forgottenPasswordProfile.readSettingAsEnum( PwmSetting.RECOVERY_SENDNEWPW_METHOD, MessageSendMethod.class); } final UserDataReader userDataReader = new LdapUserDataReader(userIdentity, chaiUser); final LoginInfoBean loginInfoBean = new LoginInfoBean(); loginInfoBean.setUserCurrentPassword(newPassword); final MacroMachine macroMachine = new MacroMachine( pwmApplication, pwmSession.getLabel(), userInfoBean, loginInfoBean, userDataReader); PasswordUtility.sendNewPassword( userInfoBean, pwmApplication, macroMachine, newPassword, pwmSession.getSessionStateBean().getLocale(), messageSendMethod); } }