Exemplo n.º 1
0
  /**
   * Setup optios and values for the user's session if authentication was ok.
   *
   * @param userSession The UserSession instance of the user
   * @param user The User instance of the authenticated user
   */
  protected void configureUserSession(UserSession userSession, User user) {

    LOG.trace("configureUserSession");
    userSession.dataToUser(user);

    // As an user may come back to the forum before its
    // last visit's session expires, we should check for
    // existent user information and then, if found, store
    // it to the database before getting his information back.
    String sessionId = SessionFacade.isUserInSession(user.getId());

    UserSession tmpUs;
    if (sessionId != null) {
      SessionFacade.storeSessionData(sessionId, JForumExecutionContext.getConnection());
      tmpUs = SessionFacade.getUserSession(sessionId);
      SessionFacade.remove(sessionId);
    } else {
      UserSessionDAO sm = DataAccessDriver.getInstance().newUserSessionDAO();
      tmpUs = sm.selectById(userSession, JForumExecutionContext.getConnection());
    }

    if (tmpUs == null) {
      userSession.setLastVisit(new Date(System.currentTimeMillis()));
    } else {
      // Update last visit and session start time
      userSession.setLastVisit(new Date(tmpUs.getStartTime().getTime() + tmpUs.getSessionTime()));
    }

    // If the execution point gets here, then the user
    // has chosen "autoLogin"
    userSession.setAutoLogin(true);
    SessionFacade.makeLogged();

    I18n.load(user.getLang());
  }
Exemplo n.º 2
0
  /**
   * Checks user credentials / automatic login.
   *
   * @param userSession The UserSession instance associated to the user's session
   * @return <code>true</code> if auto login was enabled and the user was sucessfuly logged in.
   * @throws DatabaseException
   */
  protected boolean checkAutoLogin(UserSession userSession) {

    LOG.trace("checkAutoLogin");
    String cookieName = SystemGlobals.getValue(ConfigKeys.COOKIE_NAME_DATA);

    Cookie cookie = this.getCookieTemplate(cookieName);
    Cookie hashCookie = this.getCookieTemplate(SystemGlobals.getValue(ConfigKeys.COOKIE_USER_HASH));
    Cookie autoLoginCookie =
        this.getCookieTemplate(SystemGlobals.getValue(ConfigKeys.COOKIE_AUTO_LOGIN));

    if (hashCookie != null
        && cookie != null
        && !cookie.getValue().equals(SystemGlobals.getValue(ConfigKeys.ANONYMOUS_USER_ID))
        && autoLoginCookie != null
        && "1".equals(autoLoginCookie.getValue())) {
      String uid = cookie.getValue();
      String uidHash = hashCookie.getValue();

      // Load the user-specific security hash from the database
      try {
        UserDAO userDao = DataAccessDriver.getInstance().newUserDAO();
        String userHash = userDao.getUserAuthHash(Integer.parseInt(uid));

        if (userHash == null || userHash.trim().length() == 0) {
          return false;
        }

        String securityHash = MD5.crypt(userHash);

        if (securityHash.equals(uidHash)) {
          int userId = Integer.parseInt(uid);
          userSession.setUserId(userId);

          User user = userDao.selectById(userId);

          if (user == null || user.getId() != userId || user.isDeleted()) {
            userSession.makeAnonymous();
            return false;
          }

          this.configureUserSession(userSession, user);

          return true;
        }
      } catch (Exception e) {
        throw new DatabaseException(e);
      }

      userSession.makeAnonymous();
    }

    return false;
  }
Exemplo n.º 3
0
  /**
   * Check if we have to send customized emails
   *
   * @return true if there is a need for customized emails
   */
  private boolean isCustomizationNeeded() {
    boolean need = false;

    for (Iterator<User> iter = this.users.iterator(); iter.hasNext(); ) {
      User user = iter.next();

      if (user.notifyText()) {
        need = true;
        break;
      }
    }

    return need;
  }
Exemplo n.º 4
0
  /**
   * Load user's roles.
   *
   * @param user The <code>User</code> to load
   * @param force If <code>true</code>, forces a reload. If <code>false</code>, the call will be
   *     ignored if the roles are already loaded.
   * @see SecurityRepository#load(int)
   * @see SecurityRepository#load(int, boolean)
   * @see SecurityRepository#load(User)
   * @return PermissionControl
   */
  public static PermissionControl load(User user, boolean force) {
    String userId = Integer.toString(user.getId());

    if (force || cache.get(FQN, userId) == null) {
      PermissionControl pc = new PermissionControl();

      // load roles
      GroupSecurityDAO dao = DataAccessDriver.getInstance().newGroupSecurityDAO();
      pc.setRoles(dao.loadRolesByUserGroups(user));

      cache.add(FQN, userId, pc);

      return pc;
    }

    return SecurityRepository.get(user.getId());
  }
