org.kohsuke.github.GHUser Java Examples

The following examples show how to use org.kohsuke.github.GHUser. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DynamicProjectRepositoryTest.java    From DotCi with MIT License 6 votes vote down vote up
@Test
@LocalData
public void should_create_a_new_project() throws Exception {
    GHRepository ghRepository = mock(GHRepository.class);
    when(ghRepository.getHtmlUrl()).thenReturn(new URL("http://github.com/meow"));
    GHUser ghUser = mock(GHUser.class);
    when(ghUser.getLogin()).thenReturn("test_user");
    when(ghRepository.getOwner()).thenReturn(ghUser);
    when(ghRepository.getName()).thenReturn("test_job");

    int totalBefore = (int) repo.getDatastore().createQuery(DynamicProject.class).countAll();

    DynamicProject project = repo.createNewProject(ghRepository, "test", "username");
    assertNotNull(project);
    DynamicProject retrieved = repo.getProjectById(project.getId());
    assertNotNull(retrieved);
    int totalAfter = (int) repo.getDatastore().createQuery(DynamicProject.class).countAll();
    assertEquals(totalAfter, totalBefore + 1);
}
 
Example #2
Source File: LocalRepoUpdaterTest.java    From github-integration-plugin with MIT License 6 votes vote down vote up
@Before
public void setUp() throws Exception {
    localRepo = new GitHubPRRepository(remoteRepo);

    GHRepository headRepo = mock(GHRepository.class);
    when(headRepo.getOwnerName()).thenReturn("owner");

    when(commit.getRepository()).thenReturn(headRepo);


    when(remotePR.getUser()).thenReturn(new GHUser());
    when(remotePR.getHead()).thenReturn(commit);
    when(remotePR.getBase()).thenReturn(commit);
    when(remotePR.getRepository()).thenReturn(remoteRepo);
    when(remoteRepo.getIssue(Matchers.any(Integer.class))).thenReturn(new GHIssue());

    when(commit.getSha()).thenReturn(SHA_REMOTE);
}
 
Example #3
Source File: MembershipChecker.java    From github-oauth-authorization-plugin with Apache License 2.0 6 votes vote down vote up
private boolean checkTeamMembershipUsingPersonalAccessToken(GHUser ghUser, AuthConfig authConfig, Map<String, List<String>> organizationAndTeamsAllowed) throws IOException {
    final GitHub gitHubForPersonalAccessToken = clientBuilder.from(authConfig.gitHubConfiguration());

    for (String organizationName : organizationAndTeamsAllowed.keySet()) {
        final GHOrganization organization = gitHubForPersonalAccessToken.getOrganization(organizationName);

        if (organization != null) {
            final List<String> allowedTeamsFromRole = organizationAndTeamsAllowed.get(organizationName);
            final Map<String, GHTeam> teamsFromGitHub = organization.getTeams();

            for (GHTeam team : teamsFromGitHub.values()) {
                if (allowedTeamsFromRole.contains(team.getName().toLowerCase()) && team.hasMember(ghUser)) {
                    LOG.info(format("[MembershipChecker] User `{0}` is a member of `{1}` team.", ghUser.getLogin(), team.getName()));
                    return true;
                }
            }
        }
    }

    return false;
}
 
Example #4
Source File: GitHubProvider.java    From gocd-oauth-login with Apache License 2.0 6 votes vote down vote up
@Override
public List<User> searchUser(GithubPluginSettings pluginSettings, String searchTerm) {
    List<User> users = new ArrayList<User>();
    try {
        GitHub github = getGitHub(pluginSettings);

        PagedSearchIterable<GHUser> githubSearchResults = github.searchUsers().q(searchTerm).list();
        int count = 0;
        for (GHUser githubSearchResult : githubSearchResults) {
            users.add(new User(githubSearchResult.getLogin(), githubSearchResult.getName(), githubSearchResult.getEmail()));
            count++;

            if (count == 10) {
                break;
            }
        }
    } catch (Exception e) {
        LOGGER.warn("Error occurred while trying to perform user search", e);
    }
    return users;
}
 
