Ejemplo n.º 1
0
  // password reset functionality  ---  Sajid Shajahan
  @RequestMapping(
      value = "/admin/users/resetPassword.html",
      method = RequestMethod.POST,
      produces = "application/json")
  public @ResponseBody String resetPassword(
      HttpServletRequest request, HttpServletResponse response, Locale locale) {

    AjaxResponse resp = new AjaxResponse();
    String userName = request.getParameter("username");

    /**
     * Get User with userService.getByUserName Get 3 security questions from User.getQuestion1,
     * user.getQuestion2, user.getQuestion3
     */
    HttpSession session = request.getSession();
    session.setAttribute("username_reset", userName);

    try {
      if (!StringUtils.isBlank(userName)) {

        User dbUser = userService.getByUserName(userName);

        if (dbUser == null) {
          resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE);
          resp.setStatusMessage(messages.getMessage("message.username.notfound", locale));
          return resp.toJSONString();
        }

        Map<String, String> entry = new HashMap<String, String>();
        entry.put(QUESTION_1, dbUser.getQuestion1());
        entry.put(QUESTION_2, dbUser.getQuestion2());
        entry.put(QUESTION_3, dbUser.getQuestion3());
        resp.addDataEntry(entry);
        resp.setStatus(AjaxResponse.RESPONSE_OPERATION_COMPLETED);

      } else {
        resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE);
        resp.setStatusMessage(messages.getMessage("User.resetPassword.Error", locale));
      }
    } catch (Exception e) {
      e.printStackTrace();
      resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE);
      resp.setStatusMessage(messages.getMessage("User.resetPassword.Error", locale));
      return resp.toJSONString();
    }

    String returnString = resp.toJSONString();
    return returnString;
  }
Ejemplo n.º 2
0
  // password reset functionality  ---  Sajid Shajahan
  @RequestMapping(
      value = "/admin/users/resetPasswordSecurityQtn.html",
      method = RequestMethod.POST,
      produces = "application/json")
  public @ResponseBody String resetPasswordSecurityQtn(
      @ModelAttribute(value = "userReset") UserReset userReset,
      HttpServletRequest request,
      HttpServletResponse response,
      Locale locale) {

    MerchantStore store = (MerchantStore) request.getAttribute(Constants.ADMIN_STORE);
    Language userLanguage = null;
    Locale userLocale = null;
    AjaxResponse resp = new AjaxResponse();

    // String question1 = request.getParameter("question1");
    // String question2 = request.getParameter("question2");
    // String question3 = request.getParameter("question3");

    String answer1 = request.getParameter("answer1");
    String answer2 = request.getParameter("answer2");
    String answer3 = request.getParameter("answer3");

    try {

      HttpSession session = request.getSession();
      User dbUser = userService.getByUserName((String) session.getAttribute("username_reset"));

      if (dbUser != null) {

        if (dbUser.getAnswer1().equals(answer1.trim())
            && dbUser.getAnswer2().equals(answer2.trim())
            && dbUser.getAnswer3().equals(answer3.trim())) {
          userLanguage = dbUser.getDefaultLanguage();
          userLocale = LocaleUtils.getLocale(userLanguage);

          String tempPass = userReset.generateRandomString();
          String pass = passwordEncoder.encodePassword(tempPass, null);

          dbUser.setAdminPassword(pass);
          userService.update(dbUser);

          // send email

          try {
            String[] storeEmail = {store.getStoreEmailAddress()};

            Map<String, String> templateTokens =
                EmailUtils.createEmailObjectsMap(
                    request.getContextPath(), store, messages, userLocale);
            templateTokens.put(
                EmailConstants.EMAIL_RESET_PASSWORD_TXT,
                messages.getMessage("email.user.resetpassword.text", userLocale));
            templateTokens.put(
                EmailConstants.EMAIL_CONTACT_OWNER,
                messages.getMessage("email.contactowner", storeEmail, userLocale));
            templateTokens.put(
                EmailConstants.EMAIL_PASSWORD_LABEL,
                messages.getMessage("label.generic.password", userLocale));
            templateTokens.put(EmailConstants.EMAIL_USER_PASSWORD, tempPass);

            Email email = new Email();
            email.setFrom(store.getStorename());
            email.setFromEmail(store.getStoreEmailAddress());
            email.setSubject(messages.getMessage("label.generic.changepassword", userLocale));
            email.setTo(dbUser.getAdminEmail());
            email.setTemplateName(RESET_PASSWORD_TPL);
            email.setTemplateTokens(templateTokens);

            emailService.sendHtmlEmail(store, email);

          } catch (Exception e) {
            LOGGER.error("Cannot send email to user", e);
          }

          resp.setStatus(AjaxResponse.RESPONSE_OPERATION_COMPLETED);
          resp.setStatusMessage(messages.getMessage("User.resetPassword.resetSuccess", locale));
        } else {
          resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE);
          resp.setStatusMessage(messages.getMessage("User.resetPassword.wrongSecurityQtn", locale));
        }
      } else {
        resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE);
        resp.setStatusMessage(messages.getMessage("User.resetPassword.userNotFound", locale));
      }

    } catch (ServiceException e) {
      e.printStackTrace();
      resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE);
      resp.setStatusMessage(messages.getMessage("User.resetPassword.Error", locale));
    }

    String returnString = resp.toJSONString();
    return returnString;
  }
