Java Code Examples for hudson.model.User#get()

The following examples show how to use hudson.model.User#get() . 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: GithubScmContentProviderTest.java    From blueocean-plugin with MIT License 6 votes vote down vote up
@Test
public void unauthorizedAccessToContentForMbpGHEShouldFail() throws UnirestException, IOException {
    User alice = User.get("alice");
    alice.setFullName("Alice Cooper");
    alice.addProperty(new Mailer.UserProperty("[email protected]"));

    String aliceCredentialId = createGithubEnterpriseCredential(alice);

    StaplerRequest staplerRequest = mockStapler(GithubEnterpriseScm.ID);

    MultiBranchProject mbp = mockMbp(aliceCredentialId, alice, GithubEnterpriseScm.DOMAIN_NAME);

    try {
        //Bob trying to access content but his credential is not setup so should fail
        new GithubScmContentProvider().getContent(staplerRequest, mbp);
    }catch (ServiceException.PreconditionRequired e){
        assertEquals("Can't access content from github: no credential found", e.getMessage());
        return;
    }
    fail("Should have failed with PreConditionException");
}
 
Example 2
Source File: BlueOceanCredentialsProvider.java    From blueocean-plugin with MIT License 6 votes vote down vote up
@Nonnull
@Override
public List<Credentials> getCredentials(@Nonnull Domain domain) {
    final List<Credentials> result = new ArrayList<>(1);
    if (domain.equals(FolderPropertyImpl.this.domain)) {
        final User proxyUser = User.get(getUser(), false, Collections.emptyMap());
        if (proxyUser != null) {
            try (ACLContext ignored = ACL.as(proxyUser.impersonate())) {
                for (CredentialsStore s : CredentialsProvider.lookupStores(proxyUser)) {
                    for (Domain d : s.getDomains()) {
                        if (d.test(PROXY_REQUIREMENT)) {
                            result.addAll(filter(s.getCredentials(d), withId(getId())));
                        }
                    }
                }
            } catch (UsernameNotFoundException ex) {
                logger.warn("BlueOceanCredentialsProvider.StoreImpl#getCredentials(): Username attached to credentials can not be found");
            }
        }
    }
    return result;
}
 
Example 3
Source File: BitbucketCloudScmContentProviderTest.java    From blueocean-plugin with MIT License 6 votes vote down vote up
@Test
public void unauthorizedAccessToContentShouldFail() throws UnirestException, IOException {
    User alice = User.get("alice");
    alice.setFullName("Alice Cooper");
    alice.addProperty(new Mailer.UserProperty("[email protected]"));

    String aliceCredentialId = createCredential(BitbucketCloudScm.ID, "cloud", alice);

    StaplerRequest staplerRequest = mockStapler();

    MultiBranchProject mbp = mockMbp(aliceCredentialId, alice);

    try {
        //Bob trying to access content but his credential is not setup so should fail
        new BitbucketCloudScmContentProvider().getContent(staplerRequest, mbp);
    } catch (ServiceException.PreconditionRequired e) {
        assertEquals("Can't access content from Bitbucket: no credential found", e.getMessage());
        return;
    }
    fail("Should have failed with PreConditionException");
}
 
Example 4
Source File: ProfileApiTest.java    From blueocean-plugin with MIT License 6 votes vote down vote up
@Test
public void getAuthenticatedUserShouldFail() throws Exception {
    j.jenkins.setSecurityRealm(j.createDummySecurityRealm());
    hudson.model.User user = User.get("alice");
    user.setFullName("Alice Cooper");
    user.addProperty(new Mailer.UserProperty("[email protected]"));

    hudson.model.User user1 = User.get("bob");
    user1.setFullName("Bob Cooper");
    user1.addProperty(new Mailer.UserProperty("[email protected]"));

    Map u = new RequestBuilder(baseUrl)
        .get("/organizations/jenkins/user/")
        .status(404)
        .build(Map.class); //sends jwt token for anonymous user
}
 
Example 5
Source File: PipelineApiTest.java    From blueocean-plugin with MIT License 6 votes vote down vote up
@Test
public void PipelineSecureWithLoggedInUserPermissionTest() throws IOException, UnirestException {
    j.jenkins.setSecurityRealm(j.createDummySecurityRealm());

    hudson.model.User user = User.get("alice");
    user.setFullName("Alice Cooper");


    MockFolder folder = j.createFolder("folder1");

    Project p = folder.createProject(FreeStyleProject.class, "test1");
    String token = getJwtToken(j.jenkins, "alice", "alice");
    assertNotNull(token);
    Map response = new RequestBuilder(baseUrl)
        .get("/organizations/jenkins/pipelines/folder1/pipelines/test1")
        .jwtToken(token)
        .build(Map.class);

    validatePipeline(p, response);

    Map<String,Boolean> permissions = (Map<String, Boolean>) response.get("permissions");
    assertTrue(permissions.get("create"));
    assertTrue(permissions.get("start"));
    assertTrue(permissions.get("stop"));
    assertTrue(permissions.get("read"));
}
 