Example #5
Source File: GetRolesExecutor.java    From github-oauth-authorization-plugin with Apache License 2.0 6 votes vote down vote up
@Override
public GoPluginApiResponse execute() throws IOException {
    if (request.getRoles().isEmpty()) {
        LOG.debug("[Get User Roles] Server sent empty roles config. Nothing to do!.");
        return DefaultGoPluginApiResponse.success("[]");
    }

    GitHub gitHub = clientBuilder.from(request.getAuthConfig().gitHubConfiguration());
    GHUser user = gitHub.getUser(request.getUsername());

    if (user == null) {
        LOG.error(format("[Get User Roles] User %s does not exist in GitHub.", request.getUsername()));
        return DefaultGoPluginApiResponse.error("");
    }

    List<String> roles = gitHubAuthorizer.authorize(user, request.getAuthConfig(), request.getRoles());

    LOG.debug(format("[Get User Roles] User %s has %s roles.", request.getUsername(), roles));
    return DefaultGoPluginApiResponse.success(GSON.toJson(roles));
}
 
Example #6
Source File: GitHubProvider.java    From gocd-oauth-login with Apache License 2.0 6 votes vote down vote up
private boolean isAMemberOfOrganization(GithubPluginSettings pluginSettings, User user) {
    try {
        GitHub github = getGitHub(pluginSettings);
        GHUser ghUser = github.getUser(user.getUsername());

        if(ghUser == null) return false;

        for(String orgName: pluginSettings.getGithubOrganizations()) {
            GHOrganization organization = github.getOrganization(orgName);

            if(organization != null && ghUser.isMemberOf(organization)){
                return true;
            }
        }
    } catch (Exception e) {
        LOGGER.warn("Error occurred while trying to check if user is member of organization", e);
    }
    return false;
}
 
Example #7
Source File: GetRolesExecutorTest.java    From github-oauth-authorization-plugin with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldReturnSuccessResponseWithRoles() throws IOException, JSONException {
    GitHub gitHub = mock(GitHub.class);
    GHUser ghUser = mock(GHUser.class);

    when(clientBuilder.from(request.getAuthConfig().gitHubConfiguration())).thenReturn(gitHub);
    when(gitHub.getUser("bob")).thenReturn(ghUser);
    when(request.getRoles()).thenReturn(rolesWithName("blackbird", "super-admin", "view"));
    when(authorizer.authorize(ghUser, request.getAuthConfig(), request.getRoles())).thenReturn(Arrays.asList("blackbird", "super-admin"));

    GoPluginApiResponse response = executor.execute();

    assertThat(response.responseCode(), is(200));
    JSONAssert.assertEquals("[\"blackbird\",\"super-admin\"]", response.responseBody(), true);

    InOrder inOrder = inOrder(clientBuilder, gitHub, authorizer);
    inOrder.verify(clientBuilder).from(request.getAuthConfig().gitHubConfiguration());
    inOrder.verify(gitHub).getUser(request.getUsername());
    inOrder.verify(authorizer).authorize(ghUser, request.getAuthConfig(), request.getRoles());
}
 
Example #8
Source File: GithubConnector.java    From apollo with Apache License 2.0 6 votes vote down vote up
public Optional<CommitDetails> getCommitDetails(String githubRepo, String sha) {
    try {
        logger.info("Getting commit details for sha {} on url {}", sha, githubRepo);
        GHCommit commit = gitHub.getRepository(githubRepo).getCommit(sha);

        GHUser author = commit.getAuthor();
        logger.info("1) Author of commit sha {} is {}", sha, author);
        String committerName = (author == null) ? null : author.getName();
        if (committerName == null || committerName.isEmpty()) {
            logger.info("2) Committer name of commit sha {} is {}", sha, committerName);
            committerName = author.getLogin();
            logger.info("3) Committer name of commit sha {} is {}", sha, committerName);
        }

        CommitDetails commitDetails = new CommitDetails(sha, commit.getHtmlUrl().toString(),
                commit.getCommitShortInfo().getMessage(), commit.getCommitDate(), commit.getLastStatus(),
                author.getAvatarUrl(), committerName);
        logger.info("CommitDetails: {}", commitDetails);
        return Optional.of(commitDetails);
    } catch (IOException e) {
        logger.warn("Could not get commit details from Github!", e);
        return Optional.empty();
    }
}
 
Example #9
Source File: GitHubPRDescriptionEventTest.java    From github-integration-plugin with MIT License 5 votes vote down vote up
private void causeCreationExpectations() throws IOException {
    GHUser mockUser = mock(GHUser.class);
    GHCommitPointer mockPointer = mock(GHCommitPointer.class);

    GHRepository headRepo = mock(GHRepository.class);
    when(headRepo.getOwnerName()).thenReturn("owner");

    when(mockPointer.getRepository()).thenReturn(headRepo);

    when(remotePr.getUser()).thenReturn(mockUser);
    when(remotePr.getHead()).thenReturn(mockPointer);
    when(remotePr.getBase()).thenReturn(mockPointer);
}
 
