Beispiel #1
0
 @Test
 public void testRemove() throws Exception {
   User user = new User("admin");
   user.setId(-2L);
   action.setUser(user);
   assertEquals("success", action.delete());
   assertFalse(action.hasActionErrors());
 }
  @Test
  public void testEdit() throws Exception {
    log.debug("testing edit...");
    request = newGet("/userform.html");
    request.addParameter("id", "-1"); // regular user
    request.addUserRole(Constants.ADMIN_ROLE);

    User user = c.showForm(request, new MockHttpServletResponse());
    assertEquals("Tomcat User", user.getFullName());
  }
  @Before
  public void beforeEachMethod() {
    promotionsService = new PromotionsService();

    user = new User("*****@*****.**");
    user.setId(1L);
  }
  @Test
  public void testSave() throws Exception {
    request = newPost("/userform.html");
    // set updated properties first since adding them later will
    // result in multiple parameters with the same name getting sent
    User user = ((UserManager) applicationContext.getBean("userManager")).getUser("-1");
    user.setConfirmPassword(user.getPassword());
    user.setLastName("Updated Last Name");

    request.setRemoteUser(user.getUsername());

    BindingResult errors = new DataBinder(user).getBindingResult();
    c.onSubmit(user, errors, request, new MockHttpServletResponse());

    assertFalse(errors.hasErrors());
    assertNotNull(request.getSession().getAttribute("successMessages"));
  }
Beispiel #5
0
  @Test
  public void testSave() throws Exception {
    UserManager userManager = (UserManager) applicationContext.getBean("userManager");
    User user = userManager.getUserByUsername("user");
    user.setPassword("user");
    user.setConfirmPassword("user");
    action.setUser(user);
    action.setFrom("list");

    MockHttpServletRequest request = new MockHttpServletRequest();
    request.addParameter("encryptPass", "true");
    ServletActionContext.setRequest(request);

    assertEquals("input", action.save());
    assertNotNull(action.getUser());
    assertFalse(action.hasActionErrors());
  }
  @RequestMapping(method = RequestMethod.GET)
  public ModelAndView handleRequest(HttpServletRequest request) throws Exception {
    log.debug("entering 'handleRequest' method...");

    String username = request.getParameter("username");
    MessageSourceAccessor text = new MessageSourceAccessor(messageSource, request.getLocale());

    // ensure that the username has been sent
    if (username == null) {
      log.warn("Username not specified, notifying user that it's a required field.");
      request.setAttribute(
          "error", text.getMessage("errors.required", text.getMessage("user.username")));
      return new ModelAndView("login");
    }

    log.debug("Processing Password Hint...");

    // look up the user's information
    try {
      User user = userManager.getUserByUsername(username);

      StringBuffer msg = new StringBuffer();
      msg.append("Your password hint is: ").append(user.getPasswordHint());
      msg.append("\n\nLogin at: ").append(RequestUtil.getAppURL(request));

      message.setTo(user.getEmail());
      String subject =
          '[' + text.getMessage("webapp.name") + "] " + text.getMessage("user.passwordHint");
      message.setSubject(subject);
      message.setText(msg.toString());
      mailEngine.send(message);

      saveMessage(
          request,
          text.getMessage("login.passwordHint.sent", new Object[] {username, user.getEmail()}));
    } catch (UsernameNotFoundException e) {
      log.warn(e.getMessage());
      saveError(request, text.getMessage("login.passwordHint.error", new Object[] {username}));
    } catch (MailException me) {
      log.warn(me.getMessage());
      saveError(request, me.getCause().getLocalizedMessage());
    }

    return new ModelAndView(new RedirectView(request.getContextPath()));
  }
  @Test
  public void testEditProfile() throws Exception {
    log.debug("testing edit profile...");
    request = newGet("/userform.html");
    request.setRemoteUser("user");

    user = c.showForm(request, new MockHttpServletResponse());
    assertEquals("Tomcat User", user.getFullName());
  }
