VOUser readTechnicalUserFromDb(IdentityService service, AuthorizationRequestData ard)
     throws ObjectNotFoundException, OperationNotPermittedException, OrganizationRemovedException {
   VOUser voUser = new VOUser();
   voUser.setUserId(ard.getUserId());
   voUser.setTenantId(ard.getTenantID());
   voUser = service.getUser(voUser);
   return voUser;
 }
  /**
   * 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 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;
  }