Ejemplo n.º 3
0
  @PreAuthorize("hasRole('AUTH')")
  @RequestMapping(
      value = "/admin/users/remove.html",
      method = RequestMethod.POST,
      produces = "application/json")
  public @ResponseBody String removeUser(HttpServletRequest request, Locale locale)
      throws Exception {

    // do not remove super admin

    String sUserId = request.getParameter("userId");

    AjaxResponse resp = new AjaxResponse();

    String userName = request.getRemoteUser();
    User remoteUser = userService.getByUserName(userName);

    try {

      Long userId = Long.parseLong(sUserId);
      User user = userService.getById(userId);

      /** In order to remove a User the logged in ser must be STORE_ADMIN or SUPER_USER */
      if (user == null) {
        resp.setStatusMessage(messages.getMessage("message.unauthorized", locale));
        resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE);
        return resp.toJSONString();
      }

      if (!request.isUserInRole(Constants.GROUP_ADMIN)) {
        resp.setStatusMessage(messages.getMessage("message.unauthorized", locale));
        resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE);
        return resp.toJSONString();
      }

      // check if the user removed has group ADMIN
      boolean isAdmin = false;
      if (UserUtils.userInGroup(remoteUser, Constants.GROUP_ADMIN)
          || UserUtils.userInGroup(remoteUser, Constants.GROUP_SUPERADMIN)) {
        isAdmin = true;
      }

      if (!isAdmin) {
        resp.setStatusMessage(
            messages.getMessage("message.security.caanotremovesuperadmin", locale));
        resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE);
        return resp.toJSONString();
      }

      userService.delete(user);

      resp.setStatus(AjaxResponse.RESPONSE_OPERATION_COMPLETED);

    } catch (Exception e) {
      LOGGER.error("Error while deleting product price", e);
      resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE);
      resp.setErrorMessage(e);
    }

    String returnString = resp.toJSONString();

    return returnString;
  }
