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);
  }
  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);
    }
  }
 private void setErrorAttributesAndForward(
     String forwardUrl,
     HttpServletRequest httpRequest,
     HttpServletResponse httpResponse,
     SaaSApplicationException e)
     throws ServletException, IOException {
   BesServletRequestReader.setErrorAttributes(httpRequest, e);
   forward(forwardUrl, httpRequest, httpResponse);
 }
  private HttpServletRequest handleServiceUrl(
      FilterChain chain,
      HttpServletRequest httpRequest,
      HttpServletResponse httpResponse,
      AuthorizationRequestData rdo)
      throws IOException, ServletException {

    VOMarketplace mpl;
    try {
      mpl = determineMarketplaceForSubscription(httpRequest, rdo);
    } catch (ObjectNotFoundException e) {

      logger.logError(
          Log4jLogger.SYSTEM_LOG,
          e,
          LogMessageIdentifier.ERROR_SUBSCRIPTION_NOT_FOUND,
          rdo.getSubscriptionKey());
      BesServletRequestReader.setErrorAttributes(httpRequest, e);

      handleSubscriptionNotFound(chain, httpRequest, httpResponse, rdo);
      return null;
    }

    // Bug 9588: Marketplace may have been deleted
    if (mpl != null) {
      httpRequest.setAttribute(
          Constants.REQ_ATTR_SERVICE_LOGIN_TYPE, Constants.REQ_ATTR_LOGIN_TYPE_MPL);

      httpRequest
          .getSession()
          .setAttribute(Constants.REQ_PARAM_MARKETPLACE_ID, mpl.getMarketplaceId());
    } else {
      httpRequest.setAttribute(
          Constants.REQ_ATTR_SERVICE_LOGIN_TYPE, Constants.REQ_ATTR_LOGIN_TYPE_NO_MPL);
    }

    String contextPath = rdo.getContextPath();
    if (!ADMStringUtils.isBlank(httpRequest.getQueryString())) {
      contextPath += "?" + httpRequest.getQueryString();
    }
    httpRequest.setAttribute(Constants.REQ_PARAM_SUB_KEY, rdo.getSubscriptionKey());
    httpRequest.setAttribute(Constants.REQ_PARAM_CONTEXT_PATH, contextPath);

    return processServiceUrl(
        httpRequest, httpResponse, chain, rdo.getSubscriptionKey(), contextPath, rdo);
  }
 private void handleServletException(
     HttpServletRequest httpRequest, HttpServletResponse httpResponse, ServletException e)
     throws IOException, ServletException {
   EJBException ejbEx = ExceptionHandler.getEJBException(e);
   if (ejbEx != null
       && ejbEx.getCause() instanceof Exception
       && ejbEx.getCausedByException() instanceof AccessException) {
     String forwardErrorPage;
     if (BesServletRequestReader.isMarketplaceRequest(httpRequest)) {
       forwardErrorPage = Marketplace.MARKETPLACE_ROOT + Constants.INSUFFICIENT_AUTHORITIES_URI;
     } else {
       forwardErrorPage = Constants.INSUFFICIENT_AUTHORITIES_URI;
     }
     JSFUtils.sendRedirect(httpResponse, httpRequest.getContextPath() + forwardErrorPage);
   } else {
     // make sure we do not catch exceptions cause by
     // ViewExpiredException here, they'll be handled directly in the
     // doFilter()
     throw e;
   }
 }
  protected boolean loginUser(
      FilterChain chain,
      HttpServletRequest httpRequest,
      HttpServletResponse httpResponse,
      VOUser voUser,
      AuthorizationRequestData rdo,
      IdentityService identityService)
      throws ServletException, IOException {

    HttpSession session = httpRequest.getSession();
    boolean onlyServiceLogin = BesServletRequestReader.onlyServiceLogin(session);
    String forwardUrl = (String) session.getAttribute(Constants.SESS_ATTR_FORWARD_URL);
    SessionBean sessionBean = (SessionBean) session.getAttribute(Constants.SESS_ATTR_SESSION_BEAN);

    ServiceAccess serviceAccess = ServiceAccess.getServiceAcccessFor(session);

    if (onlyServiceLogin) {
      session.setAttribute(Constants.SESS_ATTR_ONLY_SERVICE_LOGIN, Boolean.TRUE);
    }

    if (!ADMStringUtils.isBlank(forwardUrl)) {
      session.setAttribute(Constants.SESS_ATTR_FORWARD_URL, forwardUrl);
    }

    if (sessionBean != null) {
      session.setAttribute(Constants.SESS_ATTR_SESSION_BEAN, sessionBean);
    }

    if (!ADMStringUtils.isBlank(rdo.getMarketplaceId())) {
      session.setAttribute(Constants.REQ_PARAM_MARKETPLACE_ID, rdo.getMarketplaceId());
    }

    // authenticate the user
    // IMPORTANT: Changes to this method must also be applied to
    // UserBean.login()
    try {
      serviceAccess.login(voUser, rdo.getPassword(), httpRequest, httpResponse);
    } catch (CommunicationException e) {
      handleCommunicationException(chain, httpRequest, httpResponse, rdo);
      return false;
    } catch (LoginException e) {
      logger.logInfo(
          Log4jLogger.ACCESS_LOG,
          LogMessageIdentifier.INFO_USER_LOGIN_INVALID,
          httpRequest.getRemoteHost(),
          Integer.toString(httpRequest.getRemotePort()),
          StringUtils.isNotBlank(voUser.getUserId()) ? voUser.getUserId() : "",
          IPResolver.resolveIpAddress(httpRequest),
          voUser.getTenantId());
      try {
        voUser = identityService.getUser(voUser);
      } catch (ObjectNotFoundException e1) {
        handleUserNotRegistered(chain, httpRequest, httpResponse, rdo);
        return false;
      } catch (SaaSApplicationException e1) {
        setErrorAttributesAndForward(errorPage, httpRequest, httpResponse, e1);
        return false;
      }

      if (voUser.getStatus() != null
          && voUser.getStatus().getLockLevel() > UserAccountStatus.LOCK_LEVEL_LOGIN) {
        httpRequest.setAttribute(Constants.REQ_ATTR_ERROR_KEY, BaseBean.ERROR_USER_LOCKED);
        forward(errorPage, httpRequest, httpResponse);
        return false;
      }

      handleLoginException(chain, httpRequest, httpResponse, rdo);
      return false;
    }

    if (!rdo.isMarketplace()
        && !rdo.isAccessToServiceUrl() // BE09588 Login is OK if a
        // service is accessed, whose
        // subscription has no
        // marketplace
        && identityService.getCurrentUserDetails().getOrganizationRoles().size() == 1
        && identityService
            .getCurrentUserDetails()
            .getOrganizationRoles()
            .contains(OrganizationRoleType.CUSTOMER)) {
      if (ADMStringUtils.isBlank(rdo.getMarketplaceId())) {
        if (redirectToMpUrl(httpRequest, httpResponse)) {
          setupUserDetail(httpRequest, rdo, identityService, session);
          return false;
        } else {
          httpRequest.setAttribute(
              Constants.REQ_ATTR_ERROR_KEY, BaseBean.ERROR_INVALID_MARKETPLACE_URL);
          forward(BaseBean.MARKETPLACE_ERROR_PAGE, httpRequest, httpResponse);
        }
      } else {
        setupUserDetail(httpRequest, rdo, identityService, session);
        forward(BaseBean.MARKETPLACE_START_SITE, httpRequest, httpResponse);
      }
      return false;
    }

    // get the service again because the credentials have been
    // changed (important for WS usage)
    identityService = serviceAccess.getService(IdentityService.class);
    try {
      identityService.refreshLdapUser();
    } catch (ValidationException e) {
      logger.logDebug(
          "Refresh of LDAP user failed, most likely due to missing/wrong LDAP settings");
    }

    logger.logInfo(
        Log4jLogger.ACCESS_LOG,
        LogMessageIdentifier.INFO_USER_LOGIN_SUCCESS,
        StringUtils.isNotBlank(voUser.getUserId()) ? voUser.getUserId() : "",
        IPResolver.resolveIpAddress(httpRequest),
        voUser.getTenantId());
    return true;
  }
  /**
   * 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;
  }