Example #10
Source File: GitHubNotificationPipelineStepTest.java    From pipeline-githubnotify-step-plugin with MIT License 5 votes vote down vote up
@Test
public void buildWithFolderCredentials() throws Exception {

    GitHubBuilder ghb = PowerMockito.mock(GitHubBuilder.class);
    PowerMockito.when(ghb.withProxy(Matchers.<Proxy>anyObject())).thenReturn(ghb);
    PowerMockito.when(ghb.withOAuthToken(anyString(), anyString())).thenReturn(ghb);
    PowerMockito.whenNew(GitHubBuilder.class).withNoArguments().thenReturn(ghb);
    GitHub gh = PowerMockito.mock(GitHub.class);
    PowerMockito.when(ghb.build()).thenReturn(gh);
    PowerMockito.when(gh.isCredentialValid()).thenReturn(true);
    GHRepository repo = PowerMockito.mock(GHRepository.class);
    GHUser user = PowerMockito.mock(GHUser.class);
    GHCommit commit = PowerMockito.mock(GHCommit.class);
    PowerMockito.when(user.getRepository(anyString())).thenReturn(repo);
    PowerMockito.when(gh.getUser(anyString())).thenReturn(user);
    PowerMockito.when((repo.getCommit(anyString()))).thenReturn(commit);

    Folder f = jenkins.jenkins.createProject(Folder.class, "folder" + jenkins.jenkins.getItems().size());
    CredentialsStore folderStore = getFolderStore(f);
    folderStore.addCredentials(Domain.global(),
            new DummyCredentials(CredentialsScope.GLOBAL, "user", "password"));

    WorkflowJob p = f.createProject(WorkflowJob.class, "p");
    p.setDefinition(new CpsFlowDefinition(
            "githubNotify account: 'raul-arabaolaza', context: 'ATH Results', " +
                    "credentialsId: 'dummy', description: 'All tests are OK', " +
                    "repo: 'acceptance-test-harness', sha: '0b5936eb903d439ac0c0bf84940d73128d5e9487', " +
                    "status: 'SUCCESS', targetUrl: 'http://www.cloudbees.com'"
    ));
    WorkflowRun b1 = p.scheduleBuild2(0).waitForStart();
    jenkins.assertBuildStatus(Result.SUCCESS, jenkins.waitForCompletion(b1));
}
 
Example #11
Source File: GitHubNotificationPipelineStepTest.java    From pipeline-githubnotify-step-plugin with MIT License 5 votes vote down vote up
@Test
public void buildEnterprise() throws Exception {

    GitHubBuilder ghb = PowerMockito.mock(GitHubBuilder.class);
    PowerMockito.when(ghb.withProxy(Matchers.<Proxy>anyObject())).thenReturn(ghb);
    PowerMockito.when(ghb.withOAuthToken(anyString(), anyString())).thenReturn(ghb);
    PowerMockito.when(ghb.withEndpoint("https://api.example.com")).thenReturn(ghb);
    PowerMockito.whenNew(GitHubBuilder.class).withNoArguments().thenReturn(ghb);
    GitHub gh = PowerMockito.mock(GitHub.class);
    PowerMockito.when(ghb.build()).thenReturn(gh);
    PowerMockito.when(gh.isCredentialValid()).thenReturn(true);
    GHRepository repo = PowerMockito.mock(GHRepository.class);
    GHUser user = PowerMockito.mock(GHUser.class);
    GHCommit commit = PowerMockito.mock(GHCommit.class);
    PowerMockito.when(user.getRepository(anyString())).thenReturn(repo);
    PowerMockito.when(gh.getUser(anyString())).thenReturn(user);
    PowerMockito.when((repo.getCommit(anyString()))).thenReturn(commit);

    Credentials dummy = new DummyCredentials(CredentialsScope.GLOBAL, "user", "password");
    SystemCredentialsProvider.getInstance().getCredentials().add(dummy);

    WorkflowJob p = jenkins.createProject(WorkflowJob.class, "p");
    p.setDefinition(new CpsFlowDefinition(
            "githubNotify account: 'raul-arabaolaza', context: 'ATH Results', " +
                    "credentialsId: 'dummy', description: 'All tests are OK', " +
                    "repo: 'acceptance-test-harness', sha: '0b5936eb903d439ac0c0bf84940d73128d5e9487', " +
                    "status: 'SUCCESS', targetUrl: 'http://www.cloudbees.com', gitApiUrl:'https://api.example.com'"
    ));
    WorkflowRun b1 = p.scheduleBuild2(0).waitForStart();
    jenkins.assertBuildStatus(Result.SUCCESS, jenkins.waitForCompletion(b1));
}
 
