Search in sources :

Example 81 with User

use of hudson.model.User in project blueocean-plugin by jenkinsci.

the class GithubScm method getOrganizations.

@Override
public Container<ScmOrganization> getOrganizations() {
    StaplerRequest request = Stapler.getCurrentRequest();
    String credentialId = GithubCredentialUtils.computeCredentialId(getCredentialIdFromRequest(request), getId(), getUri());
    User authenticatedUser = getAuthenticatedUser();
    final StandardUsernamePasswordCredentials credential = CredentialsUtils.findCredential(credentialId, StandardUsernamePasswordCredentials.class, new BlueOceanDomainRequirement());
    if (credential == null) {
        throw new ServiceException.BadRequestException(String.format("Credential id: %s not found for user %s", credentialId, authenticatedUser.getId()));
    }
    String accessToken = credential.getPassword().getPlainText();
    try {
        GitHub github = GitHubFactory.connect(accessToken, getUri());
        final Link link = getLink().rel("organizations");
        // preserve the same order that github org api returns
        Map<String, ScmOrganization> orgMap = new LinkedHashMap<>();
        for (Map.Entry<String, GHOrganization> entry : github.getMyOrganizations().entrySet()) {
            orgMap.put(entry.getKey(), new GithubOrganization(GithubScm.this, entry.getValue(), credential, link));
        }
        GHMyself user = github.getMyself();
        if (orgMap.get(user.getLogin()) == null) {
            // this is to take care of case if/when github starts reporting user login as org later on
            orgMap = new HashMap<>(orgMap);
            orgMap.put(user.getLogin(), new GithubUserOrganization(user, credential, this));
        }
        final Map<String, ScmOrganization> orgs = orgMap;
        return new Container<ScmOrganization>() {

            @Override
            public ScmOrganization get(String name) {
                ScmOrganization org = orgs.get(name);
                if (org == null) {
                    throw new ServiceException.NotFoundException(String.format("GitHub organization %s not found", name));
                }
                return org;
            }

            @Override
            public Link getLink() {
                return link;
            }

            @Override
            public Iterator<ScmOrganization> iterator() {
                return orgs.values().iterator();
            }
        };
    } catch (IOException e) {
        if (e instanceof HttpException) {
            HttpException ex = (HttpException) e;
            if (ex.getResponseCode() == 401) {
                throw new ServiceException.PreconditionRequired("Invalid Github accessToken", ex);
            } else if (ex.getResponseCode() == 403) {
                throw new ServiceException.PreconditionRequired("Github accessToken does not have required scopes. Expected scopes 'user:email, repo'", ex);
            }
        }
        throw new ServiceException.UnexpectedErrorException(e.getMessage(), e);
    }
}
Also used : GHMyself(org.kohsuke.github.GHMyself) GHUser(org.kohsuke.github.GHUser) User(hudson.model.User) GitHub(org.kohsuke.github.GitHub) StaplerRequest(org.kohsuke.stapler.StaplerRequest) LinkedHashMap(java.util.LinkedHashMap) StandardUsernamePasswordCredentials(com.cloudbees.plugins.credentials.common.StandardUsernamePasswordCredentials) ScmOrganization(io.jenkins.blueocean.rest.impl.pipeline.scm.ScmOrganization) ScmServerEndpointContainer(io.jenkins.blueocean.rest.impl.pipeline.scm.ScmServerEndpointContainer) Container(io.jenkins.blueocean.rest.model.Container) GHOrganization(org.kohsuke.github.GHOrganization) HttpException(org.kohsuke.github.HttpException) IOException(java.io.IOException) ServiceException(io.jenkins.blueocean.commons.ServiceException) BlueOceanDomainRequirement(io.jenkins.blueocean.rest.impl.pipeline.credential.BlueOceanDomainRequirement) Map(java.util.Map) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Link(io.jenkins.blueocean.rest.hal.Link)

Example 82 with User

use of hudson.model.User in project blueocean-plugin by jenkinsci.

the class GithubPipelineCreateRequestTest method shouldSucceedForAuthedUserWithCredentialCreatedAndCredentialIdSent.