Ejemplo n.º 4
0
  @PreAuthorize("hasRole('AUTH')")
  @RequestMapping(value = "/admin/users/save.html", method = RequestMethod.POST)
  public String saveUser(
      @Valid @ModelAttribute("user") User user,
      BindingResult result,
      Model model,
      HttpServletRequest request,
      Locale locale)
      throws Exception {

    setMenu(model, request);

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

    this.populateUserObjects(user, store, model, locale);

    Language language = user.getDefaultLanguage();

    Language l = languageService.getById(language.getId());

    user.setDefaultLanguage(l);

    Locale userLocale = LocaleUtils.getLocale(l);

    User dbUser = null;

    // edit mode, need to get original user important information
    if (user.getId() != null) {
      dbUser = userService.getByUserName(user.getAdminName());
      if (dbUser == null) {
        return "redirect://admin/users/displayUser.html";
      }
    }

    List<Group> submitedGroups = user.getGroups();
    Set<Integer> ids = new HashSet<Integer>();
    for (Group group : submitedGroups) {
      ids.add(Integer.parseInt(group.getGroupName()));
    }

    // validate security questions not empty
    if (StringUtils.isBlank(user.getAnswer1())) {
      ObjectError error =
          new ObjectError(
              "answer1", messages.getMessage("security.answer.question1.message", locale));
      result.addError(error);
    }

    if (StringUtils.isBlank(user.getAnswer2())) {
      ObjectError error =
          new ObjectError(
              "answer2", messages.getMessage("security.answer.question2.message", locale));
      result.addError(error);
    }

    if (StringUtils.isBlank(user.getAnswer3())) {
      ObjectError error =
          new ObjectError(
              "answer3", messages.getMessage("security.answer.question3.message", locale));
      result.addError(error);
    }

    if (user.getQuestion1().equals(user.getQuestion2())
        || user.getQuestion1().equals(user.getQuestion3())
        || user.getQuestion2().equals(user.getQuestion1())
        || user.getQuestion1().equals(user.getQuestion3())
        || user.getQuestion3().equals(user.getQuestion1())
        || user.getQuestion1().equals(user.getQuestion2())) {

      ObjectError error =
          new ObjectError(
              "question1", messages.getMessage("security.questions.differentmessages", locale));
      result.addError(error);
    }

    Group superAdmin = null;

    if (user.getId() != null && user.getId() > 0) {
      if (user.getId().longValue() != dbUser.getId().longValue()) {
        return "redirect://admin/users/displayUser.html";
      }

      List<Group> groups = dbUser.getGroups();
      // boolean removeSuperAdmin = true;
      for (Group group : groups) {
        // can't revoke super admin
        if (group.getGroupName().equals("SUPERADMIN")) {
          superAdmin = group;
        }
      }

    } else {

      if (user.getAdminPassword().length() < 6) {
        ObjectError error =
            new ObjectError(
                "adminPassword", messages.getMessage("message.password.length", locale));
        result.addError(error);
      }
    }

    if (superAdmin != null) {
      ids.add(superAdmin.getId());
    }

    List<Group> newGroups = groupService.listGroupByIds(ids);

    // set actual user groups
    user.setGroups(newGroups);

    if (result.hasErrors()) {
      return ControllerConstants.Tiles.User.profile;
    }

    String decodedPassword = user.getAdminPassword();
    if (user.getId() != null && user.getId() > 0) {
      user.setAdminPassword(dbUser.getAdminPassword());
    } else {
      String encoded = passwordEncoder.encodePassword(user.getAdminPassword(), null);
      user.setAdminPassword(encoded);
    }

    if (user.getId() == null || user.getId().longValue() == 0) {

      // save or update user
      userService.saveOrUpdate(user);

      try {

        // creation of a user, send an email
        String userName = user.getFirstName();
        if (StringUtils.isBlank(userName)) {
          userName = user.getAdminName();
        }
        String[] userNameArg = {userName};

        Map<String, String> templateTokens =
            EmailUtils.createEmailObjectsMap(request.getContextPath(), store, messages, userLocale);
        templateTokens.put(
            EmailConstants.EMAIL_NEW_USER_TEXT,
            messages.getMessage("email.greeting", userNameArg, userLocale));
        templateTokens.put(EmailConstants.EMAIL_USER_FIRSTNAME, user.getFirstName());
        templateTokens.put(EmailConstants.EMAIL_USER_LASTNAME, user.getLastName());
        templateTokens.put(
            EmailConstants.EMAIL_ADMIN_USERNAME_LABEL,
            messages.getMessage("label.generic.username", userLocale));
        templateTokens.put(EmailConstants.EMAIL_ADMIN_NAME, user.getAdminName());
        templateTokens.put(
            EmailConstants.EMAIL_TEXT_NEW_USER_CREATED,
            messages.getMessage("email.newuser.text", userLocale));
        templateTokens.put(
            EmailConstants.EMAIL_ADMIN_PASSWORD_LABEL,
            messages.getMessage("label.generic.password", userLocale));
        templateTokens.put(EmailConstants.EMAIL_ADMIN_PASSWORD, decodedPassword);
        templateTokens.put(
            EmailConstants.EMAIL_ADMIN_URL_LABEL,
            messages.getMessage("label.adminurl", userLocale));
        templateTokens.put(
            EmailConstants.EMAIL_ADMIN_URL, FilePathUtils.buildAdminUri(store, request));

        Email email = new Email();
        email.setFrom(store.getStorename());
        email.setFromEmail(store.getStoreEmailAddress());
        email.setSubject(messages.getMessage("email.newuser.title", userLocale));
        email.setTo(user.getAdminEmail());
        email.setTemplateName(NEW_USER_TMPL);
        email.setTemplateTokens(templateTokens);

        emailService.sendHtmlEmail(store, email);

      } catch (Exception e) {
        LOGGER.error("Cannot send email to user", e);
      }

    } else {
      // save or update user
      userService.saveOrUpdate(user);
    }

    model.addAttribute("success", "success");
    return ControllerConstants.Tiles.User.profile;
  }
