void redirectToPrimarilyRequestedUrl(
      FilterChain chain,
      HttpServletRequest httpRequest,
      HttpServletResponse httpResponse,
      ServiceAccess serviceAccess,
      AuthorizationRequestData rdo)
      throws IOException, ServletException {

    String forwardUrl =
        (String) httpRequest.getSession().getAttribute(Constants.SESS_ATTR_FORWARD_URL);

    if (BesServletRequestReader.onlyServiceLogin(httpRequest.getSession())) {
      if (forwardUrl == null) {
        forwardUrl = Constants.SERVICE_BASE_URI + "/" + rdo.getSubscriptionKey() + "/";
      }
      JSFUtils.sendRedirect(httpResponse, httpRequest.getContextPath() + forwardUrl);
      return;
    }

    if (ADMStringUtils.isBlank(forwardUrl) || forwardUrl.startsWith(MenuBean.LINK_DEFAULT)) {
      forwardUrl = getDefaultUrl(serviceAccess, rdo, httpRequest);
    }

    if ((ADMStringUtils.isBlank(forwardUrl) || rdo.getRelativePath().startsWith(forwardUrl))
        && !rdo.isMarketplaceLoginPage()) {
      chain.doFilter(httpRequest, httpResponse);
    } else {
      JSFUtils.sendRedirect(httpResponse, httpRequest.getContextPath() + forwardUrl);
    }
  }
  boolean handleLoggedInUser(
      FilterChain chain,
      HttpServletRequest httpRequest,
      HttpServletResponse httpResponse,
      ServiceAccess serviceAccess,
      AuthorizationRequestData rdo)
      throws ServletException, IOException {

    VOUserDetails userDetails = rdo.getUserDetails();
    if (userDetails != null) {
      httpRequest.getSession().setAttribute(PORTAL_HAS_BEEN_REQUESTED, !rdo.isMarketplace());

      // if the user wants to use another organization he must login
      // again (the service sessions are destroyed as well)

      // don't let a user with status PASSWORD_MUST_BE_CHANGED see any
      // site but the one to change the pwd
      if (!authSettings.isServiceProvider()) {
        if (userDetails.getStatus() == UserAccountStatus.PASSWORD_MUST_BE_CHANGED
            && !rdo.isRequestedToChangePwd()) {
          forwardToPwdPage(userDetails.getUserId(), httpRequest, httpResponse);
          return true;
        }
      }

      // TODO stavreva: check this again
      if (authSettings.isServiceProvider() || !rdo.isRequestedToChangePwd()) {
        long t = System.currentTimeMillis();
        if (ADMStringUtils.isBlank(httpRequest.getServletPath())
            || httpRequest.getServletPath().startsWith(MenuBean.LINK_DEFAULT)) {
          String defaultUrl = getDefaultUrl(serviceAccess, rdo, httpRequest);
          forward(defaultUrl, httpRequest, httpResponse);
        }

        if (loginPage.equalsIgnoreCase(httpRequest.getServletPath())) {
          sendRedirect(httpRequest, httpResponse, MenuBean.LINK_DEFAULT);
        }

        if (isPageForbiddenToAccess(httpRequest, rdo, serviceAccess)) {
          forward(insufficientAuthoritiesUrl, httpRequest, httpResponse);
        }
        chain.doFilter(httpRequest, httpResponse);
        if (logger.isDebugLoggingEnabled()) {
          logger.logDebug(
              "URL='"
                  + rdo.getRelativePath()
                  + "' processed in "
                  + (System.currentTimeMillis() - t)
                  + "ms");
        }
        return true;
      }
    }

    return false;
  }
 private void handleSubscriptionNotFound(
     FilterChain chain,
     HttpServletRequest httpRequest,
     HttpServletResponse httpResponse,
     AuthorizationRequestData rdo)
     throws IOException, ServletException {
   if (authSettings.isServiceProvider()) {
     httpRequest.setAttribute(Constants.REQ_ATTR_ERROR_KEY, BaseBean.ERROR_SUBSCRIPTION_NOT_FOUND);
     forward(errorPage, httpRequest, httpResponse);
   } else {
     forwardToLoginPage(rdo.getRelativePath(), false, httpRequest, httpResponse, chain);
   }
 }
 private void handleCommunicationException(
     FilterChain chain,
     HttpServletRequest httpRequest,
     HttpServletResponse httpResponse,
     AuthorizationRequestData rdo)
     throws ServletException, IOException {
   httpRequest.setAttribute(Constants.REQ_ATTR_ERROR_KEY, BaseBean.ERROR_LOGIN_IMPOSSIBLE);
   if (authSettings.isServiceProvider()) {
     forward(errorPage, httpRequest, httpResponse);
   } else {
     forwardToLoginPage(rdo.getRelativePath(), false, httpRequest, httpResponse, chain);
   }
 }
 private void handleUserNotRegistered(
     FilterChain chain,
     HttpServletRequest httpRequest,
     HttpServletResponse httpResponse,
     AuthorizationRequestData rdo)
     throws IOException, ServletException {
   if (authSettings.isServiceProvider()) {
     httpRequest.setAttribute(Constants.REQ_ATTR_ERROR_KEY, BaseBean.ERROR_LOGIN_SAML_SP);
     forward(errorPage, httpRequest, httpResponse);
   } else {
     httpRequest.setAttribute(Constants.REQ_ATTR_ERROR_KEY, BaseBean.ERROR_LOGIN);
     forwardToLoginPage(rdo.getRelativePath(), false, httpRequest, httpResponse, chain);
   }
 }
  /**
   * Check if the current URL is protected and the current session doesn't contain a user object. If
   * this is the case perform a login.
   *
   * <p>The doFilter method of the Filter is called by the container each time a request/response
   * pair is passed through the chain due to a client request for a resource at the end of the
   * chain.
   *
   * @throws IOException
   * @throws ServletException
   */
  @Override
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws IOException, ServletException {

    HttpServletRequest httpRequest =
        new IgnoreCharacterEncodingHttpRequestWrapper((HttpServletRequest) request);
    HttpServletResponse httpResponse = (HttpServletResponse) response;
    AuthorizationRequestData rdo = initializeRequestDataObject(httpRequest);

    try {
      if (isPublicAccess(rdo, httpRequest)) {
        proceedWithFilterChain(chain, httpRequest, httpResponse);
      } else {
        handleProtectedUrlAndChangePwdCase(chain, httpRequest, httpResponse, rdo);
      }
    } catch (ServletException e) {

      // relogin is not possible in this case,
      // no SAML response to extract userid and generate password.
      if (authSettings.isServiceProvider()) {
        throw e;
      }

      if (e.getCause() instanceof ViewExpiredException) {
        // if we were logged in but a logout occurs from a different
        // browser tab, we get this exception - so redirect to the
        // same page to stay on it (Bug 7552)
        final StringBuffer url =
            new StringBuffer(rdo.getRelativePath() == null ? "" : rdo.getRelativePath());
        reLogginUserIfRequired(httpRequest, httpResponse, rdo, url);
        sendRedirect(httpRequest, httpResponse, url.toString());
      } else {
        throw e;
      }
    }
  }
 private void handleNumberFormatException(
     FilterChain chain,
     HttpServletRequest httpRequest,
     HttpServletResponse httpResponse,
     NumberFormatException e,
     AuthorizationRequestData rdo)
     throws ServletException, IOException {
   logger.logError(
       Log4jLogger.SYSTEM_LOG,
       e,
       LogMessageIdentifier.ERROR_PARSE_SUBSCRIPTION_KEY_FAILED,
       rdo.getSubscriptionKey());
   if (authSettings.isServiceProvider()) {
     httpRequest.setAttribute(Constants.REQ_ATTR_ERROR_KEY, BaseBean.ERROR_SUBSCRIPTION_KEY);
     forward(errorPage, httpRequest, httpResponse);
   } else {
     httpRequest.setAttribute(Constants.REQ_ATTR_ERROR_KEY, BaseBean.ERROR_LOGIN);
     forwardToLoginPage(rdo.getRelativePath(), false, httpRequest, httpResponse, chain);
   }
 }
  protected void handleProtectedUrlAndChangePwdCase(
      FilterChain chain,
      HttpServletRequest httpRequest,
      HttpServletResponse httpResponse,
      AuthorizationRequestData rdo)
      throws IOException, ServletException {

    if (logger.isDebugLoggingEnabled()) {
      logger.logDebug("Access to protected URL='" + rdo.getRelativePath() + "'");
    }

    ServiceAccess serviceAccess = ServiceAccess.getServiceAcccessFor(httpRequest.getSession());

    try {
      if (rdo.isAccessToServiceUrl()) {
        /*
         * We must NOT read the request parameters for service URLs
         * because this would cause a state switch of the request.
         * Afterwards the rewriting of a POST request may fail because
         * the parameters can't be accessed via the request input
         * stream.
         */
        httpRequest = handleServiceUrl(chain, httpRequest, httpResponse, rdo);
        if (httpRequest == null) {
          return;
        }
      } else if (ADMStringUtils.isBlank(rdo.getUserId())) {
        if (authSettings.isServiceProvider()) {
          if (isSamlForward(httpRequest)) {
            SAMLCredentials samlCredentials = new SAMLCredentials(httpRequest);
            rdo.setUserId(samlCredentials.getUserId());
            if (rdo.getUserId() == null) {
              httpRequest.setAttribute(
                  Constants.REQ_ATTR_ERROR_KEY, BaseBean.ERROR_INVALID_SAML_RESPONSE);
              forward(errorPage, httpRequest, httpResponse);
            }
          }
        } else {
          rdo.setUserId(httpRequest.getParameter(Constants.REQ_PARAM_USER_ID));
        }
      }

      // continue if user is already logged-in
      if (handleLoggedInUser(chain, httpRequest, httpResponse, serviceAccess, rdo)) {
        return;
      }

      // the httpRequest was already processed and we forwarded to the
      // corresponding page therefore we must not try to login again
      if (httpRequest.getAttribute(Constants.REQ_ATTR_ERROR_KEY) != null) {
        chain.doFilter(httpRequest, httpResponse);
        return;
      }

      refreshData(authSettings, rdo, httpRequest, httpResponse);

      // user not logged in, check user-name and password before login
      // don't do a trim on password because it may have
      // leading/trailing/only blanks

      if (authSettings.isServiceProvider()) {
        rollbackDefaultTimeout(httpRequest);
        if (ADMStringUtils.isBlank(rdo.getUserId())) {
          httpRequest.setAttribute(
              Constants.REQ_ATTR_ERROR_KEY, BaseBean.ERROR_INVALID_SAML_RESPONSE);
          if (isSamlForward(httpRequest)) {
            forward(errorPage, httpRequest, httpResponse);
          } else {
            forwardToLoginPage(rdo.getRelativePath(), true, httpRequest, httpResponse, chain);
          }
          return;
        }
      } else {
        if (ADMStringUtils.isBlank(rdo.getUserId()) || !rdo.isPasswordSet()) {
          if (!rdo.isMarketplace()
              && (!ADMStringUtils.isBlank(rdo.getUserId()) || rdo.isPasswordSet())) {
            // login data not complete, user or password empty
            httpRequest.setAttribute(Constants.REQ_ATTR_ERROR_KEY, BaseBean.ERROR_LOGIN);
          }
          forwardToLoginPage(rdo.getRelativePath(), true, httpRequest, httpResponse, chain);
          return;
        }
      }

      IdentityService identityService = serviceAccess.getService(IdentityService.class);
      VOUser voUser;
      try {
        voUser = readTechnicalUserFromDb(identityService, rdo);
      } catch (ObjectNotFoundException e) {
        handleUserNotRegistered(chain, httpRequest, httpResponse, rdo);
        return;
      } catch (SaaSApplicationException e) {
        setErrorAttributesAndForward(errorPage, httpRequest, httpResponse, e);
        return;
      }

      if (!authSettings.isServiceProvider()) {
        if (isAccountLocked(httpRequest, httpResponse, voUser)) {
          return;
        }
      }

      final boolean operationSucceeded;
      if (!authSettings.isServiceProvider() && rdo.isRequestedToChangePwd()) {
        operationSucceeded =
            handleChangeUserPasswordRequest(chain, httpRequest, httpResponse, rdo, identityService);
      } else {
        operationSucceeded =
            loginUser(chain, httpRequest, httpResponse, voUser, rdo, identityService);
      }
      if (!operationSucceeded) {
        return;
      }
      rdo.setUserDetails(identityService.getCurrentUserDetails());

      // read user details value object and store it in the session, DON'T
      // use old session, because it might have been invalidated
      httpRequest.getSession().setAttribute(Constants.SESS_ATTR_USER, rdo.getUserDetails());

      if (isPageForbiddenToAccess(httpRequest, rdo, serviceAccess)) {
        forward(insufficientAuthoritiesUrl, httpRequest, httpResponse);
      }
      // check if user must change his password
      if (!authSettings.isServiceProvider()
          && (rdo.getUserDetails().getStatus() == UserAccountStatus.PASSWORD_MUST_BE_CHANGED)) {
        forwardToPwdPage(rdo.getUserDetails().getUserId(), httpRequest, httpResponse);
      } else {
        redirectToPrimarilyRequestedUrl(chain, httpRequest, httpResponse, serviceAccess, rdo);
      }

    } catch (NumberFormatException e) {
      handleNumberFormatException(chain, httpRequest, httpResponse, e, rdo);
    } catch (ServletException e) {
      handleServletException(httpRequest, httpResponse, e);
    } catch (MarketplaceRemovedException e) {
      handleMarketplaceRemovedException(httpRequest, httpResponse);
    }
  }