Exemple #1
0
  /**
   * Returns user of the change set.
   *
   * @param csAuthor user name.
   * @param csAuthorEmail user email.
   * @param createAccountBasedOnEmail true if create new user based on committer's email.
   * @return {@link User}
   */
  public User findOrCreateUser(
      String csAuthor, String csAuthorEmail, boolean createAccountBasedOnEmail) {
    User user;
    if (createAccountBasedOnEmail) {
      user = User.get(csAuthorEmail, false);

      if (user == null) {
        try {
          user = User.get(csAuthorEmail, true);
          user.setFullName(csAuthor);
          user.addProperty(new Mailer.UserProperty(csAuthorEmail));
          user.save();
        } catch (IOException e) {
          // add logging statement?
        }
      }
    } else {
      user = User.get(csAuthor, false);

      if (user == null) user = User.get(csAuthorEmail.split("@")[0], true);
    }
    // set email address for user if none is already available
    if (fixEmpty(csAuthorEmail) != null && !isMailerPropertySet(user)) {
      try {
        user.addProperty(new Mailer.UserProperty(csAuthorEmail));
      } catch (IOException e) {
        // ignore error
      }
    }
    return user;
  }
Exemple #2
0
  /** Accepts submission from the configuration page. */
  public void doConfigSubmit(StaplerRequest req, StaplerResponse rsp)
      throws IOException, ServletException, FormException {
    checkPermission(Hudson.ADMINISTER);

    fullName = req.getParameter("fullName");
    description = req.getParameter("description");

    JSONObject json = req.getSubmittedForm();

    List<UserProperty> props = new ArrayList<UserProperty>();
    int i = 0;
    for (UserPropertyDescriptor d : UserProperty.all()) {
      UserProperty p = getProperty(d.clazz);

      JSONObject o = json.optJSONObject("userProperty" + (i++));
      if (o != null) {
        if (p != null) {
          p = p.reconfigure(req, o);
        } else {
          p = d.newInstance(req, o);
        }
        p.setUser(this);
      }

      if (p != null) props.add(p);
    }
    this.properties = props;

    save();

    rsp.sendRedirect(".");
  }
Exemple #3
0
  /** Accepts the new description. */
  public synchronized void doSubmitDescription(StaplerRequest req, StaplerResponse rsp)
      throws IOException, ServletException {
    checkPermission(Hudson.ADMINISTER);

    description = req.getParameter("description");
    save();

    rsp.sendRedirect("."); // go to the top page
  }