Ejemplo n.º 5
0
  private void populateUserObjects(User user, MerchantStore store, Model model, Locale locale)
      throws Exception {

    // get groups
    List<Group> groups = new ArrayList<Group>();
    List<Group> userGroups = groupService.listGroup(GroupType.ADMIN);
    for (Group group : userGroups) {
      if (!group.getGroupName().equals(Constants.GROUP_SUPERADMIN)) {
        groups.add(group);
      }
    }

    List<MerchantStore> stores = new ArrayList<MerchantStore>();
    // stores.add(store);
    stores = merchantStoreService.list();

    // String remoteUser = request.getRemoteUser();

    /*		if(user!=null && user.getId()!=null) {
    	User logedInUser = userService.getByUserName(user.getAdminName());

    	//check groups
    	List<Group> logedInUserGroups = logedInUser.getGroups();
    	for(Group group : logedInUserGroups) {
    		if(group.getGroupName().equals(Constants.GROUP_SUPERADMIN)) {
    			stores = merchantStoreService.list();
    		}
    	}
    }*/

    // questions
    List<SecurityQuestion> questions = new ArrayList<SecurityQuestion>();

    SecurityQuestion question = new SecurityQuestion();
    question.setId("1");
    question.setLabel(messages.getMessage("security.question.1", locale));
    questions.add(question);

    question = new SecurityQuestion();
    question.setId("2");
    question.setLabel(messages.getMessage("security.question.2", locale));
    questions.add(question);

    question = new SecurityQuestion();
    question.setId("3");
    question.setLabel(messages.getMessage("security.question.3", locale));
    questions.add(question);

    question = new SecurityQuestion();
    question.setId("4");
    question.setLabel(messages.getMessage("security.question.4", locale));
    questions.add(question);

    question = new SecurityQuestion();
    question.setId("5");
    question.setLabel(messages.getMessage("security.question.5", locale));
    questions.add(question);

    question = new SecurityQuestion();
    question.setId("6");
    question.setLabel(messages.getMessage("security.question.6", locale));
    questions.add(question);

    question = new SecurityQuestion();
    question.setId("7");
    question.setLabel(messages.getMessage("security.question.7", locale));
    questions.add(question);

    question = new SecurityQuestion();
    question.setId("8");
    question.setLabel(messages.getMessage("security.question.8", locale));
    questions.add(question);

    question = new SecurityQuestion();
    question.setId("9");
    question.setLabel(messages.getMessage("security.question.9", locale));
    questions.add(question);

    model.addAttribute("questions", questions);
    model.addAttribute("stores", stores);
    model.addAttribute("languages", store.getLanguages());
    model.addAttribute("groups", groups);
  }
