示例#1
0
  public boolean isSessionValid(UserSession userSession, RequestContext request) {
    String remoteUser = null;

    Cookie SSOCookie = ControllerUtils.getCookie("JforumSSO"); // my app login cookie
    logger.info("DEBUG - CustomSSO - isSessionValid - Getting JForumSSO Cookie!");

    if (SSOCookie != null) remoteUser = SSOCookie.getValue(); //  jforum username

    if (remoteUser == null) {
      logger.info("DEBUG - CustomSSO - isSessionValid - JForumSSO Cookie is NULL!");
      JForumExecutionContext.setRedirect(SystemGlobals.getValue(ConfigKeys.SSO_REDIRECT));
      return false;

    } else if (remoteUser.equals("")) {
      logger.info("DEBUG - CustomSSO - isSessionValid - JForumSSO Cookie is empty!");
      JForumExecutionContext.setRedirect(SystemGlobals.getValue(ConfigKeys.SSO_REDIRECT));
      return false;
      // user has since logged in
    } else if (remoteUser != null
        && userSession.getUserId() == SystemGlobals.getIntValue(ConfigKeys.ANONYMOUS_USER_ID)) {
      logger.info("DEBUG - CustomSSO - isSessionValid - JForumSSO Cookie is Anonymous!");
      return false;
      // user has changed user
    } else if (remoteUser != null && !remoteUser.equals(userSession.getUsername())) {
      logger.info("DEBUG - CustomSSO - isSessionValid - JForumSSO Cookie User Mismatch");
      return false;
    }
    logger.info("DEBUG - CustomSSO - isSessionValid - Returning True");
    return true; // sso pool apps user and forum user the same
  }
示例#2
0
  public static String getMessage(String m, UserSession us) {
    if (us == null || us.getLang() == null || us.getLang().equals("")) {
      return getMessage(defaultName, m);
    }

    return getMessage(us.getLang(), m);
  }
示例#3
0
  /**
   * Gets all forums available to the user.
   *
   * @param us An <code>UserSession</code> instance with user information
   * @param anonymousUserId The id which represents the anonymous user
   * @param tracking <code>Map</code> instance with information about the topics read by the user
   * @param checkUnreadPosts <code>true</code> if is to search for unread topics inside the forums,
   *     or <code>false</code> if this action is not needed.
   * @return A <code>List</code> instance where each record is an instance of a <code>Category
   *     </code> object
   */
  public static List getAllCategoriesAndForums(
      UserSession us, int anonymousUserId, Map tracking, boolean checkUnreadPosts) {
    long lastVisit = 0;
    int userId = anonymousUserId;

    if (us != null) {
      lastVisit = us.getLastVisit().getTime();
      userId = us.getUserId();
    }

    // Do not check for unread posts if the user is not logged in
    checkUnreadPosts = checkUnreadPosts && (userId != anonymousUserId);

    List categories = ForumRepository.getAllCategories(userId);

    if (!checkUnreadPosts) {
      return categories;
    }

    List returnCategories = new ArrayList();
    for (Iterator iter = categories.iterator(); iter.hasNext(); ) {
      Category c = new Category((Category) iter.next());

      for (Iterator tmpIterator = c.getForums().iterator(); tmpIterator.hasNext(); ) {
        Forum f = (Forum) tmpIterator.next();
        ForumCommon.checkUnreadPosts(f, tracking, lastVisit);
      }

      returnCategories.add(c);
    }

    return returnCategories;
  }
示例#4
0
  /**
   * @see #getAllCategoriesAndForums(boolean)
   * @return List
   */
  public static List getAllCategoriesAndForums() {

    LOG.trace("getAllCategoriesAndForums");
    UserSession us = SessionFacade.getUserSession();
    boolean checkUnread =
        (us != null && us.getUserId() != SystemGlobals.getIntValue(ConfigKeys.ANONYMOUS_USER_ID));
    return getAllCategoriesAndForums(checkUnread);
  }