Example 6
Source File: BlueOceanCredentialsProvider.java    From blueocean-plugin with MIT License 5 votes vote down vote up
@Nonnull
public <C extends Credentials> List<C> getCredentials(@Nonnull final Class<C> type,
                                                      @Nullable ItemGroup itemGroup,
                                                      @Nullable
                                                          Authentication authentication,
                                                      @Nonnull List<DomainRequirement> domainRequirements) {
    final List<C> result = new ArrayList<>();
    final FolderPropertyImpl prop = propertyOf(itemGroup);
    if (prop != null && prop.domain.test(domainRequirements)) {
        final User proxyUser = User.get(prop.getUser(), false, Collections.emptyMap());
        if (proxyUser != null) {
            try (ACLContext ignored = ACL.as(proxyUser.impersonate())) {
                for (CredentialsStore s : CredentialsProvider.lookupStores(proxyUser)) {
                    for (Domain d : s.getDomains()) {
                        if (d.test(PROXY_REQUIREMENT)) {
                            for (Credentials c : filter(s.getCredentials(d), withId(prop.getId()))) {
                                if (type.isInstance(c)) {
                                    result.add((C) c);
                                }
                            }
                        }
                    }
                }
            } catch (UsernameNotFoundException ex) {
                logger.warn("BlueOceanCredentialsProvider#getCredentials(): Username attached to credentials can not be found");
            }
        }
    }
    return result;
}
 
Example 7
Source File: ProfileApiTest.java    From blueocean-plugin with MIT License 5 votes vote down vote up
@Test
public void patchMimeFailTest() throws Exception {
    User system = User.get("SYSTEM");

    new RequestBuilder(baseUrl)
        .contentType("text/plain")
        .status(415)
        .patch("/users/"+system.getId())
        .build(Map.class);
}
 
Example 8
Source File: OicSecurityRealm.java    From oic-auth-plugin with MIT License 5 votes vote down vote up
@Override
public SecurityComponents createSecurityComponents() {
    return new SecurityComponents(
            new AuthenticationManager() {
                public Authentication authenticate(Authentication authentication) throws AuthenticationException {
                    if (authentication instanceof AnonymousAuthenticationToken)
                        return authentication;
                    throw new BadCredentialsException("Unexpected authentication type: " + authentication);
                }
            },
            new UserDetailsService() {
	
	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException {
		// Retrieve the OicUserProperty to get the list of groups that has to be set in the OicUserDetails object.
		LOGGER.fine("loadUserByUsername in createSecurityComponents called, username: " + username);
		User u = User.get(username, false, Collections.emptyMap());
		if (u == null) {
			LOGGER.fine("loadUserByUsername in createSecurityComponents called, no user '" + username + "' found");
			throw new UsernameNotFoundException(username);
		}
		LOGGER.fine("loadUserByUsername in createSecurityComponents called, user: " + u);
		List<UserProperty> props = u.getAllProperties();
		LOGGER.fine("loadUserByUsername in createSecurityComponents called, number of props: " + props.size());
		GrantedAuthority[] auths = new GrantedAuthority[0];
		for (UserProperty prop: props) {
			LOGGER.fine("loadUserByUsername in createSecurityComponents called, prop of type: " + prop.getClass().toString());
			if (prop instanceof OicUserProperty) {
				OicUserProperty oicProp = (OicUserProperty) prop;
				LOGGER.fine("loadUserByUsername in createSecurityComponents called, oic prop found with username: " + oicProp.getUserName());
				auths = oicProp.getAuthoritiesAsGrantedAuthorities();
				LOGGER.fine("loadUserByUsername in createSecurityComponents called, oic prop with auths size: " + auths.length);
			}
		}
		return new OicUserDetails(username, auths);
	}
}
    );
}
 
Example 9
Source File: ProfileApiTest.java    From blueocean-plugin with MIT License 5 votes vote down vote up
@Test @Ignore
public void putMimeTest() throws Exception {
    User system = User.get("SYSTEM");
    Map response = put("/users/"+system.getId()+"/", Collections.emptyMap());
    assertEquals(system.getId(), response.get("id"));
    assertEquals(system.getFullName(), response.get("fullName"));
}
 