Ejemplo n.º 6
0
  @PreAuthorize("hasRole('AUTH')")
  @RequestMapping(value = "/admin/users/savePassword.html", method = RequestMethod.POST)
  public String changePassword(
      @ModelAttribute("password") Password password,
      BindingResult result,
      Model model,
      HttpServletRequest request,
      HttpServletResponse response,
      Locale locale)
      throws Exception {
    setMenu(model, request);
    String userName = request.getRemoteUser();
    User dbUser = userService.getByUserName(userName);

    if (password.getUser().getId().longValue() != dbUser.getId().longValue()) {
      return "redirect:/admin/users/displayUser.html";
    }

    // validate password not empty
    if (StringUtils.isBlank(password.getPassword())) {
      ObjectError error =
          new ObjectError(
              "password",
              new StringBuilder()
                  .append(messages.getMessage("label.generic.password", locale))
                  .append(" ")
                  .append(messages.getMessage("message.cannot.empty", locale))
                  .toString());
      result.addError(error);
      return ControllerConstants.Tiles.User.password;
    }

    String tempPass = passwordEncoder.encodePassword(password.getPassword(), null);

    // password match
    if (!tempPass.equals(dbUser.getAdminPassword())) {
      ObjectError error =
          new ObjectError("password", messages.getMessage("message.password.invalid", locale));
      result.addError(error);
      return ControllerConstants.Tiles.User.password;
    }

    if (StringUtils.isBlank(password.getNewPassword())) {
      ObjectError error =
          new ObjectError(
              "newPassword",
              new StringBuilder()
                  .append(messages.getMessage("label.generic.newpassword", locale))
                  .append(" ")
                  .append(messages.getMessage("message.cannot.empty", locale))
                  .toString());
      result.addError(error);
    }

    if (StringUtils.isBlank(password.getRepeatPassword())) {
      ObjectError error =
          new ObjectError(
              "newPasswordAgain",
              new StringBuilder()
                  .append(messages.getMessage("label.generic.newpassword.repeat", locale))
                  .append(" ")
                  .append(messages.getMessage("message.cannot.empty", locale))
                  .toString());
      result.addError(error);
    }

    if (!password.getRepeatPassword().equals(password.getNewPassword())) {
      ObjectError error =
          new ObjectError(
              "newPasswordAgain", messages.getMessage("message.password.different", locale));
      result.addError(error);
    }

    if (password.getNewPassword().length() < 6) {
      ObjectError error =
          new ObjectError("newPassword", messages.getMessage("message.password.length", locale));
      result.addError(error);
    }

    if (result.hasErrors()) {
      return ControllerConstants.Tiles.User.password;
    }

    String pass = passwordEncoder.encodePassword(password.getNewPassword(), null);
    dbUser.setAdminPassword(pass);
    userService.update(dbUser);

    model.addAttribute("success", "success");
    return ControllerConstants.Tiles.User.password;
  }