@Test
public void shouldSucceedForAuthedUserWithCredentialCreatedAndCredentialIdSent() throws Exception {
    // switch to bob and create a credential
    User user = login();
    String credentialId = createGithubCredential(user);
    String orgFolderName = "cloudbeers";
    Map resp = new RequestBuilder(baseUrl).status(201).jwtToken(getJwtToken(j.jenkins, user.getId(), user.getId())).post("/organizations/" + getOrgName() + "/pipelines/").data(GithubTestUtils.buildRequestBody(GithubScm.ID, credentialId, githubApiUrl, orgFolderName, "PR-demo")).build(Map.class);
    assertNotNull(resp);
}
Also used : User(hudson.model.User) Map(java.util.Map) ImmutableMap(com.google.common.collect.ImmutableMap) PipelineBaseTest(io.jenkins.blueocean.rest.impl.pipeline.PipelineBaseTest) Test(org.junit.Test)

Example 83 with User

use of hudson.model.User in project blueocean-plugin by jenkinsci.

the class GithubPipelineCreateRequestTest method shouldSucceedForAuthedUserWithCredentialCreatedAndCredentialIdMissingEnterprise.

@Test
public void shouldSucceedForAuthedUserWithCredentialCreatedAndCredentialIdMissingEnterprise() throws Exception {
    // switch to bob and create a credential
    User user = login();
    createGithubEnterpriseCredential(user);
    String orgFolderName = "cloudbeers";
    Map resp = new RequestBuilder(baseUrl).status(201).jwtToken(getJwtToken(j.jenkins, user.getId(), user.getId())).post("/organizations/" + getOrgName() + "/pipelines/").data(GithubTestUtils.buildRequestBody(GithubEnterpriseScm.ID, null, githubApiUrl, orgFolderName, "PR-demo")).build(Map.class);
    assertNotNull(resp);
}
Also used : User(hudson.model.User) Map(java.util.Map) ImmutableMap(com.google.common.collect.ImmutableMap) PipelineBaseTest(io.jenkins.blueocean.rest.impl.pipeline.PipelineBaseTest) Test(org.junit.Test)

Example 84 with User

use of hudson.model.User in project blueocean-plugin by jenkinsci.

the class GithubPipelineCreateRequestTest method testOrgFolderIndexing.

@Test
public void testOrgFolderIndexing() throws IOException, UnirestException {
    User user = login();
    OrganizationFolder orgFolder = j.jenkins.createProject(OrganizationFolder.class, "p");
    orgFolder.getSCMNavigators().add(new GitHubSCMNavigator("cloudbeers"));
    Map map = new RequestBuilder(baseUrl).post("/organizations/jenkins/pipelines/p/runs/").jwtToken(getJwtToken(j.jenkins, user.getId(), user.getId())).data(ImmutableMap.of()).status(200).build(Map.class);
    assertNotNull(map);
}
Also used : User(hudson.model.User) OrganizationFolder(jenkins.branch.OrganizationFolder) GitHubSCMNavigator(org.jenkinsci.plugins.github_branch_source.GitHubSCMNavigator) Map(java.util.Map) ImmutableMap(com.google.common.collect.ImmutableMap) PipelineBaseTest(io.jenkins.blueocean.rest.impl.pipeline.PipelineBaseTest) Test(org.junit.Test)

Example 85 with User

use of hudson.model.User in project blueocean-plugin by jenkinsci.

the class GithubPipelineCreateRequestTest method shouldFindUserStoreCredential.