Example #12
Source File: GitHubSCMNavigator.java    From github-branch-source-plugin with MIT License 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@NonNull
@Override
public List<Action> retrieveActions(@NonNull SCMNavigatorOwner owner,
                                    @CheckForNull SCMNavigatorEvent event,
                                    @NonNull TaskListener listener) throws IOException, InterruptedException {
    // TODO when we have support for trusted events, use the details from event if event was from trusted source
    listener.getLogger().printf("Looking up details of %s...%n", getRepoOwner());
    List<Action> result = new ArrayList<>();
    StandardCredentials credentials = Connector.lookupScanCredentials((Item)owner, getApiUri(), credentialsId);
    GitHub hub = Connector.connect(getApiUri(), credentials);
    try {
        Connector.checkApiRateLimit(listener, hub);
        GHUser u = hub.getUser(getRepoOwner());
        String objectUrl = u.getHtmlUrl() == null ? null : u.getHtmlUrl().toExternalForm();
        result.add(new ObjectMetadataAction(
                Util.fixEmpty(u.getName()),
                null,
                objectUrl)
        );
        result.add(new GitHubOrgMetadataAction(u));
        result.add(new GitHubLink("icon-github-logo", u.getHtmlUrl()));
        if (objectUrl == null) {
            listener.getLogger().println("Organization URL: unspecified");
        } else {
            listener.getLogger().printf("Organization URL: %s%n",
                    HyperlinkNote.encodeTo(objectUrl, StringUtils.defaultIfBlank(u.getName(), objectUrl)));
        }
        return result;
    } finally {
        Connector.release(hub);
    }
}
 
Example #13
Source File: GitHubPRUserRestriction.java    From github-integration-plugin with MIT License 5 votes vote down vote up
public boolean isUserMemberOfOrganization(String organisation, GHUser member) throws IOException {
    boolean orgHasMember;
    //TODO check for null member
    GitHub github = githubFor(URI.create(member.getHtmlUrl().toString()));
    orgHasMember = github.getOrganization(organisation).hasMember(member);
    LOGGER.debug("org.hasMember(member)? user:'{}' org: '{}' == '{}'",
            member.getLogin(), organisation, orgHasMember ? "yes" : "no");

    return orgHasMember;
}
 
Example #14
Source File: GitHubPRUserRestriction.java    From github-integration-plugin with MIT License 5 votes vote down vote up
private boolean isInWhitelistedOrg(@Nonnull GHUser user) {
    boolean ret = false;
    for (String organisation : orgsSet) {
        try {
            ret = isUserMemberOfOrganization(organisation, user);
            if (ret) {
                break;
            }
        } catch (IOException e) {
            LOGGER.error("Can't connect retrieve organization data from GitHub", e);
        }
    }
    return ret;
}
 
Example #15
Source File: GitHubPRUserRestriction.java    From github-integration-plugin with MIT License 5 votes vote down vote up
private static boolean isMyselfUser(GHUser user) {
    boolean ret = false;

    if (isNull(user)) {
        return false;
    }

    try {
        GitHub github = githubFor(URI.create(user.getHtmlUrl().toString()));
        ret = StringUtils.equals(user.getLogin(), github.getMyself().getLogin());
    } catch (IOException e) {
        LOGGER.error("Can't connect retrieve user data from GitHub", e);
    }
    return ret;
}
 
Example #16
Source File: GitHubPRCause.java    From github-integration-plugin with MIT License 5 votes vote down vote up
public GitHubPRCause(GitHubPRPullRequest pr,
                     GHUser triggerSender,
                     GitHubPRRepository localRepo,
                     boolean skip,
                     String reason) {
    this(pr.getHeadSha(), pr.getNumber(),
            pr.isMergeable(), pr.getBaseRef(), pr.getHeadRef(),
            pr.getUserEmail(), pr.getTitle(), pr.getHtmlUrl(), pr.getSourceRepoOwner(),
            pr.getLabels(),
            triggerSender, skip, reason, "", "", pr.getState());
    this.body = pr.getBody();
    if (localRepo != null) {
        withLocalRepo(localRepo);
    }
}
 