Example 10
Source File: GithubScmContentProviderTest.java    From blueocean-plugin with MIT License 5 votes vote down vote up
@Test
public void unauthorizedSaveContentToMbpShouldFail() throws UnirestException, IOException {
    User alice = User.get("alice");
    alice.setFullName("Alice Cooper");
    alice.addProperty(new Mailer.UserProperty("[email protected]"));

    String aliceCredentialId = createGithubCredential(alice);

    StaplerRequest staplerRequest = mockStapler();

    GitContent content = new GitContent.Builder().autoCreateBranch(true).base64Data("c2xlZXAgMTUKbm9kZSB7CiAgY2hlY2tvdXQgc2NtCiAgc2ggJ2xzIC1sJwp9\\nCnNsZWVwIDE1Cg==\\n")
            .branch("test1").message("another commit").owner("cloudbeers").path("Jankinsfile").repo("PR-demo").sha("e23b8ef5c2c4244889bf94db6c05cc08ea138aef").build();

    when(staplerRequest.bindJSON(Mockito.eq(GithubScmSaveFileRequest.class), Mockito.any(JSONObject.class))).thenReturn(new GithubScmSaveFileRequest(content));


    MultiBranchProject mbp = mockMbp(aliceCredentialId, user, GithubScm.DOMAIN_NAME);

    String request = "{\n" +
            "  \"content\" : {\n" +
            "    \"message\" : \"first commit\",\n" +
            "    \"path\" : \"Jenkinsfile\",\n" +
            "    \"branch\" : \"test1\",\n" +
            "    \"repo\" : \"PR-demo\",\n" +
            "    \"sha\" : \"e23b8ef5c2c4244889bf94db6c05cc08ea138aef\",\n" +
            "    \"base64Data\" : "+"\"c2xlZXAgMTUKbm9kZSB7CiAgY2hlY2tvdXQgc2NtCiAgc2ggJ2xzIC1sJwp9\\nCnNsZWVwIDE1Cg==\\n\""+
            "  }\n" +
            "}";

    when(staplerRequest.getReader()).thenReturn(new BufferedReader(new StringReader(request), request.length()));

    try {
        //Bob trying to access content but his credential is not setup so should fail
        new GithubScmContentProvider().saveContent(staplerRequest, mbp);
    }catch (ServiceException.PreconditionRequired e){
        assertEquals("Can't access content from github: no credential found", e.getMessage());
        return;
    }
    fail("Should have failed with PreConditionException");
}
 
Example 11
Source File: ProfileApiTest.java    From blueocean-plugin with MIT License 5 votes vote down vote up
@Test
public void getUserTest() throws Exception {
    User system = User.get("SYSTEM");
    get("/users/", List.class);
    Map response = get("/users/"+system.getId());
    assertEquals(system.getId(), response.get("id"));
    assertEquals(system.getFullName(), response.get("fullName"));
    assertEquals("http://avatar.example/i/img.png", response.get("avatar"));
}
 
Example 12
Source File: ProfileApiTest.java    From blueocean-plugin with MIT License 5 votes vote down vote up
@Test
public void getAuthenticatedUser() throws Exception {
    j.jenkins.setSecurityRealm(j.createDummySecurityRealm());
    hudson.model.User user = User.get("alice");
    user.setFullName("Alice Cooper");
    user.addProperty(new Mailer.UserProperty("[email protected]"));

    // String token = getJwtToken(j.jenkins,"alice", "alice");

    Map u = new RequestBuilder(baseUrl)
        .get("/organizations/jenkins/user/")
        .authAlice()
        .status(200)
        .build(Map.class);

    assertEquals(user.getFullName(), u.get("fullName"));
    assertEquals("[email protected]", u.get("email"));
    assertEquals(user.getId(), u.get("id"));
    Map permission = (Map) u.get("permission");
    assertNotNull(permission);
    assertTrue((Boolean) permission.get("administrator"));
    Map pipelinePerm = (Map) permission.get("pipeline");
    assertEquals(true, pipelinePerm.get("start"));
    assertEquals(true, pipelinePerm.get("create"));
    assertEquals(true, pipelinePerm.get("read"));
    assertEquals(true, pipelinePerm.get("stop"));
    assertEquals(true, pipelinePerm.get("configure"));

    Map credentialPerm = (Map) permission.get("credential");
    assertEquals(true, credentialPerm.get("create"));
    assertEquals(true, credentialPerm.get("view"));
    assertEquals(true, credentialPerm.get("update"));
    assertEquals(true, credentialPerm.get("manageDomains"));
    assertEquals(true, credentialPerm.get("delete"));
}
 