@Test
public void shouldFindUserStoreCredential() throws IOException {
    // add username password credential to user's credential store in user domain and in USER scope
    User user = login();
    CredentialsStore store = null;
    for (CredentialsStore s : CredentialsProvider.lookupStores(user)) {
        if (s.hasPermission(CredentialsProvider.CREATE) && s.hasPermission(CredentialsProvider.UPDATE)) {
            store = s;
            break;
        }
    }
    assertNotNull(store);
    store.addDomain(new Domain("github-domain", "Github Domain to store personal access token", Collections.<DomainSpecification>singletonList(new BlueOceanDomainSpecification())));
    Domain domain = store.getDomainByName("github-domain");
    StandardUsernamePasswordCredentials credential = new UsernamePasswordCredentialsImpl(CredentialsScope.USER, "github", "Github Access Token", user.getId(), "12345");
    store.addCredentials(domain, credential);
    // create another credentials with same id in system store with different description
    for (CredentialsStore s : CredentialsProvider.lookupStores(Jenkins.getInstance())) {
        s.addCredentials(Domain.global(), new UsernamePasswordCredentialsImpl(CredentialsScope.USER, "github", "System Github Access Token", user.getId(), "12345"));
    }
    WorkflowMultiBranchProject mp = j.jenkins.createProject(WorkflowMultiBranchProject.class, "demo");
    AbstractFolderProperty prop = new BlueOceanCredentialsProvider.FolderPropertyImpl(user.getId(), credential.getId(), BlueOceanCredentialsProvider.createDomain("https://api.github.com"));
    mp.addProperty(prop);
    // lookup for created credential id in system store, it should resolve to previously created user store credential
    StandardCredentials c = Connector.lookupScanCredentials((Item) mp, "https://api.github.com", credential.getId());
    assertEquals("Github Access Token", c.getDescription());
    assertNotNull(c);
    assertTrue(c instanceof StandardUsernamePasswordCredentials);
    StandardUsernamePasswordCredentials usernamePasswordCredentials = (StandardUsernamePasswordCredentials) c;
    assertEquals(credential.getId(), usernamePasswordCredentials.getId());
    assertEquals(credential.getPassword().getPlainText(), usernamePasswordCredentials.getPassword().getPlainText());
    assertEquals(credential.getUsername(), usernamePasswordCredentials.getUsername());
    // check the domain
    Domain d = CredentialsUtils.findDomain(credential.getId(), user);
    assertNotNull(d);
    assertTrue(d.test(new BlueOceanDomainRequirement()));
    // now remove this property
    mp.getProperties().remove(prop);
    // it must resolve to system credential
    c = Connector.lookupScanCredentials((Item) mp, null, credential.getId());
    assertEquals("System Github Access Token", c.getDescription());
}
Also used : User(hudson.model.User) BlueOceanDomainSpecification(io.jenkins.blueocean.rest.impl.pipeline.credential.BlueOceanDomainSpecification) UsernamePasswordCredentialsImpl(com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl) BlueOceanDomainSpecification(io.jenkins.blueocean.rest.impl.pipeline.credential.BlueOceanDomainSpecification) DomainSpecification(com.cloudbees.plugins.credentials.domains.DomainSpecification) AbstractFolderProperty(com.cloudbees.hudson.plugins.folder.AbstractFolderProperty) StandardUsernamePasswordCredentials(com.cloudbees.plugins.credentials.common.StandardUsernamePasswordCredentials) WorkflowMultiBranchProject(org.jenkinsci.plugins.workflow.multibranch.WorkflowMultiBranchProject) Item(hudson.model.Item) BlueOceanDomainRequirement(io.jenkins.blueocean.rest.impl.pipeline.credential.BlueOceanDomainRequirement) CredentialsStore(com.cloudbees.plugins.credentials.CredentialsStore) Domain(com.cloudbees.plugins.credentials.domains.Domain) StandardCredentials(com.cloudbees.plugins.credentials.common.StandardCredentials) PipelineBaseTest(io.jenkins.blueocean.rest.impl.pipeline.PipelineBaseTest) Test(org.junit.Test)

Aggregations

User (hudson.model.User)105 Test (org.junit.Test)71 Map (java.util.Map)42 ImmutableMap (com.google.common.collect.ImmutableMap)38 PipelineBaseTest (io.jenkins.blueocean.rest.impl.pipeline.PipelineBaseTest)26 Mailer (hudson.tasks.Mailer)24 ServiceException (io.jenkins.blueocean.commons.ServiceException)21 StaplerRequest (org.kohsuke.stapler.StaplerRequest)14 MultiBranchProject (jenkins.branch.MultiBranchProject)13 List (java.util.List)12 JSONObject (net.sf.json.JSONObject)12 GitContent (io.jenkins.blueocean.rest.impl.pipeline.scm.GitContent)8 IOException (java.io.IOException)8 Domain (com.cloudbees.plugins.credentials.domains.Domain)7 BlueOceanDomainRequirement (io.jenkins.blueocean.rest.impl.pipeline.credential.BlueOceanDomainRequirement)7 Authentication (org.acegisecurity.Authentication)7 CredentialsStore (com.cloudbees.plugins.credentials.CredentialsStore)6 StandardUsernamePasswordCredentials (com.cloudbees.plugins.credentials.common.StandardUsernamePasswordCredentials)6 BufferedReader (java.io.BufferedReader)6 StringReader (java.io.StringReader)6