Example #17
Source File: GitHubPRCause.java    From github-integration-plugin with MIT License 5 votes vote down vote up
@Deprecated
public GitHubPRCause(GitHubPRPullRequest pr,
                     GHUser triggerSender,
                     boolean skip,
                     String reason) {
    this(pr, triggerSender, null, skip, reason);
}
 
Example #18
Source File: MembershipChecker.java    From github-oauth-authorization-plugin with Apache License 2.0 5 votes vote down vote up
public boolean isAMemberOfAtLeastOneOrganization(GHUser ghUser, AuthConfig authConfig, List<String> organizationsAllowed) throws IOException {
    if (organizationsAllowed.isEmpty()) {
        LOG.debug("[MembershipChecker] No organizations provided.");
        return false;
    }

    return checkMembershipUsingPersonalAccessToken(ghUser, authConfig, organizationsAllowed);
}
 
Example #19
Source File: GitHubPRLabelRemovedEventTest.java    From github-integration-plugin with MIT License 5 votes vote down vote up
private void causeCreationExpectations() throws IOException {
    GHUser mockUser = mock(GHUser.class);
    GHCommitPointer mockPointer = mock(GHCommitPointer.class);
    when(mockPointer.getRepository()).thenReturn(headRepository);
    when(headRepository.getOwnerName()).thenReturn("owner");
    when(remotePr.getUser()).thenReturn(mockUser);
    when(remotePr.getHead()).thenReturn(mockPointer);
    when(remotePr.getBase()).thenReturn(mockPointer);
}
 
Example #20
Source File: GitHubPRLabelAddedEventTest.java    From github-integration-plugin with MIT License 5 votes vote down vote up
private void causeCreationExpectations() throws IOException {
    GHUser mockUser = mock(GHUser.class);
    GHCommitPointer mockPointer = mock(GHCommitPointer.class);

    when(remotePr.getUser()).thenReturn(mockUser);
    when(remotePr.getHead()).thenReturn(mockPointer);
    when(remotePr.getBase()).thenReturn(mockPointer);
}
 
Example #21
Source File: GitHubPRCommentEventTest.java    From github-integration-plugin with MIT License 5 votes vote down vote up
private void causeCreationExpectations() throws IOException {
    GHUser mockUser = mock(GHUser.class);
    GHCommitPointer mockPointer = mock(GHCommitPointer.class);
    GHRepository headRepo = mock(GHRepository.class);
    when(headRepo.getOwnerName()).thenReturn("owner");

    when(mockPointer.getRepository()).thenReturn(headRepo);
    when(remotePr.getUser()).thenReturn(mockUser);
    when(remotePr.getHead()).thenReturn(mockPointer);
    when(remotePr.getBase()).thenReturn(mockPointer);
}
 
Example #22
Source File: UserRestrictionFilterTest.java    From github-integration-plugin with MIT License 5 votes vote down vote up
@Test
public void shouldNotFilterWithNotRestrictedBranchRestriction() throws Exception {
    when(uRestr.isWhitelisted(any(GHUser.class))).thenReturn(true);

    assertThat("when allowed", 
            withUserRestriction(tlRule.getListener(), uRestr).apply(new GHPullRequest()), is(true));
}
 
Example #23
Source File: UserRestrictionFilterTest.java    From github-integration-plugin with MIT License 5 votes vote down vote up
@Test
public void shouldFilterWithRestrictedBranchRestriction() throws Exception {
    when(uRestr.isWhitelisted(any(GHUser.class))).thenReturn(false);

    assertThat("when not allowed",
            withUserRestriction(tlRule.getListener(), uRestr).apply(new GHPullRequest()), is(false));
}
 
Example #24
Source File: DynamicProjectRepositoryTest.java    From DotCi with MIT License 5 votes vote down vote up
@Test
@LocalData
public void should_check_if_a_project_exists() throws Exception {
    GHRepository ghRepository = mock(GHRepository.class);
    GHUser ghUser = mock(GHUser.class);
    when(ghUser.getLogin()).thenReturn("test_user");
    when(ghRepository.getOwner()).thenReturn(ghUser);
    when(ghRepository.getName()).thenReturn("test_job");

    assertTrue(repo.projectExists(ghRepository));
}
 
