@Override protected synchronized JSON data() { JSONArray r = new JSONArray(); for (User u : modified) { UserInfo i = users.get(u); JSONObject entry = new JSONObject() .accumulate("id", u.getId()) .accumulate("fullName", u.getFullName()) .accumulate("url", u.getUrl()) .accumulate( "avatar", i.avatar != null ? i.avatar : Stapler.getCurrentRequest().getContextPath() + Functions.getResourcePath() + "/images/" + iconSize + "/user.png") .accumulate("timeSortKey", i.getTimeSortKey()) .accumulate("lastChangeTimeString", i.getLastChangeTimeString()); AbstractProject<?, ?> p = i.getProject(); if (p != null) { entry .accumulate("projectUrl", p.getUrl()) .accumulate("projectFullDisplayName", p.getFullDisplayName()); } r.add(entry); } modified.clear(); return r; }
@Exported public String getUserName() { if (authenticationName == null) return "N/A"; User u = User.get(authenticationName, false); return u != null ? u.getDisplayName() : authenticationName; }
private void addUserTriggeringTheBuild( AbstractBuild<?, ?> build, Set<InternetAddress> recipientAddresses, Set<InternetAddress> ccAddresses, EnvVars env, BuildListener listener) { User user = getByUserIdCause(build); if (user == null) { user = getByLegacyUserCause(build); } if (user != null) { String adrs = user.getProperty(Mailer.UserProperty.class).getAddress(); if (adrs != null) { addAddressesFromRecipientList(recipientAddresses, ccAddresses, adrs, env, listener); } else { listener .getLogger() .println( "Failed to send e-mail to " + user.getFullName() + " because no e-mail address is known, and no default e-mail domain is configured"); } } }
/** 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 }
@Test public void privateView() throws Exception { j.createFreeStyleProject("project1"); User user = User.get("me", true); // create user WebClient wc = j.createWebClient(); HtmlPage userPage = wc.goTo("user/me"); HtmlAnchor privateViewsLink = userPage.getFirstAnchorByText("My Views"); assertNotNull("My Views link not available", privateViewsLink); HtmlPage privateViewsPage = (HtmlPage) privateViewsLink.click(); Text viewLabel = (Text) privateViewsPage.getFirstByXPath("//div[@class='tabBar']//div[@class='tab active']/a/text()"); assertTrue("'All' view should be selected", viewLabel.getTextContent().contains(Hudson_ViewName())); View listView = listView("listView"); HtmlPage newViewPage = wc.goTo("user/me/my-views/newView"); HtmlForm form = newViewPage.getFormByName("createItem"); form.getInputByName("name").setValueAttribute("proxy-view"); ((HtmlRadioButtonInput) form.getInputByValue("hudson.model.ProxyView")).setChecked(true); HtmlPage proxyViewConfigurePage = j.submit(form); View proxyView = user.getProperty(MyViewsProperty.class).getView("proxy-view"); assertNotNull(proxyView); form = proxyViewConfigurePage.getFormByName("viewConfig"); form.getSelectByName("proxiedViewName").setSelectedAttribute("listView", true); j.submit(form); assertTrue(proxyView instanceof ProxyView); assertEquals(((ProxyView) proxyView).getProxiedViewName(), "listView"); assertEquals(((ProxyView) proxyView).getProxiedView(), listView); }
@Before public void setup() throws Throwable { // Instantiating ScmSyncConfigurationPlugin instance ScmSyncConfigurationPlugin scmSyncConfigPluginInstance = new ScmSyncConfigurationPlugin(); // Mocking PluginWrapper attached to current ScmSyncConfigurationPlugin instance PluginWrapper pluginWrapper = PowerMockito.mock(PluginWrapper.class); when(pluginWrapper.getShortName()).thenReturn("scm-sync-configuration"); // Setting field on current plugin instance Field wrapperField = Plugin.class.getDeclaredField("wrapper"); boolean wrapperFieldAccessibility = wrapperField.isAccessible(); wrapperField.setAccessible(true); wrapperField.set(scmSyncConfigPluginInstance, pluginWrapper); wrapperField.setAccessible(wrapperFieldAccessibility); // Mocking Hudson root directory currentTestDirectory = createTmpDirectory("SCMSyncConfigTestsRoot"); currentHudsonRootDirectory = new File(currentTestDirectory.getAbsolutePath() + "/hudsonRootDir/"); if (!(currentHudsonRootDirectory.mkdir())) { throw new IOException( "Could not create hudson root directory: " + currentHudsonRootDirectory.getAbsolutePath()); } FileUtils.copyDirectoryStructure( new ClassPathResource(getHudsonRootBaseTemplate()).getFile(), currentHudsonRootDirectory); // EnvVars env = Computer.currentComputer().getEnvironment(); // env.put("HUDSON_HOME", tmpHudsonRoot.getPath() ); // Creating local SVN repository... curentLocalSvnRepository = new File(currentTestDirectory.getAbsolutePath() + "/svnLocalRepo/"); if (!(curentLocalSvnRepository.mkdir())) { throw new IOException( "Could not create SVN local repo directory: " + curentLocalSvnRepository.getAbsolutePath()); } FileUtils.copyDirectoryStructure( new ClassPathResource("svnEmptyRepository").getFile(), curentLocalSvnRepository); // Mocking user User mockedUser = Mockito.mock(User.class); when(mockedUser.getId()).thenReturn("fcamblor"); // Mocking Hudson singleton instance ... // Warning : this line will only work on Objenesis supported VMs : // http://code.google.com/p/objenesis/wiki/ListOfCurrentlySupportedVMs Hudson hudsonMockedInstance = spy((Hudson) new ObjenesisStd().getInstantiatorOf(Hudson.class).newInstance()); PowerMockito.doReturn(currentHudsonRootDirectory).when(hudsonMockedInstance).getRootDir(); PowerMockito.doReturn(mockedUser).when(hudsonMockedInstance).getMe(); PowerMockito.doReturn(scmSyncConfigPluginInstance) .when(hudsonMockedInstance) .getPlugin(ScmSyncConfigurationPlugin.class); PowerMockito.mockStatic(Hudson.class); PowerMockito.doReturn(hudsonMockedInstance).when(Hudson.class); Hudson.getInstance(); // when(Hudson.getInstance()).thenReturn(hudsonMockedInstance); }
/** * All users who can login to the system. */ public List<User> getAllUsers() { List<User> r = new ArrayList<User>(); for (User u : User.getAll()) { if(u.getProperty(Details.class)!=null) r.add(u); } Collections.sort(r); return r; }
@Override public Collection<User> getPossibleOwners(Node item) { if (OwnershipPlugin.getInstance().isRequiresConfigureRights()) { IUserFilter filter = new AccessRightsFilter(item, Computer.CONFIGURE); return UserCollectionFilter.filterUsers(User.getAll(), true, filter); } else { return User.getAll(); } }
@Override public Details loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException { User u = User.get(username,false); Details p = u!=null ? u.getProperty(Details.class) : null; if(p==null) throw new UsernameNotFoundException("Password is not set: "+username); if(p.getUser()==null) throw new AssertionError(); return p; }
/** * 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; }
public People(Jenkins parent) { this.parent = parent; // for Hudson, really load all users Map<User, UserInfo> users = getUserInfo(parent.getItems()); User unknown = User.getUnknown(); for (User u : User.getAll()) { if (u == unknown) continue; // skip the special 'unknown' user if (!users.containsKey(u)) users.put(u, new UserInfo(u, null, null)); } this.users = toList(users); }
private void validateUserPropertyAddress(String address, String username, String suffix) throws Exception { PowerMockito.when(descriptor.getDefaultSuffix()).thenReturn(suffix); PowerMockito.when(user.getFullName()).thenReturn(username); PowerMockito.when(user.getId()).thenReturn(username.replace('\\', '_')); String a = new UserPropertyMock(user, null).getConfiguredAddress(); assertEquals(address, a); }
/** * Loads group lists for the user. {@link User} info has a high priority. If there is no info, * {@link UserDetails} will be loaded from the current {@link SecurityRealm}. * * @param userId * @return List of effective groups. Null if there's no info */ private static @CheckForNull List<String> getAuthorities(@Nonnull String userId) { final @CheckForNull User usr = User.get(userId, false, null); if (usr == null) { // User is not registered in Jenkins (e.g. deleted) return getAuthoritiesFromRealm(userId); } List<String> authorities = usr.getAuthorities(); if (authorities.isEmpty()) { return getAuthoritiesFromRealm(userId); } return authorities; }
/** Associates the OpenID identity of the user with {@link #realm}. */ private void associateUserWithOpenId(User u) throws Exception { WebClient wc = new WebClient().login(u.getId(), u.getId() /*assumes password==name*/); // Associate an OpenID with an existing user HtmlPage associated = wc.goTo("federatedLoginService/openid/startAssociate?openid=" + openid.url); assertTrue( associated.getDocumentURI().endsWith("federatedLoginService/openid/onAssociationSuccess")); OpenIdUserProperty p = u.getProperty(OpenIdUserProperty.class); assertEquals(1, p.getIdentifiers().size()); assertEquals(openid.getUserIdentity(), p.getIdentifiers().iterator().next()); }
@Before public void setUp() throws Exception { jenkins = PowerMockito.mock(Hudson.class); user = PowerMockito.mock(User.class); when(user.getFullName()).thenReturn("Full name"); when(user.getId()).thenReturn("user_id"); PowerMockito.spy(Mailer.class); descriptor = PowerMockito.mock(Mailer.DescriptorImpl.class); PowerMockito.doReturn(descriptor).when(Mailer.class, "descriptor"); }
/** * @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; }
/** Try to make this user a super-user */ private void tryToMakeAdmin(User u) throws IOException { WwpassIdentity p = u.getProperty(WwpassIdentity.class); p.activate(); u.save(); AuthorizationStrategy as = Jenkins.getInstance().getAuthorizationStrategy(); for (PermissionAdder adder : Jenkins.getInstance().getExtensionList(PermissionAdder.class)) { if (adder.add(as, u, Jenkins.ADMINISTER)) { return; } } LOGGER.severe( "Admin permission wasn't added for user: "******", ID: " + u.getId()); }
@Override public WwpassIdentity loadUserByUsername(String puid) throws UsernameNotFoundException, DataAccessException { Collection<User> all = User.getAll(); for (User u : all) { WwpassIdentity p = u.getProperty(WwpassIdentity.class); if (puid.equals(p != null ? p.getPuid() : null)) { return p; } } throw new UsernameNotFoundException("There is no any user with: " + puid); }
private void populateChangeEntry(String runId, ChangeLogSet.Entry changeSetItem) { String commitId = changeSetItem.getCommitId(); if (commitId != null) { put("revision", commitId, runId); } User committer = changeSetItem.getAuthor(); if (committer != null) { put("committerId", committer.getId(), runId); put("committerName", committer.getFullName(), runId); } // TODO: Branch }
public final void post(BuildListener listener) throws Exception { try { post2(listener); if (result.isBetterOrEqualTo(Result.UNSTABLE)) createSymlink(listener, "lastSuccessful"); if (result.isBetterOrEqualTo(Result.SUCCESS)) createSymlink(listener, "lastStable"); } finally { // update the culprit list HashSet<String> r = new HashSet<String>(); for (User u : getCulprits()) r.add(u.getId()); culprits = r; CheckPoint.CULPRITS_DETERMINED.report(); } }
@Override public String findMailAddressFor(User u) { String username = u.getId(); for (JiraSite site : JiraProjectProperty.DESCRIPTOR.getSites()) { try { JiraSession session = site.createSession(); if (session != null) { RemoteUser user = session.service.getUser(session.token, username); if (user != null) { String email = user.getEmail(); if (email != null) { email = unmaskEmail(email); return email; } } } } catch (IOException ex) { LOGGER.log(Level.WARNING, "Unable to create session with " + site.getName(), ex); } catch (ServiceException ex) { LOGGER.log(Level.WARNING, "Unable to create session with " + site.getName(), ex); } } return null; }
@Issue("JENKINS-9367") @Test public void allImagesCanBeLoaded() throws Exception { User.get("user", true); WebClient webClient = j.createWebClient(); webClient.setJavaScriptEnabled(false); j.assertAllImageLoadSuccessfully(webClient.goTo("asynchPeople")); }
/** * Try to make this user a super-user */ private void tryToMakeAdmin(User u) { AuthorizationStrategy as = Jenkins.getInstance().getAuthorizationStrategy(); if (as instanceof GlobalMatrixAuthorizationStrategy) { GlobalMatrixAuthorizationStrategy ma = (GlobalMatrixAuthorizationStrategy) as; ma.add(Jenkins.ADMINISTER,u.getId()); } }
@Override public Set<String> culprits() { Set<String> culprits = new HashSet<String>(); if (build instanceof AbstractBuild<?, ?>) { AbstractBuild<?, ?> jenkinsBuild = (AbstractBuild<?, ?>) build; if (!(isRunning(jenkinsBuild))) { for (User culprit : jenkinsBuild.getCulprits()) { culprits.add(culprit.getFullName()); } } } return culprits; }
@Issue("JENKINS-18641") @Test public void display() throws Exception { User.get("bob"); JenkinsRule.WebClient wc = j.createWebClient(); HtmlPage page; try { page = wc.goTo("asynchPeople"); } catch (FailingHttpStatusCodeException x) { System.err.println(x.getResponse().getResponseHeaders()); System.err.println(x.getResponse().getContentAsString()); throw x; } assertEquals(0, wc.waitForBackgroundJavaScript(120000)); boolean found = false; for (DomElement table : page.getElementsByTagName("table")) { if (table.getAttribute("class").contains("progress-bar")) { found = true; assertEquals("display: none;", table.getAttribute("style")); break; } } assertTrue(found); /* TODO this still fails occasionally, for reasons TBD (I think because User.getAll sometimes is empty): assertNotNull(page.getElementById("person-bob")); */ }
@Override protected void compute() throws Exception { int itemCount = 0; for (Item item : items) { for (Job<?, ?> job : item.getAllJobs()) { if (job instanceof AbstractProject) { AbstractProject<?, ?> p = (AbstractProject) job; RunList<? extends AbstractBuild<?, ?>> builds = p.getBuilds(); int buildCount = 0; for (AbstractBuild<?, ?> build : builds) { if (canceled()) { return; } for (ChangeLogSet.Entry entry : build.getChangeSet()) { User user = entry.getAuthor(); UserInfo info = users.get(user); if (info == null) { UserInfo userInfo = new UserInfo(user, p, build.getTimestamp()); userInfo.avatar = UserAvatarResolver.resolveOrNull(user, iconSize); synchronized (this) { users.put(user, userInfo); modified.add(user); } } else if (info.getLastChange().before(build.getTimestamp())) { synchronized (this) { info.project = p; info.lastChange = build.getTimestamp(); modified.add(user); } } } // TODO consider also adding the user of the UserCause when applicable buildCount++; progress((itemCount + 1.0 * buildCount / builds.size()) / (items.size() + 1)); } } } itemCount++; progress(1.0 * itemCount / (items.size() + /* handling User.getAll */ 1)); } if (unknown != null) { if (canceled()) { return; } for (User u : User.getAll()) { // TODO nice to have a method to iterate these lazily if (u == unknown) { continue; } if (!users.containsKey(u)) { UserInfo userInfo = new UserInfo(u, null, null); userInfo.avatar = UserAvatarResolver.resolveOrNull(u, iconSize); synchronized (this) { users.put(u, userInfo); modified.add(u); } } } } }
@Test public void deleteView() throws Exception { WebClient wc = j.createWebClient(); ListView v = listView("list"); HtmlPage delete = wc.getPage(v, "delete"); j.submit(delete.getFormByName("delete")); assertNull(j.jenkins.getView("list")); User user = User.get("user", true); MyViewsProperty p = user.getProperty(MyViewsProperty.class); v = new ListView("list", p); p.addView(v); delete = wc.getPage(v, "delete"); j.submit(delete.getFormByName("delete")); assertNull(p.getView("list")); }
@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()); }
public final void post(BuildListener listener) throws Exception { try { post2(listener); // Resolve issue with invalid symlinks for maven (see // http://issues.hudson-ci.org/browse/HUDSON-8340) if (getResult().isBetterOrEqualTo(Result.UNSTABLE)) createSymlink(listener, "lastSuccessful"); if (getResult().isBetterOrEqualTo(Result.SUCCESS)) createSymlink(listener, "lastStable"); } finally { // update the culprit list HashSet<String> r = new HashSet<String>(); for (User u : getCulprits()) r.add(u.getId()); culprits = r; CheckPoint.CULPRITS_DETERMINED.report(); } }
@Test @LocalData public void testIsAuthenticateionRequiredAsUser() { ACL.impersonate(User.get("test1").impersonate()); assertFalse(Jenkins.getInstance().hasPermission(Jenkins.ADMINISTER)); // after: not configured // before: test2, require re-auth // result: false assertFalse( SpecificUsersAuthorizationStrategy.isAuthenticateionRequired( null, new SpecificUsersAuthorizationStrategy("test2", false))); // after: test1, require re-auth // before: test2, require re-auth // result: false assertFalse( SpecificUsersAuthorizationStrategy.isAuthenticateionRequired( new SpecificUsersAuthorizationStrategy("test1", false), new SpecificUsersAuthorizationStrategy("test2", false))); // after: test1, require re-auth // before: not configured // result: false assertFalse( SpecificUsersAuthorizationStrategy.isAuthenticateionRequired( new SpecificUsersAuthorizationStrategy("test1", false), null)); // after: test2, no require re-auth // before: not configured // result: true assertTrue( SpecificUsersAuthorizationStrategy.isAuthenticateionRequired( new SpecificUsersAuthorizationStrategy("test2", true), null)); // after: test2, require re-auth // before: test2, no require re-auth // result: false assertFalse( SpecificUsersAuthorizationStrategy.isAuthenticateionRequired( new SpecificUsersAuthorizationStrategy("test2", false), new SpecificUsersAuthorizationStrategy("test2", true))); // after: admin, no require re-auth // before: test2, no require re-auth // result: true assertTrue( SpecificUsersAuthorizationStrategy.isAuthenticateionRequired( new SpecificUsersAuthorizationStrategy("admin", true), new SpecificUsersAuthorizationStrategy("test2", true))); // after: null, no require re-auth // before: null, no require re-auth // result: anything (not ABEND) SpecificUsersAuthorizationStrategy.isAuthenticateionRequired( new SpecificUsersAuthorizationStrategy(null, true), new SpecificUsersAuthorizationStrategy(null, true)); }