Ejemplo n.º 7
0
  @PreAuthorize("hasRole('CUSTOMER')")
  @RequestMapping(
      value = "/admin/customers/resetPassword.html",
      method = RequestMethod.POST,
      produces = "application/json")
  public @ResponseBody String resetPassword(
      HttpServletRequest request, HttpServletResponse response) {

    String customerId = request.getParameter("customerId");

    MerchantStore store = (MerchantStore) request.getAttribute(Constants.ADMIN_STORE);
    AjaxResponse resp = new AjaxResponse();

    try {

      Long id = Long.parseLong(customerId);

      Customer customer = customerService.getById(id);

      if (customer == null) {
        resp.setErrorString("Customer does not exist");
        resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE);
        return resp.toJSONString();
      }

      if (customer.getMerchantStore().getId().intValue() != store.getId().intValue()) {
        resp.setErrorString("Invalid customer id");
        resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE);
        return resp.toJSONString();
      }

      Language userLanguage = customer.getDefaultLanguage();

      Locale customerLocale = LocaleUtils.getLocale(userLanguage);

      String password = UserReset.generateRandomString();
      String encodedPassword = passwordEncoder.encodePassword(password, null);

      customer.setPassword(encodedPassword);

      customerService.saveOrUpdate(customer);

      // send email

      try {

        // creation of a user, send an email
        String[] storeEmail = {store.getStoreEmailAddress()};

        Map<String, String> templateTokens =
            EmailUtils.createEmailObjectsMap(
                request.getContextPath(), store, messages, customerLocale);
        templateTokens.put(
            EmailConstants.LABEL_HI, messages.getMessage("label.generic.hi", customerLocale));
        templateTokens.put(
            EmailConstants.EMAIL_CUSTOMER_FIRSTNAME, customer.getBilling().getFirstName());
        templateTokens.put(
            EmailConstants.EMAIL_CUSTOMER_LASTNAME, customer.getBilling().getLastName());
        templateTokens.put(
            EmailConstants.EMAIL_RESET_PASSWORD_TXT,
            messages.getMessage("email.customer.resetpassword.text", customerLocale));
        templateTokens.put(
            EmailConstants.EMAIL_CONTACT_OWNER,
            messages.getMessage("email.contactowner", storeEmail, customerLocale));
        templateTokens.put(
            EmailConstants.EMAIL_PASSWORD_LABEL,
            messages.getMessage("label.generic.password", customerLocale));
        templateTokens.put(EmailConstants.EMAIL_CUSTOMER_PASSWORD, password);

        Email email = new Email();
        email.setFrom(store.getStorename());
        email.setFromEmail(store.getStoreEmailAddress());
        email.setSubject(messages.getMessage("label.generic.changepassword", customerLocale));
        email.setTo(customer.getEmailAddress());
        email.setTemplateName(RESET_PASSWORD_TPL);
        email.setTemplateTokens(templateTokens);

        emailService.sendHtmlEmail(store, email);
        resp.setStatus(AjaxResponse.RESPONSE_STATUS_SUCCESS);

      } catch (Exception e) {
        LOGGER.error("Cannot send email to user", e);
        resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE);
      }

    } catch (Exception e) {
      LOGGER.error("An exception occured while changing password", e);
      resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE);
    }

    return resp.toJSONString();
  }
