/** 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
  }
  private void build(GHPullRequest pr, GHUser buildRequester, TriggerCause cause)
      throws IOException {
    ArrayList<ParameterValue> parameters = getDefaultBuildParameters();
    parameters.add(new StringParameterValue(PR_COMMIT, pr.getHead().getSha()));
    parameters.add(new StringParameterValue(PR_BRANCH, pr.getHead().getRef()));
    if (buildRequester != null) {
      parameters.add(new StringParameterValue(BUILD_REQUESTER, buildRequester.getLogin()));
      if (buildRequester.getEmail() != null) {
        parameters.add(new StringParameterValue(BUILD_REQUEST_EMAIL, buildRequester.getEmail()));
      }
    }
    parameters.add(new StringParameterValue(PR_NUMBER, String.valueOf(pr.getNumber())));
    parameters.add(new StringParameterValue(PR_MERGE_BRANCH, pr.getBase().getRef()));
    parameters.add(new StringParameterValue(PR_OWNER, pr.getUser().getLogin()));
    if (pr.getUser().getEmail() != null) {
      parameters.add(new StringParameterValue(PR_OWNER_EMAIL, pr.getUser().getEmail()));
    }
    final StringParameterValue prUrlParam =
        new StringParameterValue(PR_URL, pr.getHtmlUrl().toString());
    parameters.add(prUrlParam);

    project.scheduleBuild2(
        project.getQuietPeriod(),
        cause,
        new ParametersAction(parameters),
        getBuildData(prUrlParam),
        new RevisionParameterAction(pr.getHead().getSha()));
  }
예제 #3
0
 private void modifyCollaborators(Collection<GHUser> users, String method) throws IOException {
   verifyMine();
   for (GHUser user : users) {
     new Requester(root)
         .method(method)
         .to("/repos/" + owner.login + "/" + name + "/collaborators/" + user.getLogin());
   }
 }
 private GHRepository mockGHRepository(String ownerName, String name) throws IOException {
   GHRepository ghRepository = PowerMockito.mock(GHRepository.class);
   GHUser ghUser = PowerMockito.mock(GHUser.class);
   PowerMockito.when(ghUser.getLogin()).thenReturn(ownerName);
   PowerMockito.when(ghRepository.getOwner()).thenReturn(ghUser);
   PowerMockito.when(ghRepository.getName()).thenReturn(name);
   return ghRepository;
 }
예제 #5
0
    /**
     * @param newName
     *      If not null, rename a epository after a fork.
     */
    private void forkGitHub(String channel, String owner, String repo, String newName) {
        try {
            sendMessage(channel, "Forking "+repo);

            GitHub github = GitHub.connect();
            GHUser user = github.getUser(owner);
            if (user==null) {
                sendMessage(channel,"No such user: "******"No such repository: "+repo);
                return;
            }

            GHOrganization org = github.getOrganization("jenkinsci");
            GHRepository r;
            try {
                r = orig.forkTo(org);
            } catch (IOException e) {
                // we started seeing 500 errors, presumably due to time out.
                // give it a bit of time, and see if the repository is there
                System.out.println("GitHub reported that it failed to fork "+owner+"/"+repo+". But we aren't trusting");
                Thread.sleep(3000);
                r = org.getRepository(repo);
                if (r==null)
                    throw e;
            }
            if (newName!=null)
                r.renameTo(newName);

            // GitHub adds a lot of teams to this repo by default, which we don't want
            Set<GHTeam> legacyTeams = r.getTeams();

            GHTeam t = getOrCreateRepoLocalTeam(org, r);
            t.add(user);    // the user immediately joins this team

            // the Everyone group gets access to this new repository, too.
            GHTeam everyone = org.getTeams().get("Everyone");
            everyone.add(r);

            setupRepository(r);

            sendMessage(channel, "Created https://github.com/jenkinsci/" + (newName != null ? newName : repo));

            // remove all the existing teams
            for (GHTeam team : legacyTeams)
                team.remove(r);

        } catch (InterruptedException e) {
            sendMessage(channel,"Failed to fork a repository: "+e.getMessage());
            e.printStackTrace();
        } catch (IOException e) {
            sendMessage(channel,"Failed to fork a repository: "+e.getMessage());
            e.printStackTrace();
        }
    }
예제 #6
0
 /** Checks if this organization has the specified user as a public member. */
 public boolean hasPublicMember(GHUser user) {
   try {
     root.retrieve().to("/orgs/" + login + "/public_members/" + user.getLogin());
     return true;
   } catch (IOException ignore) {
     return false;
   }
 }
예제 #7
0
 /** Gets the collaborators on this repository. This set always appear to include the owner. */
 @WithBridgeMethods(Set.class)
 public GHPersonSet<GHUser> getCollaborators() throws IOException {
   return new GHPersonSet<GHUser>(
       GHUser.wrap(
           root.retrieve()
               .to("/repos/" + owner.login + "/" + name + "/collaborators", GHUser[].class),
           root));
 }
