protected AddressForm getPreparedAddressForm() {
   final CustomerData currentCustomerData = customerFacade.getCurrentCustomer();
   final AddressForm addressForm = new AddressForm();
   addressForm.setFirstName(currentCustomerData.getFirstName());
   addressForm.setLastName(currentCustomerData.getLastName());
   addressForm.setTitleCode(currentCustomerData.getTitleCode());
   return addressForm;
 }
 @RequestMapping(value = "/my-company", method = RequestMethod.GET)
 @RequireHardLogIn
 public String myCompany(final Model model) throws CMSItemNotFoundException {
   storeCmsPageInModel(model, getContentPageForLabelOrId(MY_COMPANY_CMS_PAGE));
   setUpMetaDataForContentPage(model, getContentPageForLabelOrId(MY_COMPANY_CMS_PAGE));
   model.addAttribute("breadcrumbs", myCompanyBreadcrumbBuilder.getBreadcrumbs(null));
   model.addAttribute("unitUid", companyB2BCommerceFacade.getParentUnit().getUid());
   model.addAttribute("userUid", customerFacade.getCurrentCustomer().getUid());
   model.addAttribute("metaRobots", "no-index,no-follow");
   return getViewForPage(model);
 }
 @RequestMapping(value = "/payment-details", method = RequestMethod.GET)
 @RequireHardLogIn
 public String paymentDetails(final Model model) throws CMSItemNotFoundException {
   model.addAttribute("customerData", customerFacade.getCurrentCustomer());
   model.addAttribute("paymentInfoData", userFacade.getCCPaymentInfos(true));
   storeCmsPageInModel(model, getContentPageForLabelOrId(PAYMENT_DETAILS_CMS_PAGE));
   setUpMetaDataForContentPage(model, getContentPageForLabelOrId(ADD_EDIT_ADDRESS_CMS_PAGE));
   model.addAttribute(
       "breadcrumbs", accountBreadcrumbBuilder.getBreadcrumbs("text.account.paymentDetails"));
   model.addAttribute("metaRobots", "no-index,no-follow");
   return ControllerConstants.Views.Pages.Account.AccountPaymentInfoPage;
 }
  @RequestMapping(value = "/update-email", method = RequestMethod.POST)
  @RequireHardLogIn
  public String updateEmail(
      final UpdateEmailForm updateEmailForm,
      final BindingResult bindingResult,
      final Model model,
      final RedirectAttributes redirectAttributes,
      final HttpServletRequest request)
      throws CMSItemNotFoundException {
    getEmailValidator().validate(updateEmailForm, bindingResult);

    String returnAction = REDIRECT_TO_PROFILE_PAGE;

    if (!bindingResult.hasErrors()
        && !updateEmailForm.getEmail().equals(updateEmailForm.getChkEmail())) {
      bindingResult.rejectValue(
          "chkEmail",
          "validation.checkEmail.equals",
          new Object[] {},
          "validation.checkEmail.equals");
    }

    if (bindingResult.hasErrors()) {
      returnAction = errorUpdatingEmail(model);
    } else {
      try {
        customerFacade.changeUid(updateEmailForm.getEmail(), updateEmailForm.getPassword());
        GlobalMessages.addFlashMessage(
            redirectAttributes,
            GlobalMessages.CONF_MESSAGES_HOLDER,
            "text.account.profile.confirmationUpdated",
            null);

        // Replace the spring security authentication with the new UID
        final String newUid = customerFacade.getCurrentCustomer().getUid().toLowerCase();
        final Authentication oldAuthentication =
            SecurityContextHolder.getContext().getAuthentication();
        final UsernamePasswordAuthenticationToken newAuthentication =
            new UsernamePasswordAuthenticationToken(
                newUid, null, oldAuthentication.getAuthorities());
        newAuthentication.setDetails(oldAuthentication.getDetails());
        SecurityContextHolder.getContext().setAuthentication(newAuthentication);
      } catch (final DuplicateUidException e) {
        bindingResult.rejectValue("email", "profile.email.unique");
        returnAction = errorUpdatingEmail(model);
      } catch (final PasswordMismatchException passwordMismatchException) {
        bindingResult.rejectValue("password", "profile.currentPassword.invalid");
        returnAction = errorUpdatingEmail(model);
      }
    }

    return returnAction;
  }
  @RequestMapping(value = "/update-email", method = RequestMethod.GET)
  @RequireHardLogIn
  public String editEmail(final Model model) throws CMSItemNotFoundException {
    final CustomerData customerData = customerFacade.getCurrentCustomer();
    final UpdateEmailForm updateEmailForm = new UpdateEmailForm();

    updateEmailForm.setEmail(customerData.getDisplayUid());

    model.addAttribute("updateEmailForm", updateEmailForm);

    storeCmsPageInModel(model, getContentPageForLabelOrId(PROFILE_CMS_PAGE));
    setUpMetaDataForContentPage(model, getContentPageForLabelOrId(PROFILE_CMS_PAGE));
    model.addAttribute(
        "breadcrumbs", accountBreadcrumbBuilder.getBreadcrumbs("text.account.profile"));
    model.addAttribute("metaRobots", "no-index,no-follow");
    return ControllerConstants.Views.Pages.Account.AccountProfileEmailEditPage;
  }
  protected void setupAuthenticationHandler() {
    BDDMockito.doReturn(Boolean.FALSE)
        .when(authenticationSuccessHandler)
        .isAlwaysUseDefaultTargetUrl();

    BDDMockito.doNothing().when(customerFacade).loginSuccess();
    final CustomerData customer = BDDMockito.mock(CustomerData.class);
    BDDMockito.given(customer.getUid()).willReturn("customer");
    BDDMockito.given(customerFacade.getCurrentCustomer()).willReturn(customer);

    BDDMockito.given(authenticationSuccessHandler.getCartFacade().getCartsForCurrentUser())
        .willReturn(savedCarts);
    BDDMockito.given(cartFacade.hasSessionCart()).willReturn(Boolean.TRUE);
    BDDMockito.given(cartFacade.getSessionCart()).willReturn(sessionCart);

    BDDMockito.doNothing().when(bruteForceAttackCounter).resetUserCounter("customer");
  }
  @RequestMapping(value = "/update-profile", method = RequestMethod.POST)
  @RequireHardLogIn
  public String updateProfile(
      final UpdateProfileForm updateProfileForm,
      final BindingResult bindingResult,
      final Model model,
      final RedirectAttributes redirectAttributes)
      throws CMSItemNotFoundException {
    getProfileValidator().validate(updateProfileForm, bindingResult);

    String returnAction = ControllerConstants.Views.Pages.Account.AccountProfileEditPage;
    final CustomerData currentCustomerData = customerFacade.getCurrentCustomer();
    final CustomerData customerData = new CustomerData();
    customerData.setTitleCode(updateProfileForm.getTitleCode());
    customerData.setFirstName(updateProfileForm.getFirstName());
    customerData.setLastName(updateProfileForm.getLastName());
    customerData.setUid(currentCustomerData.getUid());
    customerData.setDisplayUid(currentCustomerData.getDisplayUid());

    model.addAttribute("titleData", userFacade.getTitles());

    if (bindingResult.hasErrors()) {
      GlobalMessages.addErrorMessage(model, "form.global.error");
    } else {
      try {
        customerFacade.updateProfile(customerData);
        GlobalMessages.addFlashMessage(
            redirectAttributes,
            GlobalMessages.CONF_MESSAGES_HOLDER,
            "text.account.profile.confirmationUpdated",
            null);
        returnAction = REDIRECT_TO_PROFILE_PAGE;
      } catch (final DuplicateUidException e) {
        bindingResult.rejectValue("email", "registration.error.account.exists.title");
        GlobalMessages.addErrorMessage(model, "form.global.error");
      }
    }

    storeCmsPageInModel(model, getContentPageForLabelOrId(PROFILE_CMS_PAGE));
    setUpMetaDataForContentPage(model, getContentPageForLabelOrId(PROFILE_CMS_PAGE));
    model.addAttribute(
        "breadcrumbs", accountBreadcrumbBuilder.getBreadcrumbs("text.account.profile"));
    return returnAction;
  }
  @RequestMapping(value = "/profile", method = RequestMethod.GET)
  @RequireHardLogIn
  public String profile(final Model model) throws CMSItemNotFoundException {
    final List<TitleData> titles = userFacade.getTitles();

    final CustomerData customerData = customerFacade.getCurrentCustomer();
    if (customerData.getTitleCode() != null) {
      model.addAttribute("title", findTitleForCode(titles, customerData.getTitleCode()));
    }

    model.addAttribute("customerData", customerData);

    storeCmsPageInModel(model, getContentPageForLabelOrId(PROFILE_CMS_PAGE));
    setUpMetaDataForContentPage(model, getContentPageForLabelOrId(PROFILE_CMS_PAGE));
    model.addAttribute(
        "breadcrumbs", accountBreadcrumbBuilder.getBreadcrumbs("text.account.profile"));
    model.addAttribute("metaRobots", "no-index,no-follow");
    return ControllerConstants.Views.Pages.Account.AccountProfilePage;
  }
  protected String unitDetails(
      final String unit, final Model model, final HttpServletRequest request)
      throws CMSItemNotFoundException {
    storeCmsPageInModel(model, getContentPageForLabelOrId(MANAGE_UNITS_CMS_PAGE));
    setUpMetaDataForContentPage(model, getContentPageForLabelOrId(MANAGE_UNITS_CMS_PAGE));
    final List<Breadcrumb> breadcrumbs =
        myCompanyBreadcrumbBuilder.createManageUnitsDetailsBreadcrumbs(unit);
    model.addAttribute("breadcrumbs", breadcrumbs);

    B2BUnitData unitData = companyB2BCommerceFacade.getUnitForUid(unit);
    if (unitData == null) {
      unitData = new B2BUnitData();
      GlobalMessages.addErrorMessage(model, "b2bunit.notfound");
    } else if (!unitData.isActive()) {
      GlobalMessages.addInfoMessage(model, "b2bunit.disabled.infomsg");
    }

    model.addAttribute("unit", unitData);
    model.addAttribute("user", customerFacade.getCurrentCustomer());
    model.addAttribute("metaRobots", "no-index,no-follow");
    return ControllerConstants.Views.Pages.MyCompany.MyCompanyManageUnitDetailsPage;
  }
  @RequestMapping(value = "/update-profile", method = RequestMethod.GET)
  @RequireHardLogIn
  public String editProfile(final Model model) throws CMSItemNotFoundException {
    model.addAttribute("titleData", userFacade.getTitles());

    final CustomerData customerData = customerFacade.getCurrentCustomer();
    final UpdateProfileForm updateProfileForm = new UpdateProfileForm();

    updateProfileForm.setTitleCode(customerData.getTitleCode());
    updateProfileForm.setFirstName(customerData.getFirstName());
    updateProfileForm.setLastName(customerData.getLastName());

    model.addAttribute("updateProfileForm", updateProfileForm);

    storeCmsPageInModel(model, getContentPageForLabelOrId(UPDATE_PROFILE_CMS_PAGE));
    setUpMetaDataForContentPage(model, getContentPageForLabelOrId(UPDATE_PROFILE_CMS_PAGE));

    model.addAttribute(
        "breadcrumbs", accountBreadcrumbBuilder.getBreadcrumbs("text.account.profile"));
    model.addAttribute("metaRobots", "noindex,nofollow");
    return getViewForPage(model);
  }
 @ModelAttribute("user")
 public CustomerData getUser() {
   return customerFacade.getCurrentCustomer();
 }
  protected String editUser(
      final String user,
      final B2BCustomerForm b2BCustomerForm,
      final BindingResult bindingResult,
      final Model model,
      final RedirectAttributes redirectModel)
      throws CMSItemNotFoundException {
    if (bindingResult.hasErrors()) {
      GlobalMessages.addErrorMessage(model, "form.global.error");
      model.addAttribute(b2BCustomerForm);
      return editUser(b2BCustomerForm.getUid(), model);
    }

    // A B2B Admin should not be able to downgrade their roles, they must at lest belong to B2B
    // Administrator role
    if (customerFacade.getCurrentCustomer().getUid().equals(b2BCustomerForm.getUid())) {
      final Collection<String> roles =
          b2BCustomerForm.getRoles() != null ? b2BCustomerForm.getRoles() : new ArrayList<String>();
      if (!roles.contains(B2BConstants.B2BADMINGROUP)) {
        GlobalMessages.addErrorMessage(model, "form.b2bcustomer.adminrole.error");
        roles.add(B2BConstants.B2BADMINGROUP);
        b2BCustomerForm.setRoles(roles);
        model.addAttribute(b2BCustomerForm);
        return editUser(b2BCustomerForm.getUid(), model);
      } else {
        // A session user can't modify their own parent unit.
        final B2BUnitData parentUnit = companyB2BCommerceFacade.getParentUnit();
        if (!parentUnit.getUid().equals(b2BCustomerForm.getParentB2BUnit())) {
          GlobalMessages.addErrorMessage(model, "form.b2bcustomer.parentunit.error");
          b2BCustomerForm.setParentB2BUnit(parentUnit.getUid());
          model.addAttribute(b2BCustomerForm);
          return editUser(b2BCustomerForm.getUid(), model);
        }
      }
    }

    final CustomerData b2bCustomerData = new CustomerData();
    b2bCustomerData.setUid(b2BCustomerForm.getUid());
    b2bCustomerData.setTitleCode(b2BCustomerForm.getTitleCode());
    b2bCustomerData.setFirstName(b2BCustomerForm.getFirstName());
    b2bCustomerData.setLastName(b2BCustomerForm.getLastName());
    b2bCustomerData.setEmail(b2BCustomerForm.getEmail());
    b2bCustomerData.setDisplayUid(b2BCustomerForm.getEmail());
    b2bCustomerData.setUnit(
        companyB2BCommerceFacade.getUnitForUid(b2BCustomerForm.getParentB2BUnit()));
    b2bCustomerData.setRoles(
        b2BCustomerForm.getRoles() != null
            ? b2BCustomerForm.getRoles()
            : Collections.<String>emptyList());
    model.addAttribute(b2BCustomerForm);
    model.addAttribute("titleData", getUserFacade().getTitles());
    model.addAttribute("roles", populateRolesCheckBoxes(companyB2BCommerceFacade.getUserGroups()));

    storeCmsPageInModel(model, getContentPageForLabelOrId(ORGANIZATION_MANAGEMENT_CMS_PAGE));
    setUpMetaDataForContentPage(
        model, getContentPageForLabelOrId(ORGANIZATION_MANAGEMENT_CMS_PAGE));
    final List<Breadcrumb> breadcrumbs =
        myCompanyBreadcrumbBuilder.createManageUserDetailsBreadcrumb(user);
    model.addAttribute("breadcrumbs", breadcrumbs);

    try {
      b2bCommerceUserFacade.updateCustomer(b2bCustomerData);
      b2bCustomerData.setUid(b2BCustomerForm.getEmail().toLowerCase());
      GlobalMessages.addFlashMessage(
          redirectModel, GlobalMessages.CONF_MESSAGES_HOLDER, "text.confirmation.user.edited");
    } catch (final DuplicateUidException e) {
      bindingResult.rejectValue("email", "text.manageuser.error.email.exists.title");
      GlobalMessages.addErrorMessage(model, "form.global.error");
      model.addAttribute("b2BCustomerForm", b2BCustomerForm);
      return editUser(b2BCustomerForm.getUid(), model);
    }
    return String.format(REDIRECT_TO_USER_DETAILS, urlEncode(b2bCustomerData.getUid()));
  }