Exemplo n.º 5
0
  /** @param u User */
  private static void handleAvatar(User u) {

    LOG.trace("handleAvatar");
    String fileName = MD5.crypt(Integer.toString(u.getId()));
    FileItem item = (FileItem) JForumExecutionContext.getRequest().getObjectParameter("avatar");
    UploadUtils uploadUtils = new UploadUtils(item);

    // Gets file extension
    String extension = uploadUtils.getExtension().toLowerCase();
    int type = ImageUtils.IMAGE_UNKNOWN;

    if (extension.equals("jpg") || extension.equals("jpeg")) {
      type = ImageUtils.IMAGE_JPEG;
    } else if (extension.equals("gif") || extension.equals("png")) {
      type = ImageUtils.IMAGE_PNG;
    }

    if (type != ImageUtils.IMAGE_UNKNOWN) {
      String avatarTmpFileName =
          SystemGlobals.getApplicationPath() + "/images/avatar/" + fileName + "_tmp." + extension;

      // We cannot handle gifs
      if (extension.toLowerCase().equals("gif")) {
        extension = "png";
      }

      String avatarFinalFileName =
          SystemGlobals.getApplicationPath() + "/images/avatar/" + fileName + "." + extension;

      uploadUtils.saveUploadedFile(avatarTmpFileName);

      // OK, time to check and process the avatar size
      int maxWidth = SystemGlobals.getIntValue(ConfigKeys.AVATAR_MAX_WIDTH);
      int maxHeight = SystemGlobals.getIntValue(ConfigKeys.AVATAR_MAX_HEIGHT);

      BufferedImage image = ImageUtils.resizeImage(avatarTmpFileName, type, maxWidth, maxHeight);
      ImageUtils.saveImage(image, avatarFinalFileName, type);

      u.setAvatar(fileName + "." + extension);

      // Delete the temporary file
      new File(avatarTmpFileName).delete();
    }
  }
Exemplo n.º 6
0
  private void defineUserMessage(final User user) {
    try {
      this.templateParams.put("user", user);

      String text = this.processTemplate();
      int oldMessageFormat = messageFormat;
      if (user.notifyText()) {
        messageFormat = MESSAGE_HTML;
      }
      this.defineMessageText(text);
      messageFormat = oldMessageFormat;
    } catch (Exception e) {
      throw new MailException(e);
    }
  }
Exemplo n.º 7
0
  public boolean getCanEditUser(User userToEdit, List<Group> groups) {
    if (isAdministrator()) {
      return true;
    }

    for (Group group : groups) {
      for (Group group2 : userToEdit.getGroups()) {
        if (group.equals(group2)) {
          return true;
        }
      }
    }

    return false;
  }
Exemplo n.º 8
0
  /** @see net.jforum.dao.GroupSecurityDAO#loadRolesByUserGroups(net.jforum.entities.User) */
  public RoleCollection loadRolesByUserGroups(User user) {
    List groups = user.getGroupsList();

    // When the user is associated to more than one group, we
    // should check the merged roles
    int[] groupIds = this.getSortedGroupIds(groups);

    RoleCollection groupRoles = RolesRepository.getGroupRoles(groupIds);

    // Not cached yet? then do it now
    if (groupRoles == null) {
      groupRoles = this.loadRoles(groupIds);
      RolesRepository.addGroupRoles(groupIds, groupRoles);
    }

    return groupRoles;
  }
Exemplo n.º 9
0
  private void setJforumScreenname(User user) {
    SSOUtils ssoutils = new SSOUtils();

    if (!ssoutils.userExists(user.getUsername())) {
      net.jforum.entities.User jforumuser = new net.jforum.entities.User();

      jforumuser.setUsername(user.getUsername());
      jforumuser.setPassword("sso");
      String email = null == user.getEmail() ? "" : user.getEmail();
      jforumuser.setEmail(email);
      jforumuser.setFrom(user.getScreenname());
      jforumuser.setActive(1);

      UserDAO dao = DataAccessDriver.getInstance().newUserDAO();

      dao.addNew(jforumuser);

      net.jforum.entities.User addedjforumuser = dao.selectByName(user.getUsername());

      addedjforumuser.setFrom(user.getScreenname());

      dao.update(addedjforumuser);
    }
  }