Example 13
Source File: BitbucketServerScmContentProviderTest.java    From blueocean-plugin with MIT License 5 votes vote down vote up
@Test
public void unauthorizedSaveContentShouldFail() throws UnirestException, IOException {
    User alice = User.get("alice");
    alice.setFullName("Alice Cooper");
    alice.addProperty(new Mailer.UserProperty("[email protected]"));

    String aliceCredentialId = createCredential(BitbucketServerScm.ID, alice);
    StaplerRequest staplerRequest = mockStapler();
    MultiBranchProject mbp = mockMbp(aliceCredentialId, alice);

    GitContent content = new GitContent.Builder().autoCreateBranch(true).base64Data("bm9kZXsKICBlY2hvICdoZWxsbyB3b3JsZCEnCn0K")
            .branch("master").message("new commit").owner("TESTP").path("README.md").repo("pipeline-demo-test").build();

    when(staplerRequest.bindJSON(Mockito.eq(BitbucketScmSaveFileRequest.class), Mockito.any(JSONObject.class))).thenReturn(new BitbucketScmSaveFileRequest(content));

    String request = "{\n" +
            "  \"content\" : {\n" +
            "    \"message\" : \"new commit\",\n" +
            "    \"path\" : \"README.md\",\n" +
            "    \"branch\" : \"master\",\n" +
            "    \"repo\" : \"pipeline-demo-test\",\n" +
            "    \"base64Data\" : " + "\"bm9kZXsKICBlY2hvICdoZWxsbyB3b3JsZCEnCn0K\"" +
            "  }\n" +
            "}";

    when(staplerRequest.getReader()).thenReturn(new BufferedReader(new StringReader(request), request.length()));

    try {
        new BitbucketServerScmContentProvider().saveContent(staplerRequest, mbp);
    } catch (ServiceException.PreconditionRequired e) {
        assertEquals("Can't access content from Bitbucket: no credential found", e.getMessage());
        return;
    }
    fail("Should have failed with PreConditionException");
}
 
Example 14
Source File: BitbucketCloudScmContentProviderTest.java    From blueocean-plugin with MIT License 5 votes vote down vote up
@Test
public void unauthorizedSaveContentShouldFail() throws UnirestException, IOException {
    User alice = User.get("alice");
    alice.setFullName("Alice Cooper");
    alice.addProperty(new Mailer.UserProperty("[email protected]"));

    String aliceCredentialId = createCredential(BitbucketCloudScm.ID, alice);
    StaplerRequest staplerRequest = mockStapler();
    MultiBranchProject mbp = mockMbp(aliceCredentialId, alice);

    GitContent content = new GitContent.Builder().autoCreateBranch(true).base64Data("bm9kZXsKICBlY2hvICdoZWxsbyB3b3JsZCEnCn0K")
            .branch("master").message("new commit").owner("TESTP").path("README.md").repo("pipeline-demo-test").build();

    when(staplerRequest.bindJSON(Mockito.eq(BitbucketScmSaveFileRequest.class), Mockito.any(JSONObject.class))).thenReturn(new BitbucketScmSaveFileRequest(content));

    String request = "{\n" +
            "  \"content\" : {\n" +
            "    \"message\" : \"new commit\",\n" +
            "    \"path\" : \"README.md\",\n" +
            "    \"branch\" : \"master\",\n" +
            "    \"repo\" : \"pipeline-demo-test\",\n" +
            "    \"base64Data\" : " + "\"bm9kZXsKICBlY2hvICdoZWxsbyB3b3JsZCEnCn0K\"" +
            "  }\n" +
            "}";

    when(staplerRequest.getReader()).thenReturn(new BufferedReader(new StringReader(request), request.length()));

    try {
        new BitbucketCloudScmContentProvider().saveContent(staplerRequest, mbp);
    } catch (ServiceException.PreconditionRequired e) {
        assertEquals("Can't access content from Bitbucket: no credential found", e.getMessage());
        return;
    }
    fail("Should have failed with PreConditionException");
}
 
Example 15
Source File: JwtTokenVerifierImpl.java    From blueocean-plugin with MIT License 5 votes vote down vote up
public JwtAuthentication(String subject) {
    User user = User.get(subject, false, Collections.emptyMap());
    if (user == null) {
        throw new ServiceException.UnauthorizedException("Invalid JWT token: subject " + subject + " not found");
    }
    //TODO: UserDetails call is expensive, encode it in token and create UserDetails from it
    UserDetails d = Jenkins.getInstance().getSecurityRealm().loadUserByUsername(user.getId());
    this.grantedAuthorities = d.getAuthorities();
    this.name = subject;
    super.setAuthenticated(true);
}
 
