public String createDeveloper(Developer developer) {

    StringBuffer sql = new StringBuffer();

    String key = UUID.randomUUID().toString();

    // encriptar password
    PasswordEncoder encoder = new Md5PasswordEncoder();
    String hashedPass = encoder.encodePassword(developer.getPassword(), null);

    sql.append("INSERT INTO developers ");
    sql.append("(username, password, email, key) ");
    sql.append("VALUES ");
    sql.append("(?, ?, ?, ?)");

    Object[] parametros;
    int[] types;

    parametros = new Object[] {developer.getUsername(), hashedPass, developer.getEmail(), key};

    types = new int[] {Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR};

    if (jdbcTemplate.update(sql.toString(), parametros, types) == 1) {
      return key;
    } else {
      return "-1";
    }
  }
Example #2
0
  /** {@inheritDoc} */
  @SuppressWarnings("unchecked")
  public void contextInitialized(ServletContextEvent event) {
    log.debug("Initializing context...");

    ServletContext context = event.getServletContext();

    // Orion starts Servlets before Listeners, so check if the config
    // object already exists
    Map<String, Object> config = (HashMap<String, Object>) context.getAttribute(Constants.CONFIG);

    if (config == null) {
      config = new HashMap<String, Object>();
    }

    if (context.getInitParameter(Constants.CSS_THEME) != null) {
      config.put(Constants.CSS_THEME, context.getInitParameter(Constants.CSS_THEME));
    }

    ApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(context);

    /*String[] beans = ctx.getBeanDefinitionNames();
    for (String bean : beans) {
        log.debug(bean);
    }*/

    PasswordEncoder passwordEncoder = null;
    try {
      ProviderManager provider =
          (ProviderManager)
              ctx.getBean("org.springframework.security.authentication.ProviderManager#0");
      for (Object o : provider.getProviders()) {
        AuthenticationProvider p = (AuthenticationProvider) o;
        if (p instanceof RememberMeAuthenticationProvider) {
          config.put("rememberMeEnabled", Boolean.TRUE);
        } else if (ctx.getBean("passwordEncoder") != null) {
          passwordEncoder = (PasswordEncoder) ctx.getBean("passwordEncoder");
        }
      }
    } catch (NoSuchBeanDefinitionException n) {
      log.debug("authenticationManager bean not found, assuming test and ignoring...");
      // ignore, should only happen when testing
    }

    context.setAttribute(Constants.CONFIG, config);

    // output the retrieved values for the Init and Context Parameters
    if (log.isDebugEnabled()) {
      log.debug("Remember Me Enabled? " + config.get("rememberMeEnabled"));
      if (passwordEncoder != null) {
        log.debug("Password Encoder: " + passwordEncoder.getClass().getSimpleName());
      }
      log.debug("Populating drop-downs...");
    }

    setupContext(context);
  }
  @Override
  public void setCustomerModelDefaultProperties(Customer customer, MerchantStore store)
      throws Exception {
    Validate.notNull(customer, "Customer object cannot be null");
    if (customer.getId() == null || customer.getId() == 0) {
      if (StringUtils.isBlank(customer.getNick())) {
        String userName = UserReset.generateRandomString(USERNAME_LENGTH);
        customer.setNick(userName);
      }
      if (StringUtils.isBlank(customer.getPassword())) {
        String password = UserReset.generateRandomString();
        String encodedPassword = passwordEncoder.encodePassword(password, null);
        customer.setPassword(encodedPassword);
      }
    }

    if (CollectionUtils.isEmpty(customer.getGroups())) {
      List<Group> groups = groupService.listGroup(GroupType.CUSTOMER);
      for (Group group : groups) {
        if (group.getGroupName().equals(Constants.GROUP_CUSTOMER)) {
          customer.getGroups().add(group);
        }
      }
    }
  }
  @Override
  public User registerUser(UserModel userModel, boolean useTemporaryPassword) {
    User user = null;
    if (userModel != null) {
      List<Role> userRoles = new ArrayList<Role>();
      Role userRole = roleService.getRoleByAuthority(UserRole.ROLE_USER.toString());
      userRoles.add(userRole);

      user =
          new User(
              userModel.getEmail(),
              passwordEncoder.encodePassword(userModel.getPassword(), userModel.getEmail()),
              userModel.getEmail(),
              userModel.getFirstName(),
              userModel.getLastName(),
              userRoles);
      user.setPasswordExpired(useTemporaryPassword);
      // If this is the first user in the application, set them as a Knappsack administrator
      if (userService.countAll() == 0) {
        setAdminRole(user);
      }
      userDetailsDao.add(user);
      addUserToInvitedDomains(user);
    }

    return user;
  }
  @Override
  public Customer getCustomerModel(
      final PersistableCustomer customer, final MerchantStore merchantStore, Language language)
      throws Exception {

    LOG.info("Starting to populate customer model from customer data");
    Customer customerModel = null;
    CustomerPopulator populator = new CustomerPopulator();
    populator.setCountryService(countryService);
    populator.setCustomerOptionService(customerOptionService);
    populator.setCustomerOptionValueService(customerOptionValueService);
    populator.setLanguageService(languageService);
    populator.setLanguageService(languageService);
    populator.setZoneService(zoneService);

    customerModel = populator.populate(customer, merchantStore, language);
    // set groups
    if (!StringUtils.isBlank(customerModel.getPassword())
        && !StringUtils.isBlank(customerModel.getNick())) {
      customerModel.setPassword(passwordEncoder.encodePassword(customer.getClearPassword(), null));
      setCustomerModelDefaultProperties(customerModel, merchantStore);
    }

    return customerModel;
  }
  /** {@inheritDoc} */
  @Override
  public User saveExistingUser(final User user) {
    // Existing user, check password in DB
    UserDetails existingUser = null;

    try {
      existingUser = dao.loadUserByUsername(user.getUsername());
    } catch (final UsernameNotFoundException e) {
      // username could not be found
    }

    String currentPassword = "";
    if (existingUser == null) {
      // lowercase userId
      ((UserImpl) user).setUsername(user.getUsername().toLowerCase());
    } else {
      currentPassword = existingUser.getPassword();
    }

    // if new user or changed password, encrypt the password
    if (StringUtils.isBlank(currentPassword) || !currentPassword.equals(user.getPassword())) {
      ((UserImpl) user).setPassword(passwordEncoder.encodePassword(user.getPassword(), null));
    }

    return dao.save(user);
  }
 /**
  * 계정을 생성한다.
  *
  * @param userId
  * @param password
  * @param name
  * @param email
  */
 public void insertAccount(String userId, String password, String name, String email) {
   UserInfoVO userInfo = new UserInfoVO();
   userInfo.setName(name);
   userInfo.setPassword(passwordEncoder.encodePassword(password, null));
   userInfo.setEmail(email);
   userInfo.setUserId(userId);
   userInfo.setPrinciple(userInfoDao.getUserInfoCount() + 1);
   userInfoDao.insertAccount(userInfo);
   userInfoDao.insertAuthority(userInfo);
 }
 @Test
 public void can_retrieve_lost_password() {
   String newPassword = "******";
   DomainUser domainUser =
       userService.create(new DomainUser(randomString(), randomEmail(), randomString()));
   LostPasswordData token =
       userService.requestPasswordChangeToken(domainUser.getEmail(), new Date());
   userService.changePassword(token.getEmail(), token.getToken(), newPassword, newPassword);
   String expected = passwordEncoder.encodePassword(newPassword, domainUser.getPasswordSalt());
   assertThat(userService.findByID(domainUser.getId()).getPassword()).isEqualTo(expected);
 }
 @Transactional
 public void createAccount(Account user) throws UsernameAlreadyInUseException {
   try {
     jdbcTemplate.update(
         "insert into Account (firstName, lastName, username, password) values (?, ?, ?, ?)",
         user.getFirstName(),
         user.getLastName(),
         user.getUsername(),
         passwordEncoder.encodePassword(user.getPassword(), null));
   } catch (DuplicateKeyException e) {
     throw new UsernameAlreadyInUseException(user.getUsername());
   }
 }
 @Test
 public void can_update_user() {
   String newPassword = "******";
   DomainUser domainUser =
       userService.create(new DomainUser(randomString(), randomEmail(), randomString()));
   domainUser =
       userService.update(
           new DomainUser(
               domainUser.getId(), domainUser.getUsername(), domainUser.getEmail(), newPassword));
   String encryptedPass =
       passwordEncoder.encodePassword(newPassword, domainUser.getPasswordSalt());
   assertThat(userRepository.findByUsernameAndPassword(domainUser.getUsername(), encryptedPass))
       .isNotNull();
 }