Beispiel #8
0
  public void send(User user, String subject, String message, String url, boolean hint)
      throws UsernameNotFoundException, MailException {

    StringBuilder msg = new StringBuilder(message);
    if (!hint) {
      msg.append("\n\n").append(messages.get("user.username"));
      msg.append(": ").append(user.getUsername()).append("\n");
      msg.append(messages.get("user.password")).append(": ");
      msg.append(user.getPassword());
    }
    msg.append("\n\nLogin at: ").append(url);

    simpleMailMessage.setTo(user.getFullName() + "<" + user.getEmail() + ">");
    simpleMailMessage.setSubject(subject);
    simpleMailMessage.setText(msg.toString());

    mailEngine.send(simpleMailMessage);
  }
  /**
   * Convenience message to send messages to users, includes app URL as footer.
   *
   * @param user the user to send a message to.
   * @param msg the message to send.
   * @param url the URL of the application.
   */
  protected void sendUserMessage(User user, String msg, String url) {
    if (log.isDebugEnabled()) {
      log.debug("sending e-mail to user [" + user.getEmail() + "]...");
    }

    message.setTo(user.getFullName() + "<" + user.getEmail() + ">");

    Map<String, Serializable> model = new HashMap<String, Serializable>();
    model.put("user", user);

    // TODO: once you figure out how to get the global resource bundle in
    // WebWork, then figure it out here too.  In the meantime, the Username
    // and Password labels are hard-coded into the template.
    // model.put("bundle", getTexts());
    model.put("message", msg);
    model.put("applicationURL", url);
    mailEngine.sendMessage(message, templateName, model);
  }
  @Test
  public void testAdd() throws Exception {
    log.debug("testing add new user...");
    request = newGet("/userform.html");
    request.addParameter("method", "Add");
    request.addUserRole(Constants.ADMIN_ROLE);

    user = c.showForm(request, new MockHttpServletResponse());
    assertNull(user.getUsername());
  }
  @Test
  public void testSignupUser() throws Exception {
    MockHttpServletRequest request = newPost("/signup.html");

    Address address = new Address();
    address.setCity("Denver");
    address.setProvince("Colorado");
    address.setCountry("USA");
    address.setPostalCode("80210");

    User user = new User();
    user.setAddress(address);

    user.setUsername("self-registered");
    user.setPassword("Password1");
    user.setConfirmPassword("Password1");
    user.setFirstName("First");
    user.setLastName("Last");
    user.setEmail("*****@*****.**");
    user.setWebsite("http://raibledesigns.com");
    user.setPasswordHint("Password is one with you.");

    HttpServletResponse response = new MockHttpServletResponse();

    // start SMTP Server
    Wiser wiser = new Wiser();
    wiser.setPort(getSmtpPort());
    wiser.start();

    BindingResult errors = new DataBinder(user).getBindingResult();
    c.onSubmit(user, errors, request, response);
    assertFalse("errors returned in model", errors.hasErrors());

    // verify an account information e-mail was sent
    wiser.stop();
    assertTrue(wiser.getMessages().size() == 1);

    // verify that success messages are in the request
    assertNotNull(request.getSession().getAttribute("successMessages"));
    assertNotNull(request.getSession().getAttribute(Constants.REGISTERED));

    SecurityContextHolder.getContext().setAuthentication(null);
  }
  /**
   * Save the user, encrypting their passwords if necessary
   *
   * @return success when good things happen
   * @throws Exception when bad things happen
   */
  public String save() throws Exception {
    user.setEnabled(true);

    // Set the default user role on this new user
    user.addRole(roleManager.getRole(Constants.USER_ROLE));

    try {
      userManager.saveUser(user);
    } catch (AccessDeniedException ade) {
      // thrown by UserSecurityAdvice configured in aop:advisor userManagerSecurity
      log.warn(ade.getMessage());
      getResponse().sendError(HttpServletResponse.SC_FORBIDDEN);
      return null;
    } catch (UserExistsException e) {
      log.warn(e.getMessage());
      List<Object> args = new ArrayList<Object>();
      args.add(user.getUsername());
      args.add(user.getEmail());
      addActionError(getText("errors.existing.user", args));

      // redisplay the unencrypted passwords
      user.setPassword(user.getConfirmPassword());
      return INPUT;
    }

    saveMessage(getText("user.registered"));
    getSession().setAttribute(Constants.REGISTERED, Boolean.TRUE);

    // log user in automatically
    UsernamePasswordAuthenticationToken auth =
        new UsernamePasswordAuthenticationToken(
            user.getUsername(), user.getConfirmPassword(), user.getAuthorities());
    auth.setDetails(user);
    SecurityContextHolder.getContext().setAuthentication(auth);

    // Send an account information e-mail
    mailMessage.setSubject(getText("signup.email.subject"));

    try {
      sendUserMessage(user, getText("signup.email.message"), RequestUtil.getAppURL(getRequest()));
    } catch (MailException me) {
      addActionError(me.getMostSpecificCause().getMessage());
    }

    return SUCCESS;
  }
  @Test
  public void testRemove() throws Exception {
    request = newPost("/userform.html");
    request.addParameter("delete", "");
    user = new User();
    user.setId(-2L);

    BindingResult errors = new DataBinder(user).getBindingResult();
    c.onSubmit(user, errors, request, new MockHttpServletResponse());

    assertNotNull(request.getSession().getAttribute("successMessages"));
  }
  @Test
  public void testAddWithMissingFields() throws Exception {
    request = newPost("/userform.html");
    user = new User();
    user.setFirstName("Jack");
    request.setRemoteUser("user");

    BindingResult errors = new DataBinder(user).getBindingResult();
    c.onSubmit(user, errors, request, new MockHttpServletResponse());

    assertEquals(4, errors.getAllErrors().size());
  }