Example 16
Source File: UserContainerImpl.java    From blueocean-plugin with MIT License 4 votes vote down vote up
@Override
public BlueUser get(String name) {
    User user = User.get(name, false, ImmutableMap.of());
    if (user==null)     return null;
    return new UserImpl(organization, user, this);
}
 
Example 17
Source File: CLICommandInvoker.java    From jenkins-test-harness with MIT License 4 votes vote down vote up
/**
 * @deprecated only used with {@link #authorizedTo}
 */
@Deprecated
public User user() {

    return User.get(username);
}
 
Example 18
Source File: PipelineBaseTest.java    From blueocean-plugin with MIT License 4 votes vote down vote up
protected User login(String userId, String fullName, String email) throws IOException {
    j.jenkins.setSecurityRealm(j.createDummySecurityRealm());

    hudson.model.User bob = User.get(userId);

    bob.setFullName(fullName);
    if(email != null ) {
        bob.addProperty(new Mailer.UserProperty(email));
    }


    UserDetails d = Jenkins.getInstance().getSecurityRealm().loadUserByUsername(bob.getId());

    SecurityContextHolder.getContext().setAuthentication(new PrincipalAcegiUserToken(bob.getId(),bob.getId(),bob.getId(), d.getAuthorities(), bob.getId()));
    return bob;
}
 
Example 19
Source File: MultiBranchTest.java    From blueocean-plugin with MIT License 4 votes vote down vote up
@Test
public void createUserFavouriteMultibranchBranchTest() throws Exception {
    j.jenkins.setSecurityRealm(j.createDummySecurityRealm());
    hudson.model.User user = User.get("alice");
    user.setFullName("Alice Cooper");
    WorkflowMultiBranchProject mp = j.jenkins.createProject(WorkflowMultiBranchProject.class, "p");
    mp.getSourcesList().add(new BranchSource(new GitSCMSource(null, sampleRepo.toString(), "", "*", "", false),
        new DefaultBranchPropertyStrategy(new BranchProperty[0])));
    for (SCMSource source : mp.getSCMSources()) {
        assertEquals(mp, source.getOwner());
    }

    WorkflowJob p = scheduleAndFindBranchProject(mp, "master");
    j.waitUntilNoActivity();

    WorkflowJob p1 = scheduleAndFindBranchProject(mp, "feature2");

    String token = getJwtToken(j.jenkins,"alice","alice");
    Map map = new RequestBuilder(baseUrl)
        .put("/organizations/jenkins/pipelines/p/branches/feature2/favorite")
        .jwtToken(token)
        .data(ImmutableMap.of("favorite", true))
        .build(Map.class);


    validatePipeline(p1, (Map) map.get("item"));

    Assert.assertEquals("/blue/rest/organizations/jenkins/pipelines/p/branches/feature2/favorite/", getHrefFromLinks(map, "self"));

    List l = new RequestBuilder(baseUrl)
        .get("/users/"+user.getId()+"/favorites/")
        .jwtToken(token)
        .build(List.class);

    Assert.assertEquals(1, l.size());

    Map branch = (Map)((Map)l.get(0)).get("item");

    Assert.assertEquals("/blue/rest/organizations/jenkins/pipelines/p/branches/feature2/favorite/", getHrefFromLinks((Map)l.get(0), "self"));

    validatePipeline(p1, branch);

    String c = (String) branch.get("_class");
    Assert.assertEquals(BranchImpl.class.getName(), c);


    map = new RequestBuilder(baseUrl)
        .put(getUrlFromHref(getHrefFromLinks((Map)l.get(0), "self")))
        .jwtToken(token)
        .data(ImmutableMap.of("favorite", false))
        .build(Map.class);


    validatePipeline(p1, (Map) map.get("item"));

    Assert.assertEquals("/blue/rest/organizations/jenkins/pipelines/p/branches/feature2/favorite/", getHrefFromLinks(map, "self"));

    l = new RequestBuilder(baseUrl)
        .get("/users/"+user.getId()+"/favorites/")
        .jwtToken(token)
        .build(List.class);

    Assert.assertEquals(0, l.size());


    new RequestBuilder(baseUrl)
        .get("/users/"+user.getId()+"/favorites/")
        .jwtToken(getJwtToken(j.jenkins,"bob","bob"))
        .status(403)
        .build(String.class);

}
 
Example 20
Source File: JenkinsConfiguredWithCodeRuleClassRuleTest.java    From configuration-as-code-plugin with MIT License 4 votes vote down vote up
@Test
public void user_created() throws Exception {
    User admin = User.get("admin", false, Collections.emptyMap());
    assertNotNull(admin);
}