Beispiel #1
0
  public void validateCaptcha(FacesContext context, UIComponent toValidate, Object value) {

    if (c != null) {
      Map map = context.getExternalContext().getRequestParameterMap();
      String challenge = map.get("recaptcha_challenge_field").toString();
      String response = map.get("recaptcha_response_field").toString();
      HttpServletRequest req =
          (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
      ReCaptchaResponse resp = r.checkAnswer(req.getRemoteAddr(), challenge, response);
      if (!resp.isValid() || hasValidationErrors) {
        Logger.getLogger(ContactUsPage.class.getName())
            .info("INVALID RESPONSE: " + resp.getErrorMessage());
        ((UIInput) toValidate).setValid(false);
        if (hasValidationErrors) {
          context.addMessage(
              toValidate.getClientId(context),
              new FacesMessage(
                  "Some required information was entered incorrectly. Please press refresh below to get a new challenge, then correct the issue."));
          hasValidationErrors = false;
        } else {
          context.addMessage(
              toValidate.getClientId(context),
              new FacesMessage("Press refresh below to get a new challenge."));
          hasValidationErrors = false;
        }
      }
    }
  }
  /**
   * AJAX Called once user is submitting upload form
   *
   * @param model
   * @param file - Uploaded file
   * @param comment - Comment for uploaded file
   * @return
   */
  @RequestMapping(method = RequestMethod.POST)
  public @ResponseBody JsonResponse uploadAction(
      @Valid @ModelAttribute(value = "image") Image image,
      @RequestParam(value = "captcha_challenge", required = true) String challenge,
      @RequestParam(value = "captcha_response", required = true) String response,
      BindingResult result,
      HttpServletRequest paramHttpServletRequest) {
    JsonResponse jsonResponse = new JsonResponse();
    String remoteAddr = paramHttpServletRequest.getRemoteAddr();
    ReCaptchaResponse reCaptchaResponse = recaptcha.checkAnswer(remoteAddr, challenge, response);
    if (!reCaptchaResponse.isValid()) {
      jsonResponse.setCaptchaError(
          context.getMessage("error.bad.captcha", null, Locale.getDefault()));
      return jsonResponse;
    }

    prepareImage(image);
    (new ImageValidator()).validate(image, result);
    if (!result.hasErrors()) {
      try {
        image.setBytes(image.getFile().getBytes());
        image.setContentType(image.getFile().getContentType());
        image = imageService.saveImage(image);
        jsonResponse.setResponse(paramHttpServletRequest.getRequestURL() + image.getId());
      } catch (Exception e) {
        log.error(e.getMessage());
      }
    } else {
      for (ObjectError error : result.getAllErrors()) {
        jsonResponse.appendError(context.getMessage(error.getCode(), null, Locale.getDefault()));
      }
    }
    return jsonResponse;
  }
 public boolean isValid(HttpServletRequest request) {
   ReCaptcha recaptcha = ReCaptchaFactory.newReCaptcha(publicKey, privateKey, false);
   ReCaptchaResponse response =
       recaptcha.checkAnswer(
           request.getRemoteAddr(),
           request.getParameter("recaptcha_challenge_field"),
           request.getParameter("recaptcha_response_field"));
   return response.isValid();
 }
  @POST
  @Path("resetpw")
  @Consumes("application/x-www-form-urlencoded")
  @Produces(MediaType.TEXT_HTML)
  public Viewable handlePasswordResetForm(
      @Context UriInfo ui,
      @FormParam("token") String token,
      @FormParam("password1") String password1,
      @FormParam("password2") String password2,
      @FormParam("recaptcha_challenge_field") String challenge,
      @FormParam("recaptcha_response_field") String uresponse) {

    try {
      this.token = token;

      if ((password1 != null) || (password2 != null)) {
        if (management.checkPasswordResetTokenForAdminUser(user.getUuid(), token)) {
          if ((password1 != null) && password1.equals(password2)) {
            management.setAdminUserPassword(user.getUuid(), password1);
            return handleViewable("resetpw_set_success", this);
          } else {
            errorMsg = "Passwords didn't match, let's try again...";
            return handleViewable("resetpw_set_form", this);
          }
        } else {
          errorMsg = "Something odd happened, let's try again...";
          return handleViewable("resetpw_email_form", this);
        }
      }

      if (!useReCaptcha()) {
        management.startAdminUserPasswordResetFlow(user);
        return handleViewable("resetpw_email_success", this);
      }

      ReCaptchaImpl reCaptcha = new ReCaptchaImpl();
      reCaptcha.setPrivateKey(properties.getRecaptchaPrivate());

      ReCaptchaResponse reCaptchaResponse =
          reCaptcha.checkAnswer(httpServletRequest.getRemoteAddr(), challenge, uresponse);

      if (reCaptchaResponse.isValid()) {
        management.startAdminUserPasswordResetFlow(user);
        return handleViewable("resetpw_email_success", this);
      } else {
        errorMsg = "Incorrect Captcha";
        return handleViewable("resetpw_email_form", this);
      }

    } catch (RedirectionException e) {
      throw e;
    } catch (Exception e) {
      return handleViewable("error", e);
    }
  }
  public boolean isSuccessful(String challenge, String response) {
    ReCaptchaImpl reCaptcha = new ReCaptchaImpl();
    reCaptcha.setPrivateKey(PRIVATE_KEY);

    ReCaptchaResponse reCaptchaResponse = reCaptcha.checkAnswer(CAPTCHA_URL, challenge, response);
    if (reCaptchaResponse.isValid()) {
      return true;
    } else {
      return false;
    }
  }
 @RequestMapping(value = "/register", method = RequestMethod.POST)
 public String register(
     @ModelAttribute("UserForm") UserForm userForm,
     BindingResult result,
     HttpServletRequest request,
     Model model,
     @RequestParam("recaptcha_challenge_field") String challangeField,
     @RequestParam("recaptcha_response_field") String responseField,
     RedirectAttributes attributes,
     HttpServletResponse response)
     throws IOException {
   // check captcha
   String remoteAddress = request.getRemoteAddr();
   ReCaptchaResponse reCaptchaResponse =
       this.reCaptcha.checkAnswer(remoteAddress, challangeField, responseField);
   if (!reCaptchaResponse.isValid()) {
     model.addAttribute(PathHolder.ATTRIBUTE_NAME__MESSAGE, PathHolder.MESSAGE__WRONG_CAPTCHA);
     model.addAttribute(PathHolder.ATTRIBUTE_NAME__USERFORM, userForm);
     LOG.info(PathHolder.MESSAGE__WRONG_CAPTCHA);
     return PathHolder.PATH__REGISTRATION_PAGE;
   }
   // validate form
   new UserFormValidator().validate(userForm, result);
   if (result.hasErrors()) {
     model.addAttribute(PathHolder.ATTRIBUTE_NAME__MESSAGE, PathHolder.MESSAGE__WRONG_USER_DATA);
     model.addAttribute(PathHolder.ATTRIBUTE_NAME__USERFORM, userForm);
     LOG.warn(PathHolder.MESSAGE__WRONG_USER_DATA);
     return PathHolder.PATH__REGISTRATION_PAGE;
   }
   // check login
   String login = userForm.getLogin();
   try {
     if (!userService.checkLogin(userForm.getLogin())) {
       model.addAttribute(PathHolder.ATTRIBUTE_NAME__MESSAGE, PathHolder.MESSAGE__LOGIN_BUSY);
       model.addAttribute(PathHolder.ATTRIBUTE_NAME__USERFORM, userForm);
       LOG.warn("Can't check login " + login);
       return PathHolder.PATH__REGISTRATION_PAGE;
     }
     // if OK
     userService.createUser(createUser(userForm));
   } catch (Exception e) {
     model.addAttribute(
         PathHolder.ATTRIBUTE_NAME__MESSAGE, PathHolder.MESSAGE__INTERNAL_SERVICE_ERROR);
     model.addAttribute(PathHolder.ATTRIBUTE_NAME__USERFORM, userForm);
     response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
     LOG.error("Can't save new user " + userForm.getLogin(), e);
     return PathHolder.PATH__REGISTRATION_PAGE;
   }
   attributes.addFlashAttribute(
       PathHolder.ATTRIBUTE_NAME__MESSAGE, PathHolder.MESSAGE__REGISTRATION_COMPLETE);
   return PathHolder.PATH__REDIRECT + PathHolder.PATH__LOGIN_PAGE;
 }
  public static boolean checkCaptcha(HttpServletRequest request) {
    String remoteAddr = request.getRemoteAddr();
    ReCaptchaImpl reCaptcha = new ReCaptchaImpl();
    reCaptcha.setPrivateKey("6LcryM4SAAAAAKHGFwoD1t-tQsWB_QGuNInVNYbp");

    String challenge = request.getParameter("recaptcha_challenge_field");
    String uresponse = request.getParameter("recaptcha_response_field");
    ReCaptchaResponse reCaptchaResponse = reCaptcha.checkAnswer(remoteAddr, challenge, uresponse);

    if (reCaptchaResponse.isValid()) {
      return true;
    } else {
      return false;
    }
  }
Beispiel #8
0
  @POST
  @Path("resetpw")
  @Consumes("application/x-www-form-urlencoded")
  @Produces(MediaType.TEXT_HTML)
  public Viewable handlePasswordResetForm(
      @Context UriInfo ui,
      @FormParam("email") String email,
      @FormParam("recaptcha_challenge_field") String challenge,
      @FormParam("recaptcha_response_field") String uresponse) {

    try {
      if (isBlank(email)) {
        errorMsg = "No email provided, try again...";
        return handleViewable("resetpw_email_form", this);
      }

      ReCaptchaImpl reCaptcha = new ReCaptchaImpl();
      reCaptcha.setPrivateKey(properties.getRecaptchaPrivate());

      ReCaptchaResponse reCaptchaResponse =
          reCaptcha.checkAnswer(httpServletRequest.getRemoteAddr(), challenge, uresponse);

      if (!useReCaptcha() || reCaptchaResponse.isValid()) {
        user = management.findAdminUser(email);
        if (user != null) {
          management.startAdminUserPasswordResetFlow(user);
          return handleViewable("resetpw_email_success", this);
        } else {
          errorMsg = "We don't recognize that email, try again...";
          return handleViewable("resetpw_email_form", this);
        }
      } else {
        errorMsg = "Incorrect Captcha, try again...";
        return handleViewable("resetpw_email_form", this);
      }
    } catch (RedirectionException e) {
      throw e;
    } catch (Exception e) {
      return handleViewable("error", e);
    }
  }
Beispiel #9
0
  public boolean checkAnswer(HttpServletRequest request) {
    log.debug("public boolean checkAnswer( HttpServletRequest request )");

    String remoteAddr = request.getRemoteAddr();
    String challenge = request.getParameter("recaptcha_challenge_field");
    String uresponse = request.getParameter("recaptcha_response_field");

    if (captcha != null) {
      reCaptchaResponse = captcha.checkAnswer(remoteAddr, challenge, uresponse);
      return reCaptchaResponse.isValid();
    }
    return true; // TODO: Thinks about not to return always true.
  }
  public void _jspService(HttpServletRequest request, HttpServletResponse response)
      throws java.io.IOException, ServletException {

    JspFactory _jspxFactory = null;
    PageContext pageContext = null;
    HttpSession session = null;
    ServletContext application = null;
    ServletConfig config = null;
    JspWriter out = null;
    Object page = this;
    JspWriter _jspx_out = null;
    PageContext _jspx_page_context = null;

    try {
      _jspxFactory = JspFactory.getDefaultFactory();
      response.setContentType("text/html");
      pageContext = _jspxFactory.getPageContext(this, request, response, null, true, 8192, true);
      _jspx_page_context = pageContext;
      application = pageContext.getServletContext();
      config = pageContext.getServletConfig();
      session = pageContext.getSession();
      out = pageContext.getOut();
      _jspx_out = out;

      out.write("\n\n\n\n\n\n\n<html>\n<head>\n    <title>");
      if (_jspx_meth_fmt_message_0(_jspx_page_context)) return;
      out.write(
          "</title>\n    <link rel=\"stylesheet\" type=\"text/css\" href=\"/style/global.css\">\n    <style type=\"text/css\">\n        .drop-shadow {\n             font-weight: bold;\n             font-size: 14pt;\n             color: white;\n             text-shadow: black 0.1em 0.1em 0.2em;\n             padding-top: 21px;}\n    </style>\n    <meta name=\"decorator\" content=\"none\"/>\n</head>\n\n");
      org.jivesoftware.util.WebManager webManager = null;
      synchronized (_jspx_page_context) {
        webManager =
            (org.jivesoftware.util.WebManager)
                _jspx_page_context.getAttribute("webManager", PageContext.PAGE_SCOPE);
        if (webManager == null) {
          webManager = new org.jivesoftware.util.WebManager();
          _jspx_page_context.setAttribute("webManager", webManager, PageContext.PAGE_SCOPE);
        }
      }
      out.write('\n');
      java.util.HashMap errors = null;
      synchronized (_jspx_page_context) {
        errors =
            (java.util.HashMap) _jspx_page_context.getAttribute("errors", PageContext.PAGE_SCOPE);
        if (errors == null) {
          errors = new java.util.HashMap();
          _jspx_page_context.setAttribute("errors", errors, PageContext.PAGE_SCOPE);
        }
      }
      out.write('\n');
      webManager.init(request, response, session, application, out);

      boolean create = request.getParameter("create") != null;
      String username = ParamUtils.getParameter(request, "username");
      String name = ParamUtils.getParameter(request, "name");
      String email = ParamUtils.getParameter(request, "email");
      String password = ParamUtils.getParameter(request, "password");
      String passwordConfirm = ParamUtils.getParameter(request, "passwordConfirm");
      String reCaptchaChallenge = ParamUtils.getParameter(request, "recaptcha_challenge_field");
      String reCaptchaResponse = ParamUtils.getParameter(request, "recaptcha_response_field");

      RegistrationPlugin plugin =
          (RegistrationPlugin)
              webManager.getXMPPServer().getPluginManager().getPlugin("registration");
      ReCaptcha reCaptcha = null;
      if (plugin.reCaptchaEnabled()) {
        reCaptcha =
            ReCaptchaFactory.newReCaptcha(
                plugin.getReCaptchaPublicKey(),
                plugin.getReCaptchaPrivateKey(),
                plugin.reCaptchaNoScript());
      }

      // Handle a request to create a user:
      if (create) {
        // Validate
        if (username == null) {
          errors.put("username", "");
        } else {
          try {
            username = username.trim().toLowerCase();
            username = JID.escapeNode(username);
            username = Stringprep.nodeprep(username);
          } catch (StringprepException se) {
            errors.put("username", "");
          }
        }
        if (password == null) {
          errors.put("password", "");
        }
        if (passwordConfirm == null) {
          errors.put("passwordConfirm", "");
        }
        if (password != null && passwordConfirm != null && !password.equals(passwordConfirm)) {
          errors.put("passwordMatch", "");
        }
        if (plugin.reCaptchaEnabled()) {
          ReCaptchaResponse captchaResponse = null;
          try {
            captchaResponse =
                reCaptcha.checkAnswer(
                    request.getRemoteAddr(), reCaptchaChallenge, reCaptchaResponse);
          } catch (Exception e) {
          }
          if (captchaResponse == null || !captchaResponse.isValid()) {
            errors.put("reCaptchaFail", "");
          }
        }

        // do a create if there were no errors
        if (errors.size() == 0) {
          try {
            webManager.getUserManager().createUser(username, password, name, email);

            response.sendRedirect("sign-up.jsp?success=true");
            return;
          } catch (UserAlreadyExistsException e) {
            errors.put("usernameAlreadyExists", "");
          } catch (Exception e) {
            errors.put("general", "");
            Log.error(e);
          }
        }
      }

      out.write(
          "\n\n<body>\n\n<div id=\"jive-header\">\n<table cellpadding=\"0\" cellspacing=\"0\" width=\"100%\" border=\"0\">\n    <tbody>\n        <tr><td class=\"drop-shadow\">&nbsp;");
      out.print(plugin.getHeader());
      out.write("</td></tr>    \n    </tbody>\n</table>\n</div>\n\n<div id=\"jive-content\">\n\n");
      if (!plugin.webEnabled()) {
        out.write('\n');
        out.write('\n');
        if (_jspx_meth_fmt_message_1(_jspx_page_context)) return;
        out.write('\n');
        out.write('\n');
      } else {
        out.write("\n\n<p>");
        if (_jspx_meth_fmt_message_2(_jspx_page_context)) return;
        out.write("</p>\n\n");
        if (_jspx_meth_c_set_0(_jspx_page_context)) return;
        out.write('\n');
        if (_jspx_meth_c_set_1(_jspx_page_context)) return;
        out.write('\n');
        out.write('\n');
        if (!errors.isEmpty()) {
          out.write(
              "\n\n    <div class=\"jive-error\">\n    <table cellpadding=\"0\" cellspacing=\"0\" border=\"0\">\n    <tbody>\n        <tr>\n            <td class=\"jive-icon\"><img src=\"images/error-16x16.gif\" width=\"16\" height=\"16\" border=\"0\"/></td>\n            <td class=\"jive-icon-label\">\n\n            ");
          if (errors.get("general") != null) {
            out.write("\n                ");
            if (_jspx_meth_fmt_message_3(_jspx_page_context)) return;
            out.write("\n            ");
          } else if (errors.get("username") != null) {
            out.write("\n                ");
            if (_jspx_meth_fmt_message_4(_jspx_page_context)) return;
            out.write("\n            ");
          } else if (errors.get("usernameAlreadyExists") != null) {
            out.write("\n                ");
            if (_jspx_meth_fmt_message_5(_jspx_page_context)) return;
            out.write("\n            ");
          } else if (errors.get("name") != null) {
            out.write("\n                ");
            if (_jspx_meth_fmt_message_6(_jspx_page_context)) return;
            out.write("\n            ");
          } else if (errors.get("email") != null) {
            out.write("\n                ");
            if (_jspx_meth_fmt_message_7(_jspx_page_context)) return;
            out.write("\n            ");
          } else if (errors.get("password") != null) {
            out.write("\n                ");
            if (_jspx_meth_fmt_message_8(_jspx_page_context)) return;
            out.write("\n            ");
          } else if (errors.get("passwordMatch") != null) {
            out.write("\n                ");
            if (_jspx_meth_fmt_message_9(_jspx_page_context)) return;
            out.write("\n            ");
          } else if (errors.get("passwordConfirm") != null) {
            out.write("\n                ");
            if (_jspx_meth_fmt_message_10(_jspx_page_context)) return;
            out.write("\n            ");
          } else if (errors.get("reCaptchaFail") != null) {
            out.write("\n                ");
            if (_jspx_meth_fmt_message_11(_jspx_page_context)) return;
            out.write("\n            ");
          }
          out.write(
              "\n            </td>\n        </tr>\n    </tbody>\n    </table>\n    </div>\n    <br>\n\n");
        } else if (request.getParameter("success") != null) {
          out.write(
              "\n\n    <div class=\"jive-success\">\n    <table cellpadding=\"0\" cellspacing=\"0\" border=\"0\">\n    <tbody>\n        <tr>\n            <td class=\"jive-icon\"><img src=\"images/success-16x16.gif\" width=\"16\" height=\"16\" border=\"0\"></td>\n            <td class=\"jive-icon-label\">");
          if (_jspx_meth_fmt_message_12(_jspx_page_context)) return;
          out.write("</td>\n        </tr>\n    </tbody>\n    </table>\n    </div><br>\n\n");
        }
        out.write(
            "\n\n<form name=\"f\" action=\"sign-up.jsp\" method=\"get\">\n\n<div class=\"jive-contentBoxHeader\">");
        if (_jspx_meth_fmt_message_13(_jspx_page_context)) return;
        out.write(
            "</div>\n<div class=\"jive-contentBox\">\n    <div>\n    <table cellpadding=\"3\" cellspacing=\"0\" border=\"0\" width=\"100%\">\n    <tbody>\n    <tr>\n        <td width=\"1%\" nowrap><label for=\"usernametf\">");
        if (_jspx_meth_fmt_message_14(_jspx_page_context)) return;
        out.write(
            ":</label> *</td>\n        <td width=\"99%\">\n            <input type=\"text\" name=\"username\" size=\"30\" maxlength=\"75\" value=\"");
        out.print(((username != null) ? username : ""));
        out.write(
            "\"\n             id=\"usernametf\" autocomplete=\"off\">\n        </td>\n    </tr>\n    <tr>\n        <td width=\"1%\" nowrap>\n            <label for=\"nametf\">");
        if (_jspx_meth_fmt_message_15(_jspx_page_context)) return;
        out.write(
            ":</label>\n        </td>\n        <td width=\"99%\">\n            <input type=\"text\" name=\"name\" size=\"30\" maxlength=\"75\" value=\"");
        out.print(((name != null) ? name : ""));
        out.write(
            "\"\n             id=\"nametf\">\n        </td>\n    </tr>\n    <tr>\n        <td width=\"1%\" nowrap>\n            <label for=\"emailtf\">");
        if (_jspx_meth_fmt_message_16(_jspx_page_context)) return;
        out.write(
            ":</label></td>\n        <td width=\"99%\">\n            <input type=\"text\" name=\"email\" size=\"30\" maxlength=\"75\" value=\"");
        out.print(((email != null) ? email : ""));
        out.write(
            "\"\n             id=\"emailtf\">\n        </td>\n    </tr>\n    <tr>\n        <td nowrap>\n            <label for=\"passtf\">");
        if (_jspx_meth_fmt_message_17(_jspx_page_context)) return;
        out.write(
            ":</label> *\n        </td>\n        <td width=\"99%\">\n            <input type=\"password\" name=\"password\" value=\"\" size=\"20\" maxlength=\"75\"\n             id=\"passtf\">\n        </td>\n    </tr>\n    <tr>\n        <td width=\"1%\" nowrap>\n            <label for=\"confpasstf\">");
        if (_jspx_meth_fmt_message_18(_jspx_page_context)) return;
        out.write(
            ":</label> *\n        </td>\n        <td width=\"99%\">\n            <input type=\"password\" name=\"passwordConfirm\" value=\"\" size=\"20\" maxlength=\"75\"\n             id=\"confpasstf\">\n        </td>\n    </tr>\n    </tbody>\n    </table>\n    <br>\n    <span class=\"jive-description\">\n    * ");
        if (_jspx_meth_fmt_message_19(_jspx_page_context)) return;
        out.write("\n    </span>\n    </div>\n</div>\n\n");
        if (reCaptcha != null) {
          out.write('\n');
          out.print(reCaptcha.createRecaptchaHtml(null, null, 0));
          out.write('\n');
        }
        out.write("\n<input type=\"submit\" name=\"create\" value=\"");
        if (_jspx_meth_fmt_message_20(_jspx_page_context)) return;
        out.write(
            "\">\n\n</form>\n\n<script language=\"JavaScript\" type=\"text/javascript\">\ndocument.f.username.focus();\n</script>\n\n");
      }
      out.write("\n\n</body>\n</html>");
    } catch (Throwable t) {
      if (!(t instanceof SkipPageException)) {
        out = _jspx_out;
        if (out != null && out.getBufferSize() != 0) out.clearBuffer();
        if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
      }
    } finally {
      if (_jspxFactory != null) _jspxFactory.releasePageContext(_jspx_page_context);
    }
  }
  @RequestMapping(value = "/register.html", method = RequestMethod.POST)
  public String registerCustomer(
      @Valid @ModelAttribute("customer") SecuredShopPersistableCustomer customer,
      BindingResult bindingResult,
      Model model,
      HttpServletRequest request,
      final Locale locale)
      throws Exception {
    MerchantStore merchantStore = (MerchantStore) request.getAttribute(Constants.MERCHANT_STORE);
    Language language = super.getLanguage(request);

    ReCaptchaImpl reCaptcha = new ReCaptchaImpl();
    reCaptcha.setPublicKey(coreConfiguration.getProperty(Constants.RECAPATCHA_PUBLIC_KEY));
    reCaptcha.setPrivateKey(coreConfiguration.getProperty(Constants.RECAPATCHA_PRIVATE_KEY));

    String userName = null;
    String password = null;

    model.addAttribute(
        "recapatcha_public_key", coreConfiguration.getProperty(Constants.RECAPATCHA_PUBLIC_KEY));

    if (StringUtils.isNotBlank(customer.getRecaptcha_challenge_field())
        && StringUtils.isNotBlank(customer.getRecaptcha_response_field())) {
      ReCaptchaResponse reCaptchaResponse =
          reCaptcha.checkAnswer(
              request.getRemoteAddr(),
              customer.getRecaptcha_challenge_field(),
              customer.getRecaptcha_response_field());
      if (!reCaptchaResponse.isValid()) {
        LOGGER.debug("Captcha response does not matched");
        FieldError error =
            new FieldError(
                "recaptcha_challenge_field",
                "recaptcha_challenge_field",
                messages.getMessage("validaion.recaptcha.not.matched", locale));
        bindingResult.addError(error);
      }
    }

    if (StringUtils.isNotBlank(customer.getUserName())) {
      if (customerFacade.checkIfUserExists(customer.getUserName(), merchantStore)) {
        LOGGER.debug(
            "Customer with username {} already exists for this store ", customer.getUserName());
        FieldError error =
            new FieldError(
                "userName",
                "userName",
                messages.getMessage("registration.username.already.exists", locale));
        bindingResult.addError(error);
      }
      userName = customer.getUserName();
    }

    if (StringUtils.isNotBlank(customer.getPassword())
        && StringUtils.isNotBlank(customer.getCheckPassword())) {
      if (!customer.getPassword().equals(customer.getCheckPassword())) {
        FieldError error =
            new FieldError(
                "password",
                "password",
                messages.getMessage("message.password.checkpassword.identical", locale));
        bindingResult.addError(error);
      }
      password = customer.getPassword();
    }

    if (bindingResult.hasErrors()) {
      LOGGER.debug(
          "found {} validation error while validating in customer registration ",
          bindingResult.getErrorCount());
      StringBuilder template =
          new StringBuilder()
              .append(ControllerConstants.Tiles.Customer.register)
              .append(".")
              .append(merchantStore.getStoreTemplate());
      return template.toString();
    }

    @SuppressWarnings("unused")
    CustomerEntity customerData = null;
    try {
      customerData = customerFacade.registerCustomer(customer, merchantStore, language);
    } catch (CustomerRegistrationException cre) {
      LOGGER.error("Error while registering customer.. ", cre);
      ObjectError error =
          new ObjectError("registration", messages.getMessage("registration.failed", locale));
      bindingResult.addError(error);
      StringBuilder template =
          new StringBuilder()
              .append(ControllerConstants.Tiles.Customer.register)
              .append(".")
              .append(merchantStore.getStoreTemplate());
      return template.toString();
    } catch (Exception e) {
      LOGGER.error("Error while registering customer.. ", e);
      ObjectError error =
          new ObjectError("registration", messages.getMessage("registration.failed", locale));
      bindingResult.addError(error);
      StringBuilder template =
          new StringBuilder()
              .append(ControllerConstants.Tiles.Customer.register)
              .append(".")
              .append(merchantStore.getStoreTemplate());
      return template.toString();
    }

    /** Send registration email */
    emailTemplatesUtils.sendRegistrationEmail(
        customer, merchantStore, locale, request.getContextPath());

    /** Login user */
    try {

      // refresh customer
      Customer c = customerFacade.getCustomerByUserName(customer.getUserName(), merchantStore);
      // authenticate
      customerFacade.authenticate(c, userName, password);
      super.setSessionAttribute(Constants.CUSTOMER, c, request);

      return "redirect:/shop/customer/dashboard.html";

    } catch (Exception e) {
      LOGGER.error("Cannot authenticate user ", e);
      ObjectError error =
          new ObjectError("registration", messages.getMessage("registration.failed", locale));
      bindingResult.addError(error);
    }

    StringBuilder template =
        new StringBuilder()
            .append(ControllerConstants.Tiles.Customer.register)
            .append(".")
            .append(merchantStore.getStoreTemplate());
    return template.toString();
  }
  @RequestMapping(
      value = {"/shop/store/{storeCode}/contact"},
      method = RequestMethod.POST)
  public @ResponseBody String sendEmail(
      @ModelAttribute(value = "contact") ContactForm contact,
      BindingResult bindingResult,
      HttpServletRequest request,
      HttpServletResponse response,
      Locale locale)
      throws Exception {

    AjaxResponse ajaxResponse = new AjaxResponse();

    MerchantStore store = (MerchantStore) request.getAttribute(Constants.MERCHANT_STORE);

    try {

      if (StringUtils.isBlank(contact.getCaptchaResponseField())) {
        FieldError error =
            new FieldError(
                "captchaResponseField",
                "captchaResponseField",
                messages.getMessage("NotEmpty.contact.captchaResponseField", locale));
        bindingResult.addError(error);
        ajaxResponse.setErrorString(bindingResult.getAllErrors().get(0).getDefaultMessage());
        ajaxResponse.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE);
        return ajaxResponse.toJSONString();
      }

      ReCaptchaImpl reCaptcha = new ReCaptchaImpl();
      reCaptcha.setPublicKey(coreConfiguration.getProperty(Constants.RECAPATCHA_PUBLIC_KEY));
      reCaptcha.setPrivateKey(coreConfiguration.getProperty(Constants.RECAPATCHA_PRIVATE_KEY));

      if (StringUtils.isNotBlank(contact.getCaptchaChallengeField())
          && StringUtils.isNotBlank(contact.getCaptchaResponseField())) {
        ReCaptchaResponse reCaptchaResponse =
            reCaptcha.checkAnswer(
                request.getRemoteAddr(),
                contact.getCaptchaChallengeField(),
                contact.getCaptchaResponseField());
        if (!reCaptchaResponse.isValid()) {
          LOGGER.debug("Captcha response does not matched");
          FieldError error =
              new FieldError(
                  "captchaChallengeField",
                  "captchaChallengeField",
                  messages.getMessage("validaion.recaptcha.not.matched", locale));
          bindingResult.addError(error);
        }
      }

      if (bindingResult.hasErrors()) {
        LOGGER.debug(
            "found {} validation error while validating in customer registration ",
            bindingResult.getErrorCount());
        ajaxResponse.setErrorString(bindingResult.getAllErrors().get(0).getDefaultMessage());
        ajaxResponse.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE);
        return ajaxResponse.toJSONString();
      }

      emailTemplatesUtils.sendContactEmail(
          contact,
          store,
          LocaleUtils.getLocale(store.getDefaultLanguage()),
          request.getContextPath());

      ajaxResponse.setStatus(AjaxResponse.RESPONSE_STATUS_SUCCESS);
    } catch (Exception e) {
      LOGGER.error("An error occured while trying to send an email", e);
      ajaxResponse.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE);
    }

    return ajaxResponse.toJSONString();
  }