Exemple #4
0
 /** Updates the user object by adding a property. */
 public synchronized void addProperty(UserProperty p) throws IOException {
   UserProperty old = getProperty(p.getClass());
   List<UserProperty> ps = new ArrayList<UserProperty>(properties);
   if (old != null) ps.remove(old);
   ps.add(p);
   p.setUser(this);
   properties = ps;
   save();
 }
  /**
   * @return <code>null</code> if failed. The browser is already redirected to retry by the time
   *     this method returns. a valid {@link User} object if the user creation was successful.
   */
  private User createAccount(StaplerRequest req, StaplerResponse rsp, String formView)
      throws ServletException, IOException {

    SignupInfo si = new SignupInfo(req);

    String puid = authenticateInWwpass(si.ticket, certFile, keyFile);

    try {
      if (loadUserByUsername(puid) != null) {
        si.errorMessages.add(Messages.WwpassSecurityRealm_PuidIsAlreadyTaken());
      }
    } catch (UsernameNotFoundException e) {

    }

    if (si.nickname == null || si.nickname.length() == 0)
      si.errorMessages.add(Messages.WwpassSecurityRealm_NicknameIsRequired());
    else {
      User user = User.get(si.nickname, false);
      if (null != user)
        if (user.getProperty(WwpassIdentity.class) != null)
          si.errorMessages.add(Messages.WwpassSecurityRealm_NicknameIsAlreadyTaken());
    }

    if (si.fullname == null || si.fullname.length() == 0)
      si.errorMessages.add(Messages.WwpassSecurityRealm_FullnameIsRequired());
    else {
      User user = User.get(si.fullname, false);
      if (null != user)
        if (user.getProperty(WwpassIdentity.class) != null)
          si.errorMessages.add(Messages.WwpassSecurityRealm_FullnameIsAlreadyTaken());
    }

    if (si.email == null || !si.email.contains("@"))
      si.errorMessages.add(Messages.WwpassSecurityRealm_InvalidEmailAddress());

    if (!si.errorMessages.isEmpty()) {
      // failed. ask the user to try again.
      req.setAttribute("data", si);
      req.getView(this, formView).forward(req, rsp);
      return null;
    }

    // register the user
    WwpassIdentity id = new WwpassIdentity(puid);
    id.populate(si);

    User user = createAccount(id);
    id.updateProfile(user);

    user.save();
    return user;
  }
    /**
     * @return
     *      null if failed. The browser is already redirected to retry by the time this method returns.
     *      a valid {@link User} object if the user creation was successful.
     */
    private User createAccount(StaplerRequest req, StaplerResponse rsp, boolean selfRegistration, String formView) throws ServletException, IOException {
        // form field validation
        // this pattern needs to be generalized and moved to stapler
        SignupInfo si = new SignupInfo(req);

        if(selfRegistration && !validateCaptcha(si.captcha))
            si.errorMessage = "Text didn't match the word shown in the image";

        if(si.password1 != null && !si.password1.equals(si.password2))
            si.errorMessage = "Password didn't match";

        if(!(si.password1 != null && si.password1.length() != 0))
            si.errorMessage = "Password is required";

        if(si.username==null || si.username.length()==0)
            si.errorMessage = "User name is required";
        else {
            User user = User.get(si.username, false);
            if (null != user)
                si.errorMessage = "User name is already taken";
        }

        if(si.fullname==null || si.fullname.length()==0)
            si.fullname = si.username;

        if(si.email==null || !si.email.contains("@"))
            si.errorMessage = "Invalid e-mail address";

        if(si.errorMessage!=null) {
            // failed. ask the user to try again.
            req.setAttribute("data",si);
            req.getView(this, formView).forward(req,rsp);
            return null;
        }

        // register the user
        User user = createAccount(si.username,si.password1);
        user.setFullName(si.fullname);
        try {
            // legacy hack. mail support has moved out to a separate plugin
            Class<?> up = Jenkins.getInstance().pluginManager.uberClassLoader.loadClass("hudson.tasks.Mailer.UserProperty");
            Constructor<?> c = up.getDeclaredConstructor(String.class);
            user.addProperty((UserProperty)c.newInstance(si.email));
        } catch (RuntimeException e) {
            throw e;
        } catch (Exception e) {
            LOGGER.log(Level.WARNING, "Failed to set the e-mail address",e);
        }
        user.save();
        return user;
    }
  /** Try to make this user a super-user */
  private void tryToMakeAdmin(User u) throws IOException {
    WwpassIdentity p = u.getProperty(WwpassIdentity.class);
    p.activate();
    u.save();
    AuthorizationStrategy as = Jenkins.getInstance().getAuthorizationStrategy();

    for (PermissionAdder adder : Jenkins.getInstance().getExtensionList(PermissionAdder.class)) {
      if (adder.add(as, u, Jenkins.ADMINISTER)) {
        return;
      }
    }
    LOGGER.severe(
        "Admin permission wasn't added for user: "******", ID: " + u.getId());
  }
 /**
  * Add the score to the users that have committed code in the change set
  *
  * @param score the score that the build was worth
  * @param accountableBuilds the builds for which the {@code score} is awarded for.
  * @throws IOException thrown if the property could not be added to the user object.
  * @return true, if any user scores was updated; false, otherwise
  */
 private boolean updateUserScores(
     Set<User> players, double score, List<AbstractBuild<?, ?>> accountableBuilds)
     throws IOException {
   if (score != 0) {
     for (User user : players) {
       UserScoreProperty property = user.getProperty(UserScoreProperty.class);
       if (property == null) {
         property = new UserScoreProperty();
         user.addProperty(property);
       }
       if (property.isParticipatingInGame()) {
         property.setScore(property.getScore() + score);
         property.rememberAccountableBuilds(accountableBuilds, score);
       }
       user.save();
     }
   }
   return (!players.isEmpty());
 }
    /**
     * @return
     *      null if failed. The browser is already redirected to retry by the time this method returns.
     *      a valid {@link User} object if the user creation was successful.
     */
    private User createAccount(StaplerRequest req, StaplerResponse rsp, boolean selfRegistration, String formView) throws ServletException, IOException {
        // form field validation
        // this pattern needs to be generalized and moved to stapler
        SignupInfo si = new SignupInfo(req);

        if(selfRegistration && !validateCaptcha(si.captcha))
            si.errorMessage = "Text didn't match the word shown in the image";

        if(si.password1 != null && !si.password1.equals(si.password2))
            si.errorMessage = "Password didn't match";

        if(!(si.password1 != null && si.password1.length() != 0))
            si.errorMessage = "Password is required";

        if(si.username==null || si.username.length()==0)
            si.errorMessage = "User name is required";
        else {
            User user = User.get(si.username);
            if(user.getProperty(Details.class)!=null)
                si.errorMessage = "User name is already taken. Did you forget the password?";
        }

        if(si.fullname==null || si.fullname.length()==0)
            si.fullname = si.username;

        if(si.email==null || !si.email.contains("@"))
            si.errorMessage = "Invalid e-mail address";

        if(si.errorMessage!=null) {
            // failed. ask the user to try again.
            req.setAttribute("data",si);
            req.getView(this, formView).forward(req,rsp);
            return null;
        }

        // register the user
        User user = createAccount(si.username,si.password1);
        user.addProperty(new Mailer.UserProperty(si.email));
        user.setFullName(si.fullname);
        user.save();
        return user;
    }
  /**
   * Tests {@link Team#doImportViewsSubmit(String, org.kohsuke.stapler.StaplerRequest,
   * org.kohsuke.stapler.StaplerResponse)}.
   *
   * @throws Exception if so
   */
  public void testDoImportViewsSubmit() throws Exception {
    FreeStyleProject p = createFreeStyleProject();
    User user = User.get("bob", true);
    MyViewsProperty property = user.getProperty(MyViewsProperty.class);
    ListView view1 = new ListView("view1");
    view1.add(p);
    property.addView(view1);
    ListView view2 = new ListView("view2");
    property.addView(view2);
    user.save();

    PluginImpl.getInstance().addTeam(new Team("Team1", "Description"));
    Team team = PluginImpl.getInstance().getTeams().get("Team1");
    StaplerRequest request = mock(StaplerRequest.class);
    StaplerResponse response = mock(StaplerResponse.class);

    team.doImportViewsSubmit(user.getId(), request, response);

    verify(response).sendRedirect2(Matchers.contains(team.getUrl()));

    TeamViewsProperty views = team.getProperty(TeamViewsProperty.class);
    Collection<View> collection = views.getViews();
    assertEquals(3, collection.size());

    boolean found1 = false;
    boolean found2 = false;
    for (View next : collection) {
      if (next.getViewName().equals("view1")) {
        found1 = true;
        assertNotSame(view1, next);
        assertEquals(1, next.getItems().size());
      } else if (next.getViewName().equals("view2")) {
        found2 = true;
        assertNotSame(view2, next);
      }
    }
    assertTrue(found1);
    assertTrue(found2);
  }