Example #11
0
  public void isPasswordEncoder() {
    try {
      String plainPassword = "******";
      String expectedEncodedPassword = "******";

      System.out.println("plainPassword: "******"expectedEncodedPassword: " + expectedEncodedPassword);

      assertTrue(passwordEncoder.isPasswordValid(expectedEncodedPassword, plainPassword, null));
    } catch (Exception e) {
      e.printStackTrace();
      fail();
    }
  }
Example #12
0
  public void testEncode() {
    try {
      String plainPassword = "******";
      String expectedEncodedPassword = "******";
      String encodedPassword = passwordEncoder.encodePassword(plainPassword, null);

      System.out.println("plainPassword: "******"encodedPassword: " + encodedPassword);
      assertEquals(expectedEncodedPassword, encodedPassword);
    } catch (Exception e) {
      e.printStackTrace();
      fail();
    }
  }
  /** {@inheritDoc} */
  public User saveUser(User user) throws UserExistsException {

    if (user.getVersion() == null) {
      // if new user, lowercase userId
      user.setUsername(user.getUsername().toLowerCase());
    }

    // Get and prepare password management-related artifacts
    boolean passwordChanged = false;
    if (passwordEncoder != null) {
      // Check whether we have to encrypt (or re-encrypt) the password
      if (user.getVersion() == null) {
        // New user, always encrypt
        passwordChanged = true;
      } else {
        // Existing user, check password in DB
        String currentPassword = userDao.getUserPassword(user.getUsername());
        if (currentPassword == null) {
          passwordChanged = true;
        } else {
          if (!currentPassword.equals(user.getPassword())) {
            passwordChanged = true;
          }
        }
      }

      // If password was changed (or new user), encrypt it
      if (passwordChanged) {
        user.setPassword(passwordEncoder.encodePassword(user.getPassword(), null));
      }
    } else {
      log.warn("PasswordEncoder not set, skipping password encryption...");
    }

    try {
      return userDao.saveUser(user);
    } catch (DataIntegrityViolationException e) {
      // e.printStackTrace();
      log.warn(e.getMessage());
      throw new UserExistsException("User '" + user.getUsername() + "' already exists!");
    } catch (JpaSystemException e) { // needed for JPA
      // e.printStackTrace();
      log.warn(e.getMessage());
      throw new UserExistsException("User '" + user.getUsername() + "' already exists!");
    }
  }
 /*
  * (non-Javadoc)
  *
  * @see edu.kit.pse.ass.user.management.UserManagement#register(java.lang.String, java.lang.String)
  */
 @Override
 @Transactional
 public String register(String userID, String password)
     throws UserAlreadyExistsException, IllegalArgumentException {
   if (userID == null || userID.isEmpty()) {
     throw new IllegalArgumentException("Illegal userID specified.");
   }
   if (password == null || password.isEmpty()) {
     throw new IllegalArgumentException("Illegal password specified");
   }
   password = passwordEncoder.encodePassword(password, null);
   if (userDAO.getUser(userID) != null) {
     throw new UserAlreadyExistsException();
   }
   User u = userDAO.insertUser(userID, password);
   return u.getEmail();
 }
 @Override
 protected void additionalAuthenticationChecks(
     UserDetails userDetails, UsernamePasswordAuthenticationToken authentication)
     throws AuthenticationException {
   if (authentication.getCredentials() == null) {
     logger.debug("Authentication failed: no credentials provided");
     throw new BadCredentialsException(
         messages.getMessage(
             "AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"),
         userDetails);
   }
   String presentedPassword = authentication.getCredentials().toString();
   if (!passwordEncoder.isPasswordValid(userDetails.getPassword(), presentedPassword, null)) {
     logger.debug("Authentication failed: password does not match stored value");
     throw new BadCredentialsException(
         messages.getMessage(
             "AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"),
         userDetails);
   }
 }
  private boolean authenticate(String username, String password, String realm) {
    if ((username == null) && (password == null)) {
      return false;
    }

    try {
      String encodedPassword = passwordEncoder.encodePassword(password, null);
      Authentication authentication =
          authenticationManager.authenticate(
              new NextServerAuthentication(username, encodedPassword, realm));
      if (!authentication.isAuthenticated()) {
        return false;
      }

      SecurityContextHolder.getContext().setAuthentication(authentication);

      return true;
    } catch (AuthenticationException e) {
      return false;
    }
  }
  /** A-Team feature: forming xml|json files with notes 26-04-2012 */
  @RequestMapping(value = "/api/user/notes", method = RequestMethod.GET)
  public String exportExecute(
      @RequestParam Map<String, Object> reqMap,
      @RequestParam("email") String email,
      @RequestParam("pass") String password,
      @RequestParam("type") String formatXmlJson,
      HttpServletRequest request,
      HttpServletResponse response)
      throws IOException {

    PrintWriter out = response.getWriter();
    response.setContentType("text/plain");
    User currentUser = null;
    currentUser = userService.getUserByEmail(email);

    String encodedPass = passwordEncoder.encodePassword(password, null);
    if (currentUser != null && encodedPass.equals(currentUser.getPassword())) {
      List<Record> records =
          recordService.getRecords(
              currentUser, accessService.getAccess(2), recordTypeService.getRecordType(1), "");

      xmlService = new XMLService();
      if (formatXmlJson.equals("xml")) {
        xmlService.formXml(records, currentUser, accessService.getAccess(2));
      } else {
        xmlService.formJson(records, currentUser, accessService.getAccess(2));
      }
      out.print(xmlService.getXmlText().toString());
      out.close();
    } else {

      out.println("Access denied");
      out.close();
    }
    return null;
  }