Beispiel #13
0
 public String getErrorMessage() {
   return reCaptchaResponse.getErrorMessage();
 }
  @RequestMapping(value = CONTROLLER_MAPPING + "submit", method = RequestMethod.POST)
  public ModelAndView formSubmission(
      HttpServletRequest request,
      String confirmationUrl,
      String usersEmail,
      String name,
      String fromEmail,
      String toEmail,
      String userMsg) {
    ModelAndView modelAndView = new ModelAndView(confirmationUrl);

    if (log.isDebugEnabled()) log.debug("Contact form submitted");

    if ((StringUtils.isBlank(confirmationUrl))
        || (StringUtils.isBlank(fromEmail))
        || (StringUtils.isBlank(toEmail))) {
      log.error(
          String.format(
              "Contact form not configured properly, confirmationUrl: %s, fromEmail: %s, toEmail: %s",
              confirmationUrl, fromEmail, toEmail));
      modelAndView =
          new ModelAndView("system-error", "errorMsg", "This page has not been configure");

      ContactUsResponse contactUsResponse = contactUsResponseService.findContactUsResponse();
      if (contactUsResponse != null) {
        modelAndView.addObject("fromEmail", contactUsResponse.getFromEmailAddress());
        modelAndView.addObject("toEmail", contactUsResponse.getToEmailAddresses());
      } else {
        modelAndView =
            new ModelAndView("system-error", "errorMsg", "This page has not been configure");
      }
    } else if ((StringUtils.isBlank(usersEmail))
        || (StringUtils.isBlank(name))
        || (StringUtils.isBlank(userMsg))) {
      log.warn(
          String.format(
              "Contact form was not submitted properly, usersEmail: %s, name: %s, userMsg: %s",
              usersEmail, name, userMsg));
      modelAndView =
          new ModelAndView(
              "contact/form", "errorMsg", "You must provide entries for all required fields");

      ContactUsResponse contactUsResponse = contactUsResponseService.findContactUsResponse();
      if (contactUsResponse != null) {
        modelAndView.addObject("fromEmail", contactUsResponse.getFromEmailAddress());
        modelAndView.addObject("toEmail", contactUsResponse.getToEmailAddresses());
        modelAndView.addObject("name", name);
        modelAndView.addObject("userMsg", userMsg);
        modelAndView.addObject("usersEmail", usersEmail);
      } else {
        modelAndView =
            new ModelAndView("system-error", "errorMsg", "This page has not been configure");
      }
    } else if (!EmailUtil.isValidEmailAddress(usersEmail)) {
      modelAndView =
          new ModelAndView("contact/form", "errorMsg", "You must provide a valid email address");

      ContactUsResponse contactUsResponse = contactUsResponseService.findContactUsResponse();
      if (contactUsResponse != null) {
        modelAndView.addObject("fromEmail", contactUsResponse.getFromEmailAddress());
        modelAndView.addObject("toEmail", contactUsResponse.getToEmailAddresses());
        modelAndView.addObject("name", name);
        modelAndView.addObject("userMsg", userMsg);
        modelAndView.addObject("usersEmail", usersEmail);
      } else {
        modelAndView =
            new ModelAndView("system-error", "errorMsg", "This page has not been configure");
      }
    } else {
      String challenge = (String) request.getParameter("recaptcha_challenge_field");
      String response = (String) request.getParameter("recaptcha_response_field");
      String remoteAddr = request.getRemoteAddr();

      ReCaptchaImpl reCaptcha = new ReCaptchaImpl();

      reCaptcha.setPrivateKey("6Lco2cUSAAAAAO3-55M3iPPOfr3FIe_4n5XYsFBW");

      ReCaptchaResponse reCaptchaResponse = reCaptcha.checkAnswer(remoteAddr, challenge, response);

      if (reCaptchaResponse.isValid()) {
        log.debug(
            String.format(
                "Contact form submitted properly, confirmationUrl: %s, fromEmail: %s, toEmail: %s, name: %s, usersEmail: %s, userMsg: %s",
                confirmationUrl, fromEmail, toEmail, name, usersEmail, userMsg));

        if (!EmailUtil.send(
            fromEmail,
            toEmail,
            name,
            "Website Contact Request from " + name + " (" + usersEmail + ")",
            userMsg)) {
          log.error(String.format("An error occurred sending the email", ""));
          modelAndView =
              new ModelAndView(
                  "contact/form",
                  "errorMsg",
                  "An error occurred sending your request, please try again later.");
        }
      } else {
        ContactUsResponse contactUsResponse = contactUsResponseService.findContactUsResponse();
        if (contactUsResponse != null) {
          modelAndView = new ModelAndView("contact/form", "errorMsg", "Invalid captcha");

          modelAndView.addObject("fromEmail", contactUsResponse.getFromEmailAddress());
          modelAndView.addObject("toEmail", contactUsResponse.getToEmailAddresses());
          modelAndView.addObject("name", name);
          modelAndView.addObject("userMsg", userMsg);
          modelAndView.addObject("usersEmail", usersEmail);
        } else {
          modelAndView =
              new ModelAndView("system-error", "errorMsg", "This page has not been configure");
        }
      }
    }

    log.debug("Finishing off by loading navigation");

    loadConfig(modelAndView);
    loadNavigation(modelAndView);
    modelAndView.addObject("currentUser", siteUserService.getCurrentUser());

    return modelAndView;
  }