示例#5
0
  /**
   * Gets the language name for the current request. The method will first look at {@link
   * UserSession#getLang()} and use it if any value is found. Otherwise, the default board language
   * will be used
   *
   * @return String
   */
  public static String getUserLanguage() {
    UserSession us = SessionFacade.getUserSession();

    if (us == null || us.getLang() == null || us.getLang().trim().equals("")) {
      return defaultName;
    }

    return us.getLang();
  }
示例#6
0
  /**
   * Makes the current logged user watch a specific topic.
   *
   * @param topicId the id of the topic to watch
   */
  @SecurityConstraint(value = AuthenticatedRule.class, displayLogin = true)
  public void watch(long topicId) {
    Topic topic = new Topic();
    topic.setId(topicId);

    UserSession userSession = this.userSession;

    this.watchService.watch(topic, userSession.getUser());
    this.result.redirectTo(Actions.LIST + "/" + topicId);
  }
  /**
   * 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;
  }
示例#8
0
  /**
   * Check if the logged user has access to the role. This method gets user's id from its session.
   *
   * @param roleName The role name to verify
   * @param value The value relacted to the role to verify for access
   * @return <code>true</code> if the user has access to the role, <code>false</code> if access is
   *     denied
   */
  public static boolean canAccess(String roleName, String value) {
    UserSession us = SessionFacade.getUserSession();

    if (us == null) {
      logger.warn(
          "Found null userSession. Going anonymous. Session id #"
              + JForumExecutionContext.getRequest().getSessionContext().getId());
      us = new UserSession();
      us.makeAnonymous();
    }

    return canAccess(us.getUserId(), roleName, value);
  }
示例#9
0
  /**
   * @see #getMessage(String, String, Object[])
   * @param messageName String
   * @param params Object
   * @return String
   */
  public static String getMessage(String messageName, Object params[]) {
    String lang = "";
    UserSession us = SessionFacade.getUserSession();

    if (us != null && us.getLang() != null) {
      lang = us.getLang();
    }

    if ("".equals(lang)) {
      return getMessage(defaultName, messageName, params);
    }

    return getMessage(lang, messageName, params);
  }
示例#10
0
  /**
   * Makes the current user to unwatch a specific topic
   *
   * @param topicId the id of the topic to unwatch
   */
  @SecurityConstraint(value = AuthenticatedRule.class, displayLogin = true)
  public void unwatch(long topicId) {
    Topic topic = new Topic();
    topic.setId(topicId);

    this.watchService.unwatch(topic, userSession.getUser());
    this.result.redirectTo(this).list(topicId);
  }
示例#11
0
  @Extends(Actions.LIST)
  public void afterList() {
    boolean isWatching = false;
    UserSession userSession = this.userSession;

    if (userSession.isLogged()) {
      Topic topic = (Topic) this.result.included().get("topic");
      TopicWatch subscription = this.watchService.getSubscription(topic, userSession.getUser());
      isWatching = subscription != null;

      if (!subscription.isRead()) {
        subscription.markAsRead();
      }
    }

    this.result.include("isUserWatchingTopic", isWatching);
  }
示例#12
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());
  }
  @Test
  public void moveTopics() {
    when(userSession.getUser()).thenReturn(user);
    when(roleManager.getCanMoveTopics()).thenReturn(true);

    controller.moveTopics(1, "return path", moderationLog, 2, 3, 4);

    verify(service).moveTopics(1, moderationLog, 2, 3, 4);
    verify(mockResult).redirectTo("return path");
  }
  @Test
  public void lockUnlock() {
    when(userSession.getUser()).thenReturn(user);
    when(roleManager.getCanLockUnlockTopics()).thenReturn(true);
    when(mockResult.redirectTo(ForumController.class)).thenReturn(mockForumController);

    controller.lockUnlock(1, null, moderationLog, new int[] {1, 2, 3});

    verify(service).lockUnlock(new int[] {1, 2, 3}, moderationLog);
    verify(mockForumController).show(1, 0);
  }
  @Test
  public void deleteTopicsExpectSuccess() {
    when(userSession.getUser()).thenReturn(user);
    when(roleManager.getCanDeletePosts()).thenReturn(true);
    when(topicRepository.get(4)).thenReturn(new Topic());
    when(topicRepository.get(5)).thenReturn(new Topic());
    when(mockResult.redirectTo(ForumController.class)).thenReturn(mockForumController);

    controller.deleteTopics(1, null, new int[] {4, 5}, moderationLog);

    verify(service).deleteTopics(Arrays.asList(new Topic(), new Topic()), moderationLog);
    // TODO pass zero?
    verify(mockForumController).show(1, 0);
  }