Example #25
Source File: GitHubNotificationPipelineStepTest.java    From pipeline-githubnotify-step-plugin with MIT License 5 votes vote down vote up
@Test
public void buildWithInferWithoutCredentialsMustFail() throws Exception {

    GitHubBuilder ghb = PowerMockito.mock(GitHubBuilder.class);
    PowerMockito.when(ghb.withProxy(Matchers.<Proxy>anyObject())).thenReturn(ghb);
    PowerMockito.when(ghb.withOAuthToken(anyString(), anyString())).thenReturn(ghb);
    PowerMockito.whenNew(GitHubBuilder.class).withNoArguments().thenReturn(ghb);
    GitHub gh = PowerMockito.mock(GitHub.class);
    PowerMockito.when(ghb.build()).thenReturn(gh);
    PowerMockito.when(gh.isCredentialValid()).thenReturn(true);
    GHRepository repo = PowerMockito.mock(GHRepository.class);
    GHUser user = PowerMockito.mock(GHUser.class);
    PowerMockito.when(user.getRepository(anyString())).thenReturn(repo);
    PowerMockito.when(gh.getUser(anyString())).thenReturn(user);
    PowerMockito.when((repo.getCommit(anyString()))).thenReturn(null);

    Credentials dummy = new DummyCredentials(CredentialsScope.GLOBAL, "user", "password");
    SystemCredentialsProvider.getInstance().getCredentials().add(dummy);

    WorkflowJob p = jenkins.createProject(WorkflowJob.class, "p");
    p.setDefinition(new CpsFlowDefinition(
            "githubNotify  account: 'raul-arabaolaza', context: 'ATH Results', " +
                    "description: 'All tests are OK', sha: '0b5936eb903d439ac0c0bf84940d73128d5e9487'," +
                    "status: 'SUCCESS', targetUrl: 'http://www.cloudbees.com', repo: 'acceptance-test-harness'"
    ));
    WorkflowRun b1 = p.scheduleBuild2(0).waitForStart();
    jenkins.assertBuildStatus(Result.FAILURE, jenkins.waitForCompletion(b1));
    jenkins.assertLogContains(GitHubStatusNotificationStep.Execution.UNABLE_TO_INFER_DATA, b1);
}
 
Example #26
Source File: GithubNotificationConfigTest.java    From github-autostatus-plugin with MIT License 5 votes vote down vote up
@Test
public void testConfigBranchSource() throws Exception {
    Run build = Mockito.mock(Run.class);
    SCMRevisionAction mockSCMRevisionAction = mock(SCMRevisionAction.class);
    when(build.getAction(SCMRevisionAction.class)).thenReturn(mockSCMRevisionAction);

    GitHubSCMSource source = mock(GitHubSCMSource.class);
    when(source.getCredentialsId()).thenReturn("git-user");
    when(source.getRepoOwner()).thenReturn("repo-owner");
    when(source.getRepository()).thenReturn("repo");
    BranchSCMHead head = new BranchSCMHead("test-branch");
    SCMRevisionImpl revision = new SCMRevisionImpl(head, "what-the-hash");
    when(mockSCMRevisionAction.getRevision()).thenReturn(revision);

    WorkflowMultiBranchProject mockProject = mock(WorkflowMultiBranchProject.class);
    WorkflowJob mockJob = new WorkflowJob(mockProject, "job-name");
    when(build.getParent()).thenReturn(mockJob);
    when(mockProject.getSCMSources()).thenReturn(Collections.singletonList(source));

    PowerMockito.mockStatic(CredentialsMatchers.class);
    when(CredentialsMatchers.firstOrNull(any(), any())).thenReturn(new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, "user-pass", null, "git-user", "git-password"));

    GitHub github = mock(GitHub.class);
    GHUser mockUser = mock(GHUser.class);
    GHRepository mockRepo = mock(GHRepository.class);
    when(github.getUser(any())).thenReturn(mockUser);
    when(mockUser.getRepository(any())).thenReturn(mockRepo);
    GitHubBuilder builder = PowerMockito.mock(GitHubBuilder.class);

    PowerMockito.when(builder.withProxy(Matchers.<Proxy>anyObject())).thenReturn(builder);
    PowerMockito.when(builder.withOAuthToken(anyString(), anyString())).thenReturn(builder);
    PowerMockito.when(builder.build()).thenReturn(github);
    PowerMockito.when(builder.withEndpoint(any())).thenReturn(builder);

    GithubNotificationConfig instance = GithubNotificationConfig.fromRun(build, builder);
    assertEquals("what-the-hash", instance.getShaString());
    assertEquals("test-branch", instance.getBranchName());
}
 