Ejemplo n.º 8
0
  @PreAuthorize("hasRole('CUSTOMER')")
  @RequestMapping(value = "/admin/customers/save.html", method = RequestMethod.POST)
  public String saveCustomer(
      @Valid @ModelAttribute("customer") Customer customer,
      BindingResult result,
      Model model,
      HttpServletRequest request,
      Locale locale)
      throws Exception {

    this.setMenu(model, request);

    String email_regEx = "\\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}\\b";
    Pattern pattern = Pattern.compile(email_regEx);

    Language language = (Language) request.getAttribute("LANGUAGE");
    MerchantStore store = (MerchantStore) request.getAttribute(Constants.ADMIN_STORE);
    List<Language> languages = languageService.getLanguages();

    model.addAttribute("languages", languages);

    this.getCustomerOptions(model, customer, store, language);

    // get countries
    List<Country> countries = countryService.getCountries(language);

    if (!StringUtils.isBlank(customer.getEmailAddress())) {
      java.util.regex.Matcher matcher = pattern.matcher(customer.getEmailAddress());

      if (!matcher.find()) {
        ObjectError error =
            new ObjectError(
                "customerEmailAddress", messages.getMessage("Email.customer.EmailAddress", locale));
        result.addError(error);
      }
    } else {
      ObjectError error =
          new ObjectError(
              "customerEmailAddress",
              messages.getMessage("NotEmpty.customer.EmailAddress", locale));
      result.addError(error);
    }

    if (StringUtils.isBlank(customer.getBilling().getFirstName())) {
      ObjectError error =
          new ObjectError(
              "billingFirstName",
              messages.getMessage("NotEmpty.customer.billingFirstName", locale));
      result.addError(error);
    }

    if (StringUtils.isBlank(customer.getBilling().getLastName())) {
      ObjectError error =
          new ObjectError(
              "billingLastName", messages.getMessage("NotEmpty.customer.billingLastName", locale));
      result.addError(error);
    }

    if (StringUtils.isBlank(customer.getBilling().getAddress())) {
      ObjectError error =
          new ObjectError(
              "billingAddress",
              messages.getMessage("NotEmpty.customer.billingStreetAddress", locale));
      result.addError(error);
    }

    if (StringUtils.isBlank(customer.getBilling().getCity())) {
      ObjectError error =
          new ObjectError(
              "billingCity", messages.getMessage("NotEmpty.customer.billingCity", locale));
      result.addError(error);
    }

    if (customer.getShowBillingStateList().equalsIgnoreCase("yes")
        && customer.getBilling().getZone().getCode() == null) {
      ObjectError error =
          new ObjectError(
              "billingState", messages.getMessage("NotEmpty.customer.billingState", locale));
      result.addError(error);

    } else if (customer.getShowBillingStateList().equalsIgnoreCase("no")
        && customer.getBilling().getState() == null) {
      ObjectError error =
          new ObjectError(
              "billingState", messages.getMessage("NotEmpty.customer.billingState", locale));
      result.addError(error);
    }

    if (StringUtils.isBlank(customer.getBilling().getPostalCode())) {
      ObjectError error =
          new ObjectError(
              "billingPostalCode",
              messages.getMessage("NotEmpty.customer.billingPostCode", locale));
      result.addError(error);
    }

    // check if error from the @valid
    if (result.hasErrors()) {
      model.addAttribute("countries", countries);
      return "admin-customer";
    }

    Customer newCustomer = new Customer();

    if (customer.getId() != null && customer.getId().longValue() > 0) {
      newCustomer = customerService.getById(customer.getId());

      if (newCustomer == null) {
        return "redirect:/admin/customers/list.html";
      }

      if (newCustomer.getMerchantStore().getId().intValue() != store.getId().intValue()) {
        return "redirect:/admin/customers/list.html";
      }

    } else {
      //  new customer set marchant_Id
      MerchantStore merchantStore = (MerchantStore) request.getAttribute(Constants.ADMIN_STORE);
      newCustomer.setMerchantStore(merchantStore);
    }

    newCustomer.setEmailAddress(customer.getEmailAddress());

    // get Customer country/zone
    Country deliveryCountry =
        countryService.getByCode(customer.getDelivery().getCountry().getIsoCode());
    Country billingCountry =
        countryService.getByCode(customer.getBilling().getCountry().getIsoCode());

    Zone deliveryZone = customer.getDelivery().getZone();
    Zone billingZone = customer.getBilling().getZone();

    if (customer.getShowDeliveryStateList().equalsIgnoreCase("yes")) {
      deliveryZone = zoneService.getByCode(customer.getDelivery().getZone().getCode());
      customer.getDelivery().setState(null);

    } else if (customer.getShowDeliveryStateList().equalsIgnoreCase("no")) {
      deliveryZone = null;
      customer.getDelivery().setState(customer.getDelivery().getState());
    }

    if (customer.getShowBillingStateList().equalsIgnoreCase("yes")) {
      billingZone = zoneService.getByCode(customer.getBilling().getZone().getCode());
      customer.getBilling().setState(null);

    } else if (customer.getShowBillingStateList().equalsIgnoreCase("no")) {
      billingZone = null;
      customer.getBilling().setState(customer.getBilling().getState());
    }

    newCustomer.setDefaultLanguage(customer.getDefaultLanguage());

    customer.getDelivery().setZone(deliveryZone);
    customer.getDelivery().setCountry(deliveryCountry);
    newCustomer.setDelivery(customer.getDelivery());

    customer.getBilling().setZone(billingZone);
    customer.getBilling().setCountry(billingCountry);
    newCustomer.setBilling(customer.getBilling());

    customerService.saveOrUpdate(newCustomer);

    model.addAttribute("customer", newCustomer);
    model.addAttribute("countries", countries);
    model.addAttribute("success", "success");

    return "admin-customer";
  }