Beispiel #15
0
  public String execute() {

    // ensure that the username has been sent
    if (username == null || "".equals(username)) {
      log.warn("Username not specified, notifying user that it's a required field.");

      addError("errors.required", getText("user.username"));
      return null;
    }

    if (log.isDebugEnabled()) {
      log.debug("Processing Password Hint...");
    }

    // look up the user's information
    try {
      User user = userManager.getUserByUsername(username);

      StringBuffer msg = new StringBuffer();
      msg.append("Your password hint is: " + user.getPasswordHint());
      msg.append("\n\nLogin at: " + RequestUtil.getAppURL(getRequest()));

      message.setTo(user.getEmail());
      String subject = '[' + getText("webapp.name") + "] " + getText("user.passwordHint");
      message.setSubject(subject);
      message.setText(msg.toString());
      mailEngine.send(message);

      addMessage("login.passwordHint.sent", new Object[] {username, user.getEmail()});

    } catch (Exception e) {
      e.printStackTrace();
      // If exception is expected do not rethrow
      addError("login.passwordHint.error", username);
    }

    return "success";
  }
Beispiel #16
0
  @Test
  public void testSaveConflictingUser() throws Exception {
    UserManager userManager = (UserManager) applicationContext.getBean("userManager");
    User user = userManager.getUserByUsername("user");
    user.setPassword("user");
    user.setConfirmPassword("user");
    // e-mail address from existing user
    User existingUser = (User) userManager.getUsers().get(0);
    user.setEmail(existingUser.getEmail());
    action.setUser(user);
    action.setFrom("list");

    Integer originalVersionNumber = user.getVersion();
    log.debug("original version #: " + originalVersionNumber);

    MockHttpServletRequest request = new MockHttpServletRequest();
    request.addParameter("encryptPass", "true");
    ServletActionContext.setRequest(request);

    assertEquals("input", action.save());
    assertNotNull(action.getUser());
    assertEquals(originalVersionNumber, user.getVersion());
    assertTrue(action.hasActionErrors());
  }
  @RequestMapping(method = RequestMethod.POST)
  public String onSubmit(
      final User user,
      final BindingResult errors,
      final HttpServletRequest request,
      final HttpServletResponse response)
      throws Exception {
    if (request.getParameter("cancel") != null) {
      return getCancelView();
    }

    if (validator != null) { // validator is null during testing
      validator.validate(user, errors);

      if (StringUtils.isBlank(user.getPassword())) {
        errors.rejectValue(
            "password",
            "errors.required",
            new Object[] {getText("user.password", request.getLocale())},
            "Password is a required field.");
      }

      if (errors.hasErrors()) {
        return "signup";
      }
    }

    final Locale locale = request.getLocale();

    user.setEnabled(true);

    // Set the default user role on this new user
    user.addRole(roleManager.getRole(Constants.USER_ROLE));

    // unencrypted users password to log in user automatically
    final String password = user.getPassword();

    try {
      this.getUserManager().saveUser(user);
    } catch (final AccessDeniedException ade) {
      // thrown by UserSecurityAdvice configured in aop:advisor userManagerSecurity
      log.warn(ade.getMessage());
      response.sendError(HttpServletResponse.SC_FORBIDDEN);
      return null;
    } catch (final UserExistsException e) {
      errors.rejectValue(
          "username",
          "errors.existing.user",
          new Object[] {user.getUsername(), user.getEmail()},
          "duplicate user");

      return "signup";
    }

    saveMessage(request, getText("user.registered", user.getUsername(), locale));
    request.getSession().setAttribute(Constants.REGISTERED, Boolean.TRUE);

    // log user in automatically
    final UsernamePasswordAuthenticationToken auth =
        new UsernamePasswordAuthenticationToken(
            user.getUsername(), password, user.getAuthorities());
    auth.setDetails(user);
    SecurityContextHolder.getContext().setAuthentication(auth);

    // Send user an e-mail
    if (log.isDebugEnabled()) {
      log.debug("Sending user '" + user.getUsername() + "' an account information e-mail");
    }

    // Send an account information e-mail
    message.setSubject(getText("signup.email.subject", locale));

    try {
      sendUserMessage(
          user, getText("signup.email.message", locale), RequestUtil.getAppURL(request));
    } catch (final MailException me) {
      saveError(request, me.getMostSpecificCause().getMessage());
    }

    return getSuccessView();
  }