Example #27
Source File: MembershipChecker.java    From github-oauth-authorization-plugin with Apache License 2.0 5 votes vote down vote up
private boolean checkMembershipUsingPersonalAccessToken(GHUser ghUser, AuthConfig authConfig, List<String> organizationsAllowed) throws IOException {
    final GitHub gitHubForPersonalAccessToken = clientBuilder.from(authConfig.gitHubConfiguration());

    for (String organizationName : organizationsAllowed) {
        final GHOrganization organization = gitHubForPersonalAccessToken.getOrganization(organizationName);
        if (organization != null && organization.hasMember(ghUser)) {
            LOG.info(format("[MembershipChecker] User `{0}` is a member of `{1}` organization.", ghUser.getLogin(), organizationName));
            return true;
        }
    }

    return false;
}
 
Example #28
Source File: MembershipChecker.java    From github-oauth-authorization-plugin with Apache License 2.0 5 votes vote down vote up
public boolean isAMemberOfAtLeastOneTeamOfOrganization(GHUser ghUser, AuthConfig authConfig, Map<String, List<String>> organizationAndTeamsAllowed) throws IOException {
    if (organizationAndTeamsAllowed.isEmpty()) {
        LOG.debug("[MembershipChecker] No teams provided.");
        return false;
    }

    return checkTeamMembershipUsingPersonalAccessToken(ghUser, authConfig, organizationAndTeamsAllowed);
}
 
Example #29
Source File: GitHubAuthorizer.java    From github-oauth-authorization-plugin with Apache License 2.0 5 votes vote down vote up
public List<String> authorize(GHUser user, AuthConfig authConfig, List<Role> roles) throws IOException {
    final List<String> assignedRoles = new ArrayList<>();

    if (roles.isEmpty()) {
        return assignedRoles;
    }

    LOG.debug(format("[Authorize] Authorizing user {0}", user.getLogin()));

    for (Role role : roles) {
        final List<String> allowedUsers = role.roleConfiguration().users();
        if (!allowedUsers.isEmpty() && allowedUsers.contains(user.getLogin().toLowerCase())) {
            LOG.info(format("[Authorize] Assigning role `{0}` to user `{1}`. As user belongs to allowed users list.", role.name(), user.getLogin()));
            assignedRoles.add(role.name());
            continue;
        }

        if (membershipChecker.isAMemberOfAtLeastOneOrganization(user, authConfig, role.roleConfiguration().organizations())) {
            LOG.debug(format("[Authorize] Assigning role `{0}` to user `{1}`. As user is a member of at least one organization.", role.name(), user.getLogin()));
            assignedRoles.add(role.name());
            continue;
        }

        if (membershipChecker.isAMemberOfAtLeastOneTeamOfOrganization(user, authConfig, role.roleConfiguration().teams())) {
            LOG.debug(format("[Authorize] Assigning role `{0}` to user `{1}`. As user is a member of at least one team of the organization.", role.name(), user.getLogin()));
            assignedRoles.add(role.name());
        }
    }

    LOG.debug(format("[Authorize] User `{0}` is authorized with `{1}` role(s).", user.getLogin(), assignedRoles));

    return assignedRoles;
}
 
Example #30
Source File: ValidateUserRequestExecutor.java    From github-oauth-authorization-plugin with Apache License 2.0 5 votes vote down vote up
@Override
public GoPluginApiResponse execute() throws Exception {
    GitHub gitHub = clientBuilder.from(request.getAuthConfig().gitHubConfiguration());
    GHUser user = gitHub.getUser(request.getUsername());
    if (user == null) {
        LOG.error(format("[Is Valid User] User %s does not exist in GitHub.", request.getUsername()));
        return DefaultGoPluginApiResponse.error(String.format("User '%s' does not exist in GitHub.", request.getUsername()));
    } else {
        LOG.debug(format("[Is Valid User] %s is valid user.", request.getUsername()));
        return DefaultGoPluginApiResponse.success("");
    }
}