Example #18
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;
  }
  public Account saveNewUser(Account account) {
    account.setPassword(passwordEncoder.encodePassword(account.getPassword(), null));

    return accountRepository.save(account);
  }
Example #20
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;
  }
Example #21
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;
  }
 private String getHash(String plaintext, String salt) {
   return passwordEncoder.encodePassword(plaintext, salt);
 }
Example #23
0
 @Transactional
 public void addUser(User u, String pass) {
   userDao.saveOrUpdate(u);
   u.setPassword(passwordEncoder.encodePassword(pass, u.getId()));
   userDao.saveOrUpdate(u);
 }
Example #24
0
  /** {@inheritDoc} */
  @Override
  public User save(final User user) {
    ((UserImpl) user).setPassword(passwordEncoder.encodePassword(user.getPassword(), null));

    return dao.save(user);
  }
  @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();
  }
Example #26
0
 public void setPassword(String password) {
   PasswordEncoder crypto = new Md5PasswordEncoder();
   this.password = crypto.encodePassword(password, null);
 }
  @RequestMapping(value = "/new", method = RequestMethod.POST)
  public String newUser(
      @RequestParam("fname") String fname,
      @RequestParam("lname") String lname,
      @RequestParam("username") String username,
      @RequestParam("password") String pass,
      @RequestParam("role") String role,
      ModelMap map) {
    try {
      ebFirstNameValidator.validate(fname);
      ebLastNameValidator.validate(lname);
      ebUsernameValidator.validate(username);
      ebPasswordValidator.validate(pass);

    } catch (EBException e) {
      map.addAttribute("fname", fname);
      map.addAttribute("lname", lname);
      map.addAttribute("username", username);
      map.addAttribute("pass", pass);
      map.addAttribute("error", e.getErrorMessage());
      return "newuser";
    }

    PasswordEncoder encoder = new Md5PasswordEncoder();
    String hashedPass = encoder.encodePassword(pass, null);
    ebUserService.addUser(fname, lname, username, hashedPass);
    EBUser e = ebUserService.getUser(username);
    EBUserRole r = ebUserRoleService.getRoleByName(role);
    List<EBUserRole> list = new ArrayList<EBUserRole>();
    list.add(r);
    e.setUserRole(list);
    ebUserService.addUser(e);

    return "sAdmin";
  }