Exemplo n.º 10
0
  public LostPasswordSpammer(final User user, final String mailTitle) {
    final String forumLink = ViewCommon.getForumLink();

    final String url =
        new StringBuilder()
            .append(forumLink)
            .append("user/recoverPassword/")
            .append(user.getActivationKey())
            .append(SystemGlobals.getValue(ConfigKeys.SERVLET_EXTENSION))
            .toString();

    final SimpleHash params = new SimpleHash();
    params.put("url", url);
    params.put("user", user);

    final List<User> recipients = new ArrayList<User>();
    recipients.add(user);

    this.setUsers(recipients);
    this.setTemplateParams(params);

    super.prepareMessage(
        mailTitle, SystemGlobals.getValue(ConfigKeys.MAIL_LOST_PASSWORD_MESSAGE_FILE));
  }
Exemplo n.º 11
0
  public boolean dispatchMessages() {
    try {
      int sendDelay = SystemGlobals.getIntValue(ConfigKeys.MAIL_SMTP_DELAY);

      if (SystemGlobals.getBoolValue(ConfigKeys.MAIL_SMTP_AUTH)) {
        if (StringUtils.isNotEmpty(username) && StringUtils.isNotEmpty(password)) {
          boolean ssl = SystemGlobals.getBoolValue(ConfigKeys.MAIL_SMTP_SSL);

          Transport transport = this.session.getTransport(ssl ? "smtps" : "smtp");

          try {
            String host = SystemGlobals.getValue(ConfigKeys.MAIL_SMTP_HOST);

            transport.connect(host, username, password);

            if (transport.isConnected()) {
              for (Iterator<User> userIter = this.users.iterator(); userIter.hasNext(); ) {
                User user = userIter.next();

                if (this.needCustomization) {
                  this.defineUserMessage(user);
                }

                if (StringUtils.isNotEmpty(user.getEmail())) {
                  Address address = new InternetAddress(user.getEmail());
                  LOGGER.debug("Sending mail to: " + user.getEmail());
                  this.message.setRecipient(Message.RecipientType.TO, address);
                  Stats.record("Sent email", user.getEmail());
                  transport.sendMessage(this.message, new Address[] {address});
                }
                if (sendDelay > 0) {
                  try {
                    Thread.sleep(sendDelay);
                  } catch (InterruptedException ie) {
                    LOGGER.error("Error while Thread.sleep." + ie, ie);
                  }
                }
              }
            }
          } catch (Exception e) {
            throw new MailException(e);
          } finally {
            try {
              transport.close();
            } catch (Exception e) {
              LOGGER.error(e);
            }
          }
        }
      } else {
        for (Iterator<User> iter = this.users.iterator(); iter.hasNext(); ) {
          User user = iter.next();

          if (this.needCustomization) {
            this.defineUserMessage(user);
          }

          if (StringUtils.isNotEmpty(user.getEmail())) {
            Address address = new InternetAddress(user.getEmail());
            LOGGER.debug("Sending mail to: " + user.getEmail());
            this.message.setRecipient(Message.RecipientType.TO, address);
            Stats.record("Sent email", user.getEmail());
            Transport.send(this.message, new Address[] {address});
          }
          if (sendDelay > 0) {
            try {
              Thread.sleep(sendDelay);
            } catch (InterruptedException ie) {
              LOGGER.error("Error while Thread.sleep." + ie, ie);
            }
          }
        }
      }
    } catch (MessagingException e) {
      LOGGER.error("Error while dispatching the message. " + e, e);
    }

    return true;
  }
