Java Code Examples for hudson.model.User#current()
The following examples show how to use
hudson.model.User#current() .
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: BuildListener.java From audit-log-plugin with MIT License | 6 votes |
/** * Fired when a build is started, event logged via Log4j-audit. * * @param run of type Run having the build information * @param listener of type TaskListener that the onStarted method expects */ @Override public void onStarted(Run run, TaskListener listener) { BuildStart buildStart = LogEventFactory.getEvent(BuildStart.class); List causeObjects = run.getCauses(); List<String> causes = new ArrayList<>(causeObjects.size()); for (Object cause: causeObjects) { Cause c = (Cause)cause; causes.add(c.getShortDescription()); } buildStart.setBuildNumber(run.getNumber()); buildStart.setCause(causes); buildStart.setProjectName(run.getParent().getFullName()); buildStart.setTimestamp(formatDateISO(run.getStartTimeInMillis())); User user = User.current(); if(user != null) buildStart.setUserId(user.getId()); else buildStart.setUserId(null); buildStart.logEvent(); }
Example 2
Source File: GitReadSaveService.java From blueocean-plugin with MIT License | 6 votes |
@Nonnull protected StandardUsernamePasswordCredentials getCredentialForUser(@Nonnull Item item, @Nonnull String repositoryUrl) { User user = User.current(); if (user == null) { //ensure this session has authenticated user throw new ServiceException.UnauthorizedException("No logged in user found"); } String credentialId = GitScm.makeCredentialId(repositoryUrl); StandardUsernamePasswordCredentials credential = null; if (credentialId != null) { credential = CredentialsUtils.findCredential(credentialId, StandardUsernamePasswordCredentials.class, new BlueOceanDomainRequirement()); } if (credential == null) { throw new ServiceException.UnauthorizedException("No credential found for " + credentialId + " for user " + user.getDisplayName()); } return credential; }
Example 3
Source File: GitReadSaveRequest.java From blueocean-plugin with MIT License | 6 votes |
@CheckForNull StandardCredentials getCredential() { StandardCredentials credential = null; User user = User.current(); if (user == null) { throw new ServiceException.UnauthorizedException("Not authenticated"); } // Get committer info and credentials if (GitUtils.isSshUrl(gitSource.getRemote()) || GitUtils.isLocalUnixFileUrl(gitSource.getRemote())) { credential = UserSSHKeyManager.getOrCreate(user); } else { String credentialId = GitScm.makeCredentialId(gitSource.getRemote()); if (credentialId != null) { credential = CredentialsUtils.findCredential(credentialId, StandardCredentials.class, new BlueOceanDomainRequirement()); } } return credential; }
Example 4
Source File: FavoriteListStatePreloader.java From blueocean-plugin with MIT License | 6 votes |
@CheckForNull @Override public String getStateJson() { User jenkinsUser = User.current(); if (jenkinsUser == null) { return null; } FavoriteUserProperty fup = jenkinsUser.getProperty(FavoriteUserProperty.class); if (fup == null) { return null; } Set<String> favorites = fup.getAllFavorites(); if (favorites == null) { return null; } return JSONArray.fromObject(favorites).toString(); }
Example 5
Source File: UserPublicKeyRoute.java From blueocean-plugin with MIT License | 6 votes |
/** * Deletes the user's private Jenkins-managed key * * @return */ @DELETE @WebMethod(name = "") @TreeResponse public UserKey resetPublicKey() { User authenticatedUser = User.current(); if (authenticatedUser == null) { throw new ServiceException.UnauthorizedException("Not authorized"); } if (!StringUtils.equals(user.getId(), authenticatedUser.getId())) { throw new ServiceException.ForbiddenException("Not authorized"); } UserSSHKeyManager.reset(authenticatedUser); return getPublickey(); }
Example 6
Source File: UserStatePreloader.java From blueocean-plugin with MIT License | 6 votes |
/** * {@inheritDoc} */ @Override public String getStateJson() { BlueOrganization organization = Iterables.getFirst(OrganizationFactory.getInstance().list(), null); try { User currentUser = User.current(); if (currentUser != null && organization != null) { return Export.toJson(new UserImpl(organization, currentUser), true); } else { return ANONYMOUS; } } catch (IOException e) { LOGGER.log(Level.SEVERE, "Unexpected error serializing active User object and adding to page preload state."); return ANONYMOUS; } }
Example 7
Source File: AbstractPipelineCreateRequest.java From blueocean-plugin with MIT License | 5 votes |
protected User checkUserIsAuthenticatedAndHasItemCreatePermission(BlueOrganization organization) { ModifiableTopLevelItemGroup p = getParent(organization); User authenticatedUser = User.current(); if (authenticatedUser == null) { throw new ServiceException.UnauthorizedException("Must be logged in to create a pipeline"); } Authentication authentication = Jenkins.getAuthentication(); ACL acl = (p instanceof AccessControlled) ? ((AccessControlled) p).getACL() : Jenkins.getInstance().getACL(); if(!acl.hasPermission(authentication, Item.CREATE)){ throw new ServiceException.ForbiddenException( String.format("User %s doesn't have Job create permission", authenticatedUser.getId())); } return authenticatedUser; }
Example 8
Source File: CredentialApi.java From blueocean-plugin with MIT License | 5 votes |
@POST @WebMethod(name = "") public CreateResponse create(@JsonBody JSONObject body, StaplerRequest request) throws IOException { User authenticatedUser = User.current(); if(authenticatedUser == null){ throw new ServiceException.UnauthorizedException("No authenticated user found"); } JSONObject jsonObject = body.getJSONObject("credentials"); final IdCredentials credentials = request.bindJSON(IdCredentials.class, jsonObject); String domainName = DOMAIN_NAME; if(jsonObject.get("domain") != null && jsonObject.get("domain") instanceof String){ domainName = (String) jsonObject.get("domain"); } CredentialsUtils.createCredentialsInUserStore(credentials, authenticatedUser, domainName, ImmutableList.of(new BlueOceanDomainSpecification())); CredentialsStoreAction.DomainWrapper domainWrapper = credentialStoreAction.getDomain(domainName); if(domainWrapper != null) { CredentialsStoreAction.CredentialsWrapper credentialsWrapper = domainWrapper.getCredential(credentials.getId()); if (credentialsWrapper != null){ return new CreateResponse( new CredentialApi.Credential( credentialsWrapper, getLink().rel("domains").rel(domainName).rel("credentials"))); } } //this should never happen throw new ServiceException.UnexpectedErrorException("Unexpected error, failed to create credential"); }
Example 9
Source File: UserImplPermissionTest.java From blueocean-plugin with MIT License | 5 votes |
@Override public BlueUser getUser() { User user = User.current(); if (user == null) { throw new ServiceException.NotFoundException("No authenticated user found"); } return new UserImpl(this, user, new UserContainerImpl(this, this)); }
Example 10
Source File: FavoriteUtil.java From blueocean-plugin with MIT License | 5 votes |
private static User getUser() { User user = User.current(); if(user == null) { throw new ServiceException.ForbiddenException("Must be logged in to use set favorites"); } return user; }
Example 11
Source File: FavoritesStatePreloader.java From blueocean-plugin with MIT License | 5 votes |
@Override protected FetchData getFetchData(@Nonnull BlueUrlTokenizer blueUrl) { User jenkinsUser = User.current(); if (jenkinsUser != null) { BlueOrganization organization = Iterables.getFirst(OrganizationFactory.getInstance().list(), null); if (organization != null) { String pipelineFullName = blueUrl.getPart(BlueUrlTokenizer.UrlPart.PIPELINE); // don't need this list when at pipeline pages if (pipelineFullName != null) { return null; } UserImpl blueUser = new UserImpl(organization, jenkinsUser, organization.getUsers()); BlueFavoriteContainer favoritesContainer = blueUser.getFavorites(); if (favoritesContainer != null) { JSONArray favorites = new JSONArray(); // Limit the number of favorites to return to a sane amount Iterator<BlueFavorite> favoritesIterator = favoritesContainer.iterator(0, DEFAULT_LIMIT); while (favoritesIterator.hasNext()) { Reachable favorite = favoritesIterator.next(); try { favorites.add(JSONObject.fromObject(Export.toJson(favorite))); } catch (IOException e) { LOGGER.log(Level.FINE, String.format("Unable to preload favorites for User '%s'. Serialization error.", jenkinsUser.getFullName()), e); return null; } } return new FetchData(favoritesContainer.getLink().getHref() + "?start=0&limit=" + DEFAULT_LIMIT, favorites.toString()); } } } // Don't preload any data on the page. return null; }
Example 12
Source File: OrganizationImpl.java From blueocean-plugin with MIT License | 5 votes |
@Override public BlueUser getUser() { User user = User.current(); if(user == null){ throw new ServiceException.NotFoundException("No authenticated user found"); } return new UserImpl(this, user, new UserContainerImpl(this, this)); }
Example 13
Source File: AbstractScm.java From blueocean-plugin with MIT License | 5 votes |
/** * Gives authenticated user * @return logged in {@link User} * @throws ServiceException.UnauthorizedException */ protected User getAuthenticatedUser(){ User authenticatedUser = User.current(); if(authenticatedUser == null){ throw new ServiceException.UnauthorizedException("No logged in user found"); } return authenticatedUser; }
Example 14
Source File: LockableResourcesRootAction.java From lockable-resources-plugin with MIT License | 5 votes |
public String getUserName() { User current = User.current(); if (current != null) return current.getFullName(); else return null; }
Example 15
Source File: AbstractBitbucketScm.java From blueocean-plugin with MIT License | 5 votes |
/** * Request payload: * { * "userName": "joe", * "password":"****", * "apiUrl":"mybitbucketserver.com" * } * @param request userName and password of bitbucket server * * @return credential id */ @Override public HttpResponse validateAndCreate(@JsonBody JSONObject request) { User authenticatedUser = User.current(); if(authenticatedUser == null){ throw new ServiceException.UnauthorizedException("No logged in user found"); } String userName = (String) request.get("userName"); String password = (String) request.get("password"); String apiUrl = (String) request.get("apiUrl"); validate(userName, password, apiUrl); final StandardUsernamePasswordCredentials credential = new UsernamePasswordCredentialsImpl(CredentialsScope.USER, createCredentialId(apiUrl), "Bitbucket server credentials", userName, password); //if credentials are wrong, this call will fail with 401 error validateCredential(apiUrl, credential); StandardUsernamePasswordCredentials bbCredentials = CredentialsUtils.findCredential(createCredentialId(apiUrl), StandardUsernamePasswordCredentials.class, new BlueOceanDomainRequirement()); try { if (bbCredentials == null) { CredentialsUtils.createCredentialsInUserStore( credential, authenticatedUser, getDomainId(), ImmutableList.<DomainSpecification>of(new BlueOceanDomainSpecification())); } else { CredentialsUtils.updateCredentialsInUserStore( bbCredentials, credential, authenticatedUser, getDomainId(), ImmutableList.<DomainSpecification>of(new BlueOceanDomainSpecification())); } return createResponse(credential.getId()); }catch (IOException e){ throw new ServiceException.UnexpectedErrorException(e.getMessage()); } }
Example 16
Source File: RequestContextFilter.java From audit-log-plugin with MIT License | 5 votes |
/** * The filter through which the flow passes is used to set the context level attributes */ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { User user = User.current(); if(user != null){ RequestContext.setUserId(user.getId()); } RequestContext.setIpAddress(request.getRemoteAddr()); RequestContext.setNodeName(request.getLocalName()); //RequestContext.setRequestUri(request.getRequestURI()); chain.doFilter(request, response); RequestContext.clear(); }
Example 17
Source File: BuildListener.java From audit-log-plugin with MIT License | 5 votes |
/** * Fired when a build is completed, event logged via Log4j-audit. * * @param run of type Run having the build information * @param listener of type TaskListener that the onCompleted method expects */ @Override public void onCompleted(Run run, TaskListener listener) { BuildFinish buildFinish = LogEventFactory.getEvent(BuildFinish.class); List causeObjects = run.getCauses(); List<String> causes = new ArrayList<>(causeObjects.size()); for (Object cause: causeObjects) { Cause c = (Cause)cause; causes.add(c.getShortDescription()); } buildFinish.setBuildNumber(run.getNumber()); buildFinish.setCause(causes); buildFinish.setProjectName(run.getParent().getFullName()); Instant start = Instant.ofEpochMilli(run.getStartTimeInMillis()); Instant finish = start.plusMillis(run.getDuration()); buildFinish.setTimestamp(formatDateISO(finish.toEpochMilli())); User user = User.current(); if(user != null) buildFinish.setUserId(user.getId()); else buildFinish.setUserId(null); buildFinish.logEvent(); }
Example 18
Source File: GitLabSecurityRealm.java From gitlab-oauth-plugin with MIT License | 4 votes |
/** * 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 (StringUtils.isBlank(code)) { Log.info("doFinishLogin: missing code or private_token."); return HttpResponses.redirectToContextRoot(); } String state = request.getParameter("state"); HttpPost httpPost = new HttpPost(gitlabWebUri + "/oauth/token"); List<NameValuePair> parameters = new ArrayList<NameValuePair>(); parameters.add(new BasicNameValuePair("client_id", clientID)); parameters.add(new BasicNameValuePair("client_secret", clientSecret)); parameters.add(new BasicNameValuePair("code", code)); parameters.add(new BasicNameValuePair("grant_type", "authorization_code")); parameters.add(new BasicNameValuePair("redirect_uri", buildRedirectUrl(request, state))); httpPost.setEntity(new UrlEncodedFormEntity(parameters, StandardCharsets.UTF_8)); CloseableHttpClient httpclient = HttpClients.createDefault(); HttpHost proxy = getProxy(httpPost); if (proxy != null) { RequestConfig config = RequestConfig.custom() .setProxy(proxy) .build(); httpPost.setConfig(config); } org.apache.http.HttpResponse response = httpclient.execute(httpPost); 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.close(); String accessToken = extractToken(content); if (StringUtils.isNotBlank(accessToken)) { // only set the access token if it exists. GitLabAuthenticationToken auth = new GitLabAuthenticationToken(accessToken, getGitlabApiUri(), TokenType.ACCESS_TOKEN); HttpSession session = request.getSession(false); if (session != null) { // avoid session fixation session.invalidate(); } request.getSession(true); SecurityContextHolder.getContext().setAuthentication(auth); GitlabUser self = auth.getMyself(); User user = User.current(); if (user != null) { user.setFullName(self.getName()); // Set email from gitlab only if empty if (!user.getProperty(Mailer.UserProperty.class).hasExplicitlyConfiguredAddress()) { user.addProperty(new Mailer.UserProperty(auth.getMyself().getEmail())); } } SecurityListener.fireAuthenticated(new GitLabOAuthUserDetails(self, auth.getAuthorities())); } else { Log.info("Gitlab did not return an access token."); } if (StringUtils.isNotBlank(state)) { return HttpResponses.redirectTo(state); } return HttpResponses.redirectToContextRoot(); }
Example 19
Source File: AbstractBitbucketScmContentProvider.java From blueocean-plugin with MIT License | 4 votes |
@Override @Nonnull protected StandardUsernamePasswordCredentials getCredentialForUser(@Nonnull final Item item, @Nonnull String apiUrl){ User user = User.current(); if(user == null){ //ensure this session has authenticated user throw new ServiceException.UnauthorizedException("No logged in user found"); } StaplerRequest request = Stapler.getCurrentRequest(); String scmId = request.getParameter("scmId"); //get credential for this user AbstractBitbucketScm scm; final BlueOrganization organization = OrganizationFactory.getInstance().getContainingOrg(item); if(BitbucketEndpointConfiguration.normalizeServerUrl(apiUrl) .startsWith(BitbucketEndpointConfiguration.normalizeServerUrl(BitbucketCloudScm.API_URL)) //tests might add scmId to indicate which Scm should be used to find credential //We have to do this because apiUrl might be of WireMock server and not Github || (StringUtils.isNotBlank(scmId) && scmId.equals(BitbucketCloudScm.ID))) { scm = new BitbucketCloudScm(new Reachable() { @Override public Link getLink() { Preconditions.checkNotNull(organization); return organization.getLink().rel("scm"); } }); }else{ //server scm = new BitbucketServerScm((new Reachable() { @Override public Link getLink() { Preconditions.checkNotNull(organization); return organization.getLink().rel("scm"); } })); } //pick up github credential from user's store StandardUsernamePasswordCredentials credential = scm.getCredential(BitbucketEndpointConfiguration.normalizeServerUrl(apiUrl)); if(credential == null){ throw new ServiceException.PreconditionRequired("Can't access content from Bitbucket: no credential found"); } return credential; }
Example 20
Source File: GithubScmContentProvider.java From blueocean-plugin with MIT License | 4 votes |
@Override protected StandardUsernamePasswordCredentials getCredentialForUser(final Item item, String apiUrl){ User user = User.current(); if(user == null){ //ensure this session has authenticated user throw new ServiceException.UnauthorizedException("No logged in user found"); } StaplerRequest request = Stapler.getCurrentRequest(); String scmId = request.getParameter("scmId"); //get credential for this user GithubScm scm; final BlueOrganization organization = OrganizationFactory.getInstance().getContainingOrg(item); if(apiUrl.startsWith(GitHubSCMSource.GITHUB_URL) //tests might add scmId to indicate which Scm should be used to find credential //We have to do this because apiUrl might be of WireMock server and not Github || (StringUtils.isNotBlank(scmId) && scmId.equals(GithubScm.ID))) { scm = new GithubScm(new Reachable() { @Override public Link getLink() { Preconditions.checkNotNull(organization); return organization.getLink().rel("scm"); } }); }else{ //GHE scm = new GithubEnterpriseScm((new Reachable() { @Override public Link getLink() { Preconditions.checkNotNull(organization); return organization.getLink().rel("scm"); } })); } //pick up github credential from user's store StandardUsernamePasswordCredentials githubCredential = scm.getCredential(GithubScm.normalizeUrl(apiUrl)); if(githubCredential == null){ throw new ServiceException.PreconditionRequired("Can't access content from github: no credential found"); } return githubCredential; }