/**
   * 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 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 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"));
  }
示例#4
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);
  }
  @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();
  }