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 proceedWithFilterChain(
      FilterChain chain, HttpServletRequest httpRequest, HttpServletResponse httpResponse)
      throws IOException, ServletException {

    BesServletRequestReader.param2Attr(httpRequest, Constants.REQ_PARAM_SUB_KEY);
    BesServletRequestReader.param2Attr(httpRequest, Constants.REQ_PARAM_CONTEXT_PATH);
    BesServletRequestReader.param2Attr(httpRequest, Constants.REQ_PARAM_SUPPLIER_ID);
    BesServletRequestReader.param2Attr(httpRequest, Constants.REQ_ATTR_SERVICE_LOGIN_TYPE);
    BesServletRequestReader.param2Attr(httpRequest, Constants.REQ_ATTR_ERROR_KEY);

    chain.doFilter(httpRequest, httpResponse);
  }
  /**
   * Invokes the validators and bean actions specified in the xhtml file to change the user's
   * password.
   *
   * @throws ServletException
   * @throws IOException
   * @throws DatatypeConfigurationException
   * @throws SAML2AuthnRequestException
   */
  protected boolean handleChangeUserPasswordRequest(
      FilterChain chain,
      HttpServletRequest httpRequest,
      HttpServletResponse httpResponse,
      AuthorizationRequestData rdo,
      IdentityService identityService)
      throws IOException, ServletException {
    if (rdo.isRequestedToChangePwd()) {

      if (!PasswordValidator.validPasswordLength(rdo.getNewPassword())
          || !PasswordValidator.validPasswordLength(rdo.getNewPassword2())
          || !PasswordValidator.passwordsAreEqual(rdo.getNewPassword(), rdo.getNewPassword2())) {
        // Let JSF run the validators and return the response!
        chain.doFilter(httpRequest, httpResponse);
        return false;
      }

      // Run the validators and bean methods. Prevent JSF
      // from writing content to the response, otherwise the following
      // redirect's wouldn't work.
      HttpServletResponse resp =
          new HttpServletResponseWrapper(httpResponse) {
            @Override
            public void flushBuffer() throws IOException {}

            @Override
            public PrintWriter getWriter() throws IOException {
              return new PrintWriter(getOutputStream());
            }

            @Override
            public ServletOutputStream getOutputStream() throws IOException {
              return new ServletOutputStream() {
                @Override
                public void write(int b) throws IOException {}
              };
            }
          };
      chain.doFilter(httpRequest, resp);
      httpResponse.reset();
    }

    VOUser voUser = new VOUser();
    voUser.setUserId(rdo.getUserId());
    try {
      voUser = identityService.getUser(voUser);
    } catch (ObjectNotFoundException e) {
      handleUserNotRegistered(chain, httpRequest, httpResponse, rdo);
      return false;
    } catch (SaaSApplicationException e) {
      setErrorAttributesAndForward(errorPage, httpRequest, httpResponse, e);
      return false;
    }

    if (httpRequest.getAttribute(Constants.REQ_ATTR_ERROR_KEY) != null) {
      // Error occurred - check if user is locked now
      if (voUser.getStatus() != null
          && voUser.getStatus().getLockLevel() > UserAccountStatus.LOCK_LEVEL_LOGIN) {
        httpRequest.setAttribute(Constants.REQ_ATTR_ERROR_KEY, BaseBean.ERROR_USER_LOCKED);
        sendRedirect(httpRequest, httpResponse, errorPage);
      } else {
        // Run it again to get error result on current response
        chain.doFilter(httpRequest, httpResponse);
      }

      return false;
    }

    if (voUser.getStatus() != UserAccountStatus.ACTIVE) {
      // the password change request failed
      // set the REQ_ATTR_ERROR_KEY to avoid an infinite loop
      httpRequest
          .getSession()
          .setAttribute(Constants.SESS_ATTR_USER, identityService.getCurrentUserDetails());
      httpRequest.setAttribute(Constants.REQ_ATTR_ERROR_KEY, "");
      if (rdo.isMarketplace()) {
        forward(BaseBean.MARKETPLACE_LOGIN, httpRequest, httpResponse);
      } else {
        forward(pwdPage, httpRequest, httpResponse);
      }
      return false;
    }

    rdo.setPassword(httpRequest.getParameter(BesServletRequestReader.REQ_PARAM_PASSWORD_NEW));
    rdo.getUserDetails().setStatus(UserAccountStatus.ACTIVE);
    return true;
  }
  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);
    }
  }
  /**
   * If the user wants to access a service URL we must check if he is logged into the service.
   *
   * @return the given HTTP request, a request wrapper which must be used to perform the service
   *     login or null if the caller should continue with the filter chain
   * @throws IOException
   * @throws ServletException
   * @throws DatatypeConfigurationException
   * @throws SAML2AuthnRequestException
   * @throws Exception
   */
  private HttpServletRequest processServiceUrl(
      HttpServletRequest request,
      HttpServletResponse response,
      FilterChain chain,
      String subKey,
      String contextPath,
      AuthorizationRequestData rdo)
      throws ServletException, IOException {

    HttpSession session = request.getSession();
    ServiceAccess serviceAccess = ServiceAccess.getServiceAcccessFor(session);

    if ("/".equals(contextPath) && !BesServletRequestReader.onlyServiceLogin(session)) {
      // if the user accesses a subscription from the my subscription list
      // we check the subscription key map in the session (this causes
      // some overhead - EJB call - and should NOT be done for every
      // service request)

      // preserve mId
      String mId = (String) session.getAttribute(Constants.REQ_PARAM_MARKETPLACE_ID);

      SessionListener.cleanup(session);

      session = request.getSession();
      session.setAttribute(Constants.REQ_PARAM_MARKETPLACE_ID, mId);
    }

    Map<String, VOSubscription> map = getSubMapFromSession(session);
    VOSubscription sub = map.get(subKey);
    VOUserDetails userDetails = (VOUserDetails) session.getAttribute(Constants.SESS_ATTR_USER);
    if (BesServletRequestReader.onlyServiceLogin(session)) {
      session.removeAttribute(Constants.SESS_ATTR_ONLY_SERVICE_LOGIN);

      // at least remove the user details from the session
      session.removeAttribute(Constants.SESS_ATTR_USER);
      if (userDetails != null) {
        session.setAttribute(Constants.REQ_PARAM_LOCALE, userDetails.getLocale());
      }
    }

    if (userDetails != null
        && userDetails.getStatus() != UserAccountStatus.PASSWORD_MUST_BE_CHANGED) {
      // the user is already logged in

      if (sub == null) {
        // the user is not logged in the service, we must call the
        // SSO bridge

        sub = getSubscription(serviceAccess, subKey);

        if (sub == null) {
          UserNotAssignedException e =
              new UserNotAssignedException(subKey, userDetails.getUserId());
          logger.logError(
              Log4jLogger.SYSTEM_LOG | Log4jLogger.AUDIT_LOG,
              e,
              LogMessageIdentifier.ERROR_ACTIVE_SUBSCRIPTION_FOR_CURRENT_USER_FAILED,
              subKey);
          setErrorAttributesAndForward(
              getDefaultUrl(serviceAccess, rdo, request), request, response, e);
          return null;

        } else if (sub.getStatus() != SubscriptionStatus.ACTIVE
            && sub.getStatus() != SubscriptionStatus.PENDING_UPD) {
          SubscriptionStateException e =
              new SubscriptionStateException(
                  "Subscription '" + subKey + "' not active or pending update.",
                  Reason.ONLY_ACTIVE);
          logger.logError(
              Log4jLogger.SYSTEM_LOG | Log4jLogger.AUDIT_LOG,
              e,
              LogMessageIdentifier.ERROR_SUBSCRIPTION_NOT_ACTIVE,
              subKey);
          setErrorAttributesAndForward(
              getDefaultUrl(serviceAccess, rdo, request), request, response, e);
          return null;

        } else if (!sub.getServiceBaseURL()
            .toLowerCase()
            .startsWith(request.getScheme().toLowerCase() + "://")) {
          setErrorAttributesAndForward(errorPage, request, response, new ServiceSchemeException());
          return null;
        }

        String userToken = ADMStringUtils.getRandomString(40);

        // create a service session database record (which is used by
        // the service to resolve the user token)
        try {
          synchronized (map) {
            createServiceSession(serviceAccess, subKey, session.getId(), userToken);
            // the map must be filled after the service session was
            // created otherwise the session listener cleanup method
            // might clear the list
            map.put(subKey, sub);
          }
        } catch (ObjectNotFoundException e) {
          handleSubscriptionNotFound(chain, request, response, rdo);
          return null;
        } catch (ServiceParameterException e) {
          setErrorAttributesAndForward(Constants.SERVICE_USAGE_ERROR_URI, request, response, e);
          return null;
        } catch (SaaSApplicationException e) {
          setErrorAttributesAndForward(errorPage, request, response, e);
          return null;
        }

        if (sub.getServiceAccessType() == ServiceAccessType.LOGIN) {
          // perform a redirect to the SSO bridge with the user token
          String url = removeEndingSlash(sub.getServiceBaseURL());
          if (sub.getServiceLoginPath() != null) {
            url += sub.getServiceLoginPath();
          }
          if (url.contains("?")) {
            url += "&";
          } else {
            url += "?";
          }
          SsoParameters ssoParameters = new SsoParameters();
          ssoParameters.setContextPath(contextPath);
          ssoParameters.setInstanceId(sub.getServiceInstanceId());
          ssoParameters.setLanguage(userDetails.getLocale());
          ssoParameters.setSubscriptionKey(subKey);
          ssoParameters.setBssId(request.getSession().getId());
          ssoParameters.setUsertoken(userToken);
          url += ssoParameters.getQueryString();
          JSFUtils.sendRedirect(response, url);
          return null;
        }

      } else {
        if (sub.getServiceAccessType() == ServiceAccessType.LOGIN) {
          // send a redirect to the service base URL, the service
          // session should be still active
          JSFUtils.sendRedirect(response, sub.getServiceBaseURL());
          return null;
        }

        // nothing to do (the user is logged in the platform and the
        // service) the rewriting is done by the subsequent filters in
        // the filter chain which is activated by the caller
      }
    } else {
      // the user is not logged in

      if (sub == null) {
        // the user is neither logged in platform nor in the
        // service,
        //
        // The later processing will forward to the service login
        // page processing. After the login there will be a redirect to
        // the primarily requested URL which will perform the service
        // login
        session.setAttribute(Constants.SESS_ATTR_ONLY_SERVICE_LOGIN, Boolean.TRUE);

      } else {
        // the user is logged in the service

        if (sub.getServiceAccessType() == ServiceAccessType.LOGIN) {
          // send a redirect to the service base URL, the service
          // session should be still active
          JSFUtils.sendRedirect(response, sub.getServiceBaseURL());
        } else {
          // don't perform any other checks continue with the
          // filter chain which will perform the rewriting
          chain.doFilter(request, response);
        }
        return null;
      }
    }
    return request;
  }