예제 #8
0
 /**
  * Gets the names of the collaborators on this repository. This method deviates from the principle
  * of this library but it works a lot faster than {@link #getCollaborators()}.
  */
 public Set<String> getCollaboratorNames() throws IOException {
   Set<String> r = new HashSet<String>();
   for (GHUser u :
       GHUser.wrap(
           root.retrieve()
               .to("/repos/" + owner.login + "/" + name + "/collaborators", GHUser[].class),
           root)) r.add(u.login);
   return r;
 }
  private boolean isWhitelisted(GHUser user, GitHub gitHub) throws IOException {
    if (whitelist == null) {
      return true;
    }

    if (whitelist.contains(user.getLogin())) {
      return true;
    }

    Set<String> whitelistOrgNames = gitHub.getMyOrganizations().keySet();
    whitelistOrgNames.retainAll(whitelist);
    for (String name : whitelistOrgNames) {
      GHOrganization organization = gitHub.getOrganization(name);
      if (organization.hasMember(user)) {
        return true;
      }
    }
    return false;
  }
예제 #10
0
 /*package*/ static GHUser[] wrap(GHUser[] users, GitHub root) {
   for (GHUser f : users) f.root = root;
   return users;
 }
예제 #11
0
 /**
  * Remove a member of the organisation - which will remove them from all teams, and remove their
  * access to the organization’s repositories.
  */
 public void remove(GHUser user) throws IOException {
   root.retrieve().method("DELETE").to("/orgs/" + login + "/members/" + user.getLogin());
 }
예제 #12
0
 /** Conceals the membership. */
 public void conceal(GHUser u) throws IOException {
   root.retrieve().method("DELETE").to("/orgs/" + login + "/public_members/" + u.getLogin(), null);
 }
예제 #13
0
 /** Publicizes the membership. */
 public void publicize(GHUser u) throws IOException {
   root.retrieve().method("PUT").to("/orgs/" + login + "/public_members/" + u.getLogin(), null);
 }
  void handle(GHEventPayload.IssueComment issueComment, GitHub gitHub) throws IOException {
    // check the trigger phrase
    PullRequestBuildTrigger trigger = project.getTrigger(PullRequestBuildTrigger.class);
    if (StringUtils.isBlank(trigger.getTriggerPhrase())) {
      if (LOGGER.isLoggable(Level.FINE)) {
        LOGGER.fine("No trigger phrase configured for project: " + project.getDisplayName());
      }
      return;
    }

    String issueUrl = issueComment.getIssue().getHtmlUrl().toString();
    if (!issueUrl.startsWith(gitHubRepositoryUrl)) {
      LOGGER.finest(
          MessageFormat.format(
              "GitHub issue {0} is not related to project {1}. "
                  + "GitHub project URL configured for project {1}: {2}",
              issueUrl, project.getFullName(), gitHubRepositoryUrl));

      return;
    }

    String commentBody = issueComment.getComment().getBody();
    if (!triggerPhrasePattern.matcher(commentBody).find()) {
      if (LOGGER.isLoggable(Level.FINE)) {
        LOGGER.fine("No trigger phrase matching on comment: " + commentBody);
      }
      return;
    }

    GHUser buildRequester = issueComment.getComment().getUser();
    if (!isWhitelisted(buildRequester, gitHub)) {
      LOGGER.info(
          MessageFormat.format(
              "GitHub user {0} is not in the whitelist of project {1}",
              buildRequester.getLogin(), project.getFullName()));

      return;
    }

    final int prNumber = issueComment.getIssue().getNumber();

    GHPullRequest pullRequest = issueComment.getRepository().getPullRequest(prNumber);
    // Updating PR to force the cache (if present) to refresh:
    pullRequest.setTitle(pullRequest.getTitle());

    pullRequest = issueComment.getRepository().getPullRequest(prNumber);

    if (LOGGER.isLoggable(Level.FINE)) {
      LOGGER.fine("ghPullRequest = " + getPullRequestAsString(pullRequest));
    }

    if (pullRequest.getState() == GHIssueState.OPEN) {
      PullRequestData pullRequestData =
          PullRequestManager.getInstance().addPullRequestData(pullRequest, project);

      cancelBuilds(pullRequestData);
      build(pullRequest, buildRequester, new TriggerCause(pullRequest, buildRequester));
    } else if (LOGGER.isLoggable(Level.FINE)) {
      LOGGER.fine(
          MessageFormat.format(
              "Pull request {0} is not opened, no build is triggered",
              pullRequest.getHtmlUrl().toString()));
    }
  }
예제 #15
0
 /** Conceals the membership. */
 public void conceal(GHUser u) throws IOException {
   root.retrieveWithAuth3("/orgs/" + login + "/public_members/" + u.getLogin(), null, "DELETE");
 }
예제 #16
0
 /** Publicizes the membership. */
 public void publicize(GHUser u) throws IOException {
   root.retrieveWithAuth3("/orgs/" + login + "/public_members/" + u.getLogin(), null, "PUT");
 }