Exemplo n.º 12
0
  /**
   * Updates the user information
   *
   * @param userId int The user id we are saving
   * @return List
   */
  public static List saveUser(int userId) {

    LOG.trace("saveUser");
    List errors = new ArrayList();

    UserDAO um = DataAccessDriver.getInstance().newUserDAO();
    User u = um.selectById(userId);

    RequestContext request = JForumExecutionContext.getRequest();
    boolean isAdmin = SessionFacade.getUserSession().isAdmin();

    if (isAdmin) {
      String username = request.getParameter("username");

      if (username != null) {
        u.setUsername(username.trim());
      }

      if (request.getParameter("rank_special") != null) {
        u.setRankId(request.getIntParameter("rank_special"));
      }
    }

    SafeHtml safeHtml = new SafeHtml();

    u.setId(userId);
    u.setIcq(safeHtml.makeSafe(request.getParameter("icq")));
    u.setAim(safeHtml.makeSafe(request.getParameter("aim")));
    u.setMsnm(safeHtml.makeSafe(request.getParameter("msn")));
    u.setYim(safeHtml.makeSafe(request.getParameter("yim")));
    u.setFrom(safeHtml.makeSafe(request.getParameter("location")));
    u.setOccupation(safeHtml.makeSafe(request.getParameter("occupation")));
    u.setInterests(safeHtml.makeSafe(request.getParameter("interests")));
    u.setBiography(safeHtml.makeSafe(request.getParameter("biography")));
    u.setSignature(safeHtml.makeSafe(request.getParameter("signature")));
    u.setViewEmailEnabled(request.getParameter("viewemail").equals("1"));
    u.setViewOnlineEnabled(request.getParameter("hideonline").equals("0"));
    u.setNotifyPrivateMessagesEnabled(request.getParameter("notifypm").equals("1"));
    u.setNotifyOnMessagesEnabled(request.getParameter("notifyreply").equals("1"));
    u.setAttachSignatureEnabled(request.getParameter("attachsig").equals("1"));
    u.setHtmlEnabled(request.getParameter("allowhtml").equals("1"));
    u.setLang(request.getParameter("language"));
    u.setBbCodeEnabled("1".equals(request.getParameter("allowbbcode")));
    u.setSmiliesEnabled("1".equals(request.getParameter("allowsmilies")));
    u.setNotifyAlways("1".equals(request.getParameter("notify_always")));
    u.setNotifyText("1".equals(request.getParameter("notify_text")));

    String website = safeHtml.makeSafe(request.getParameter("website"));

    if (!StringUtils.isEmpty(website) && !website.toLowerCase().startsWith("http://")) {
      website = "http://" + website;
    }

    u.setWebSite(website);

    String currentPassword = request.getParameter("current_password");
    boolean isCurrentPasswordEmpty = currentPassword == null || "".equals(currentPassword.trim());

    if (isAdmin || !isCurrentPasswordEmpty) {
      if (!isCurrentPasswordEmpty) {
        currentPassword = MD5.crypt(currentPassword);
      }

      if (isAdmin || u.getPassword().equals(currentPassword)) {
        u.setEmail(safeHtml.makeSafe(request.getParameter("email")));

        String newPassword = request.getParameter("new_password");

        if (newPassword != null && newPassword.length() > 0) {
          u.setPassword(MD5.crypt(newPassword));
        }
      } else {
        errors.add(I18n.getMessage("User.currentPasswordInvalid"));
      }
    }

    if (request.getParameter("avatardel") != null) {
      File avatarFile = new File(u.getAvatar());

      File fileToDelete =
          new File(SystemGlobals.getApplicationPath() + "/images/avatar/" + avatarFile.getName());

      if (fileToDelete.exists()) {
        fileToDelete.delete();
      }

      u.setAvatar(null);
    }

    if (request.getObjectParameter("avatar") != null) {
      try {
        UserCommon.handleAvatar(u);
      } catch (Exception e) {
        UserCommon.LOG.warn("Problems while uploading the avatar: " + e);
        errors.add(I18n.getMessage("User.avatarUploadError"));
      }
    } else if (SystemGlobals.getBoolValue(ConfigKeys.AVATAR_ALLOW_EXTERNAL_URL)) {
      String avatarUrl = request.getParameter("avatarUrl");

      if (!StringUtils.isEmpty(avatarUrl)) {
        if (avatarUrl.toLowerCase().startsWith("http://")) {

          try {
            Image image = ImageIO.read(new URL(avatarUrl));

            if (image != null) {
              if (image.getWidth(null) > SystemGlobals.getIntValue(ConfigKeys.AVATAR_MAX_WIDTH)
                  || image.getHeight(null)
                      > SystemGlobals.getIntValue(ConfigKeys.AVATAR_MAX_HEIGHT)) {
                errors.add(I18n.getMessage("User.avatarTooBig"));
              } else {
                u.setAvatar(avatarUrl);
              }
            }
          } catch (Exception e) {
            errors.add(I18n.getMessage("User.avatarUploadError"));
          }
        } else {
          errors.add(I18n.getMessage("User.avatarUrlShouldHaveHttp"));
        }
      }
    }

    if (errors.size() == 0) {
      um.update(u);

      if (SessionFacade.getUserSession().getUserId() == userId) {
        SessionFacade.getUserSession().setLang(u.getLang());
      }
    }

    return errors;
  }