示例#16
0
  /**
   * Checks for user authentication using some SSO implementation
   *
   * @param userSession UserSession
   */
  protected void checkSSO(UserSession userSession) {

    LOG.trace("checkSSO");
    try {
      SSO sso =
          (SSO) Class.forName(SystemGlobals.getValue(ConfigKeys.SSO_IMPLEMENTATION)).newInstance();
      String username = sso.authenticateUser(JForumExecutionContext.getRequest());

      if (username == null || username.trim().equals("")) {
        userSession.makeAnonymous();
      } else {
        SSOUtils utils = new SSOUtils();

        if (!utils.userExists(username)) {
          SessionContext session = JForumExecutionContext.getRequest().getSessionContext();

          String email =
              (String) session.getAttribute(SystemGlobals.getValue(ConfigKeys.SSO_EMAIL_ATTRIBUTE));
          String password =
              (String)
                  session.getAttribute(SystemGlobals.getValue(ConfigKeys.SSO_PASSWORD_ATTRIBUTE));

          if (email == null) {
            email = SystemGlobals.getValue(ConfigKeys.SSO_DEFAULT_EMAIL);
          }

          if (password == null) {
            password = SystemGlobals.getValue(ConfigKeys.SSO_DEFAULT_PASSWORD);
          }

          utils.register(password, email);
        }

        this.configureUserSession(userSession, utils.getUser());
      }
    } catch (Exception e) {
      e.printStackTrace();
      throw new ForumException("Error while executing SSO actions: " + e);
    }
  }
示例#17
0
  /**
   * Do a refresh in the user's session. This method will update the last visit time for the current
   * user, as well checking for authentication if the session is new or the SSO user has changed
   */
  public void refreshSession() {

    LOG.trace("refreshSession");
    UserSession userSession = SessionFacade.getUserSession();
    RequestContext request = JForumExecutionContext.getRequest();

    if (userSession == null) {
      userSession = new UserSession();
      userSession.registerBasicInfo();
      userSession.setSessionId(request.getSessionContext().getId());
      userSession.setIp(request.getRemoteAddr());
      SessionFacade.makeUnlogged();

      if (!JForumExecutionContext.getForumContext().isBot()) {
        // Non-SSO authentications can use auto login
        if (!ConfigKeys.TYPE_SSO.equals(SystemGlobals.getValue(ConfigKeys.AUTHENTICATION_TYPE))) {
          if (SystemGlobals.getBoolValue(ConfigKeys.AUTO_LOGIN_ENABLED)) {
            this.checkAutoLogin(userSession);
          } else {
            userSession.makeAnonymous();
          }
        } else {
          this.checkSSO(userSession);
        }
      }

      SessionFacade.add(userSession);
    } else if (ConfigKeys.TYPE_SSO.equals(SystemGlobals.getValue(ConfigKeys.AUTHENTICATION_TYPE))) {
      SSO sso;

      try {
        sso =
            (SSO)
                Class.forName(SystemGlobals.getValue(ConfigKeys.SSO_IMPLEMENTATION)).newInstance();
      } catch (Exception e) {
        throw new ForumException(e);
      }

      // If SSO, then check if the session is valid
      if (!sso.isSessionValid(userSession, request)) {
        SessionFacade.remove(userSession.getSessionId());
        refreshSession();
      }
    } else {
      SessionFacade.getUserSession().updateSessionTime();
    }
  }
示例#18
0
 /**
  * @see net.jforum.security.AccessRule#shouldProceed(net.jforum.entities.UserSession,
  *     javax.servlet.http.HttpServletRequest)
  */
 @Override
 public boolean shouldProceed(UserSession userSession, HttpServletRequest request) {
   return userSession.getRoleManager().isModerator();
 }