Beispiel #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;
  }
  /** This is where the user comes back to at the end of the OpenID redirect ping-pong. */
  public HttpResponse doFinishLogin(StaplerRequest request) throws IOException {

    String code = request.getParameter("code");

    if (code == null || code.trim().length() == 0) {
      Log.info("doFinishLogin: missing code.");
      return HttpResponses.redirectToContextRoot();
    }

    Log.info("test");

    HttpPost httpost =
        new HttpPost(
            githubUri
                + "/login/oauth/access_token?"
                + "client_id="
                + clientID
                + "&"
                + "client_secret="
                + clientSecret
                + "&"
                + "code="
                + code);

    DefaultHttpClient httpclient = new DefaultHttpClient();

    org.apache.http.HttpResponse response = httpclient.execute(httpost);

    HttpEntity entity = response.getEntity();

    String content = EntityUtils.toString(entity);

    // When HttpClient instance is no longer needed,
    // shut down the connection manager to ensure
    // immediate deallocation of all system resources
    httpclient.getConnectionManager().shutdown();

    String accessToken = extractToken(content);

    if (accessToken != null && accessToken.trim().length() > 0) {

      String githubServer = githubUri.replaceFirst("http.*\\/\\/", "");

      // only set the access token if it exists.
      GithubAuthenticationToken auth = new GithubAuthenticationToken(accessToken, githubServer);
      SecurityContextHolder.getContext().setAuthentication(auth);

      GHUser self = auth.getGitHub().getMyself();
      User u = User.current();
      u.setFullName(self.getName());
      u.addProperty(new Mailer.UserProperty(self.getEmail()));
    } else {
      Log.info("Github did not return an access token.");
    }

    String referer = (String) request.getSession().getAttribute(REFERER_ATTRIBUTE);
    if (referer != null) return HttpResponses.redirectTo(referer);
    return HttpResponses
        .redirectToContextRoot(); // referer should be always there, but be defensive
  }
    /**
     * @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;
    }
Beispiel #4
0
  public TestGitRepo(String name, File tmpDir, TaskListener listener)
      throws IOException, InterruptedException {
    this.name = name;
    this.listener = listener;

    envVars = new EnvVars();

    gitDir = tmpDir;
    User john = User.get(johnDoe.getName(), true);
    UserProperty johnsMailerProperty = new Mailer.UserProperty(johnDoe.getEmailAddress());
    john.addProperty(johnsMailerProperty);

    User jane = User.get(janeDoe.getName(), true);
    UserProperty janesMailerProperty = new Mailer.UserProperty(janeDoe.getEmailAddress());
    jane.addProperty(janesMailerProperty);

    // initialize the git interface.
    gitDirPath = new FilePath(gitDir);
    git = Git.with(listener, envVars).in(gitDir).getClient();

    // finally: initialize the repo
    git.init();
  }
  @Test
  public void testConvertRecipientList_userName()
      throws AddressException, IOException, UnsupportedEncodingException {
    Mailer.descriptor().setDefaultSuffix("@gmail.com");
    User u = User.get("advantiss");
    u.setFullName("Peter Samoshkin");
    Mailer.UserProperty prop = new Mailer.UserProperty("*****@*****.**");
    u.addProperty(prop);

    InternetAddress[] internetAddresses =
        emailRecipientUtils
            .convertRecipientString("advantiss", envVars)
            .toArray(new InternetAddress[0]);

    assertEquals(1, internetAddresses.length);
    assertEquals("*****@*****.**", internetAddresses[0].getAddress());
  }
 /**
  * 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;
    }
 /** Creates a new user account by registering a password to the user. */
 public User createAccount(WwpassIdentity id) throws IOException {
   User user = User.get(id.getNickname());
   user.addProperty(id);
   return user;
 }
 /**
  * Creates a new user account by registering a password to the user.
  */
 public User createAccount(String userName, String password) throws IOException {
     User user = User.get(userName);
     user.addProperty(Details.fromPlainPassword(password));
     return user;
 }