JCUser copy = new JCUser(user.getUsername(), user.getEmail(), user.getPassword()); copy.setId(user.getId()); copy.setFirstName(user.getFirstName()); copy.setLastName(user.getLastName()); copy.setLastLogin(user.getLastLogin()); copy.setBanReason(user.getBanReason()); copy.setRole(user.getRole()); copy.setEncodedUsername(user.getEncodedUsername()); copy.setAvatar(user.getAvatar()); copy.setVersion(user.getVersion()); for (Group group : user.getGroups()) { copy.getGroups().add(copyUserGroup(group,copy)); copy.setSalt(user.getSalt()); copy.setPostCount(user.getPostCount()); copy.setLanguage(user.getLanguage()); copy.setPageSize(user.getPageSize()); copy.setLocation(user.getLocation()); copy.setSignature(user.getSignature()); copy.setRegistrationDate(user.getRegistrationDate()); copy.setEnabled(user.isEnabled()); copy.setAutosubscribe(user.isAutosubscribe()); copy.setMentioningNotificationsEnabled(user.isMentioningNotificationsEnabled()); copy.setSendPmNotification(user.isSendPmNotification()); copy.setAvatarLastModificationTime(user.getAvatarLastModificationTime()); copy.setAllForumMarkedAsReadTime(user.getAllForumMarkedAsReadTime()); copy.setUuid(user.getUuid());
/** * {@inheritDoc} */ @Override @PreAuthorize("hasPermission(#branch.id, 'BRANCH', 'BranchPermission.VIEW_TOPICS')") public void markAllTopicsAsRead(Branch branch) { JCUser user = userService.getCurrentUser(); if (!user.isAnonymous()) { // would be logical to remove per-topic Last Read Post records from DB, // but it's not worth it since most people will anyway press on global Mark All As Read // at some point and this will clean the records for user. Ergo, it's not expected // that the DB will be overwhelmed with per-topic Last Read Post records. branchReadedMarkerDao.markBranchAsRead(user, branch); } }
public static JCUser getUserWithAllFieldsFilled() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { JCUser user = getDefaultUser(); DateTime dateTime = new DateTime(); user.setId(1); user.setLanguage(Language.RUSSIAN); user.setPageSize(1); user.setLocation("location"); user.setSignature("signature"); user.setRegistrationDate(dateTime); user.setEnabled(true); user.setAutosubscribe(true); user.setMentioningNotificationsEnabled(true); user.setSendPmNotification(true); user.getContacts().add(ObjectsFactory.getDefaultUserContact()); user.setAvatarLastModificationTime(dateTime); user.setAllForumMarkedAsReadTime(dateTime); user.setAvatar(new byte[]{1}); user.setVersion(1L); user.setBanReason("Ban Reason"); user.setRole("Role"); Method setLastLogin = User.class.getDeclaredMethod("setLastLogin", DateTime.class); Method setEncodedUsername = User.class.getDeclaredMethod("setEncodedUsername", String.class); setLastLogin.setAccessible(true); setEncodedUsername.setAccessible(true); setLastLogin.invoke(user, new DateTime()); setEncodedUsername.invoke(user, "Encoded Username"); return user; }
/** * Constructor which fills dto fields from user. * * @param user copying source */ public EditUserProfileDto(JCUser user) { this.userId = user.getId(); this.username = user.getUsername(); this.userProfileVersion = user.getVersion(); }
/** * Constructor which fills dto fields from user. * * @param user copying source */ public UserNotificationsDto(JCUser user) { this.userId = user.getId(); this.autosubscribe = user.isAutosubscribe(); this.mentioningNotificationsEnabled = user.isMentioningNotificationsEnabled(); this.sendPmNotification = user.isSendPmNotification(); }
/** * Constructor which fills dto fields from user. * * @param user copying source */ public UserProfileDto(JCUser user) { this.userId = user.getId(); this.firstName = user.getFirstName(); this.lastName = user.getLastName(); this.email = user.getEmail(); this.signature = user.getSignature(); this.pageSize = user.getPageSize(); this.location = user.getLocation(); this.postCount = user.getPostCount(); this.registrationDate = user.getRegistrationDate(); this.lastLogin = user.getLastLogin(); }
/** * Send email notification to user when he was mentioned in forum. * Email notification will be sent only when notifications are enabled * in forum, otherwise nothing will happen. * * @param recipient mentioned user who will receive notification * @param postId id of post where user was mentioned */ public void sendUserMentionedNotification(JCUser recipient, long postId) { String urlSuffix = "/posts/" + postId; String url = this.getDeploymentRootUrl() + urlSuffix; Locale locale = recipient.getLanguage().getLocale(); Map<String, Object> model = new HashMap<>(); model.put(NAME, recipient.getUsername()); model.put(LINK, url); model.put(LINK_LABEL, getDeploymentRootUrlWithoutPort() + urlSuffix); model.put(RECIPIENT_LOCALE, locale); try { this.sendEmail(recipient.getEmail(), messageSource.getMessage("userMentioning.subject", new Object[]{}, locale), model, "userMentioning.vm"); } catch (MailingFailedException e) { LOGGER.error("Failed to sent activation mail for user: " + recipient.getUsername()); } }
/** * {@inheritDoc} */ @Override public JCUser saveEditedUserProfile( long editedUserId, UserInfoContainer editedUserProfileInfo) throws NotFoundException { JCUser editedUser = this.get(editedUserId); byte[] decodedAvatar = base64Wrapper.decodeB64Bytes(editedUserProfileInfo.getB64EncodedAvatar()); editedUser.setEmail(editedUserProfileInfo.getEmail()); if (!Arrays.equals(editedUser.getAvatar(), decodedAvatar)) { editedUser.setAvatarLastModificationTime(new DateTime()); } editedUser.setAvatar(decodedAvatar); editedUser.setSignature(editedUserProfileInfo.getSignature()); editedUser.setFirstName(editedUserProfileInfo.getFirstName()); editedUser.setLastName(editedUserProfileInfo.getLastName()); editedUser.setPageSize(editedUserProfileInfo.getPageSize()); editedUser.setLocation(editedUserProfileInfo.getLocation()); this.getDao().saveOrUpdate(editedUser); LOGGER.info("Updated user profile. Username: {}", editedUser.getUsername()); return editedUser; }
/** * Sends email with a hyperlink to activate user account. * * @param recipient user to send activation mail to */ public void sendAccountActivationMail(JCUser recipient) { try { String urlSuffix = "/user/activate/" + recipient.getUuid(); String url = this.getDeploymentRootUrl() + urlSuffix; Locale locale = recipient.getLanguage().getLocale(); Map<String, Object> model = new HashMap<>(); model.put(NAME, recipient.getUsername()); model.put(LINK, url); model.put(LINK_LABEL, getDeploymentRootUrlWithoutPort() + urlSuffix); model.put(RECIPIENT_LOCALE, locale); this.sendEmail(recipient.getEmail(), messageSource.getMessage("accountActivation.subject", new Object[]{}, locale), model, "accountActivation.vm"); } catch (MailingFailedException e) { LOGGER.error("Failed to sent activation mail for user: " + recipient.getUsername()); } }
JCUser user = new JCUser(userDto.getUsername(), userDto.getEmail(), userDto.getPassword()); user.setLanguage(userDto.getLanguage()); user.setAutosubscribe(DEFAULT_AUTOSUBSCRIBE); user.setSendPmNotification(DEFAULT_SEND_PM_NOTIFICATION); user.setAvatar(avatarService.getDefaultImage()); user.setRegistrationDate(new DateTime()); this.getDao().saveOrUpdate(user); mailService.sendAccountActivationMail(user); LOGGER.info("JCUser registered: {}", user.getUsername()); return user;
/** * {@inheritDoc} */ @Override @PreAuthorize("hasPermission(#branchId, 'BRANCH', 'BranchPermission.CREATE_POSTS')") public Post replyToTopic(long topicId, String answerBody, long branchId) throws NotFoundException { Topic topic = topicFetchService.getTopicSilently(topicId); this.assertPostingIsAllowed(topic); JCUser currentUser = userService.getCurrentUser(); currentUser.setPostCount(currentUser.getPostCount() + 1); Post answer = new Post(currentUser, answerBody); topic.addPost(answer); topic.removeDraftOfUser(currentUser); if (currentUser.isAutosubscribe()){ subscriptionService.subscribe(topic); } postDao.saveOrUpdate(answer); Branch branch = topic.getBranch(); branch.setLastPost(answer); branchDao.saveOrUpdate(branch); dao.saveOrUpdate(topic); securityService.createAclBuilder().grant(GeneralPermission.WRITE).to(currentUser).on(answer).flush(); notificationService.subscribedEntityChanged(topic); userService.notifyAndMarkNewlyMentionedUsers(answer); logger.debug("New post in topic. Topic id={}, Post id={}, Post author={}", new Object[]{topicId, answer.getId(), currentUser.getUsername()}); return answer; }
/** * Get link to user's profile. * * @param username user's name * @return null when user doesn't exist, otherwise link to user's profile */ private String getLinkToUserProfile(String username, UserDao userDao) { String userPofileLink = null; JCUser user = userDao.getByUsername(username); if (user != null && user.getUsername().equals(username)) { userPofileLink = getApplicationNameAsContextPath() + "/users/" + user.getId(); LOGGER.trace("{} has the following url of profile - {}", username, userPofileLink); } else { LOGGER.trace("Mentioned user wasn't find: {}", username); } return userPofileLink; }
/** * Handle user's successful authentication. * Updates last login time for authenticated user. * * @param request http request * @param response http response * @param authentication user's authentication * @throws ServletException forwarded from handler chain * @throws IOException forwarded from handler chain */ public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException { JCUser user = (JCUser) authentication.getPrincipal(); userService.updateLastLoginTime(user); logger.info("JCUser logged in: " + user.getUsername()); //apply language settings assuming CookieLocaleResolver usage String languageCode = user.getLanguage().getLanguageCode(); LocaleResolver localeResolver = new CookieLocaleResolver(); localeResolver.setLocale(request, response, user.getLanguage().getLocale()); Cookie cookie = new Cookie(CookieLocaleResolver.DEFAULT_COOKIE_NAME, languageCode); cookie.setPath("/"); response.addCookie(cookie); super.onAuthenticationSuccess(request, response, authentication); } }
/** * Quotes text given as a valid BB-coded quote. Such a quotes are rendered automatically in posts or forum messages. * On UI you can find Quote button near each post. * * @param source text to quote, not null * @param author text author, not null * @return well formed BB qoute */ public String quote(String source, JCUser author) { Validate.notNull(source, "Source cannot be null"); Validate.notNull(author, "Author cannot be null"); return String.format(QUOTE_PATEERN, author.getUsername(), source); }
/** * {@inheritDoc} */ @Override public JCUser saveEditedUserNotifications(long editedUserId, UserNotificationsContainer userNotificationsInfo) throws NotFoundException { JCUser editedUser = this.get(editedUserId); editedUser.setMentioningNotificationsEnabled(userNotificationsInfo.isMentioningNotificationsEnabled()); editedUser.setSendPmNotification(userNotificationsInfo.isSendPmNotification()); editedUser.setAutosubscribe(userNotificationsInfo.isAutosubscribe()); this.getDao().saveOrUpdate(editedUser); LOGGER.info("Updated user notification settings. Username: {}", editedUser.getUsername()); return editedUser; }
/** * Constructor which fills dto fields from user. * * @param user copying source */ public UserSecurityDto(JCUser user) { this.userId = user.getId(); }
/** * Resolves user locale. If user is logged in locale will be read from database. If user is anonymous locale will be * resolved form request and cookies using standard {@link CookieLocaleResolver} mechanism * * @param request HttpServletRequest * @return user locale */ @Override public Locale resolveLocale(HttpServletRequest request) { Locale locale = (Locale)request.getAttribute(LOCALE_REQUEST_ATTRIBUTE_NAME); if (locale != null) { return locale; } JCUser currentUser = userReader.getCurrentUser(); if (currentUser.isAnonymous()) { locale = super.resolveLocale(request); } else { locale = currentUser.getLanguage().getLocale(); } request.setAttribute(LOCALE_REQUEST_ATTRIBUTE_NAME, locale); return locale; }
/** * {@inheritDoc} */ @Override public void activateAccount(String uuid) throws NotFoundException, UserTriesActivatingAccountAgainException { JCUser user = this.getDao().getByUuid(uuid); if (user == null) { LOGGER.warn("Could not activate user with UUID[{}] because it doesn't exist. Either it was removed from DB " + "because too much time passed between registration and activation, or there is an error in link" + ", might be possible the user searches for vulnerabilities in the forum.", uuid); throw new NotFoundException(); } else if (!user.isEnabled()) { Group group = groupDao.getGroupByName(AdministrationGroup.USER.getName()); user.addGroup(group); user.setEnabled(true); this.getDao().saveOrUpdate(user); activateByPlugin(user.getUsername()); LOGGER.info("User [{}] successfully activated", user.getUsername()); } else { LOGGER.warn("User [{}] tried to activate his account again, but that's impossible. Either he clicked the " + "link again, or someone looks for vulnerabilities in the forum.", user.getUsername()); throw new UserTriesActivatingAccountAgainException(); } }
/** * @param value filed value to be validated * @param context validator context, not used here * @return true if user specified is not the current one logged in */ @Override public boolean isValid(String value, ConstraintValidatorContext context) { JCUser user = service.getCurrentUser(); return user.isAnonymous() || !user.getUsername().equalsIgnoreCase(value); } }
/** * Computes new last read post on the page based on the topic size and * current pagination settings. * * @param user user to calculate post for * @param topic topic to calculate post for * @param pageNum page number co calculate last post seen by the user * @return last post on the page */ private Post calculatePostOnPage(JCUser user, Topic topic, int pageNum) { int maxPostIndex = user.getPageSize() * pageNum - 1; maxPostIndex = Math.min(topic.getPostCount() - 1, maxPostIndex); return topic.getPosts().get(maxPostIndex); }