com.cloudbees.plugins.credentials.common.StandardCredentials Java Examples

The following examples show how to use com.cloudbees.plugins.credentials.common.StandardCredentials. 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: DockerConnector.java    From yet-another-docker-plugin with MIT License 6 votes vote down vote up
@RequirePOST
public ListBoxModel doFillCredentialsIdItems(@AncestorInPath ItemGroup context) {
    AccessControlled ac = (context instanceof AccessControlled ? (AccessControlled) context : Jenkins.getInstance());
    if (!ac.hasPermission(Jenkins.ADMINISTER)) {
        return new ListBoxModel();
    }

    List<StandardCredentials> credentials =
            CredentialsProvider.lookupCredentials(StandardCredentials.class,
                    context,
                    ACL.SYSTEM,
                    Collections.emptyList());

    return new CredentialsListBoxModel()
            .includeEmptyValue()
            .withMatching(CredentialsMatchers.always(), credentials);
}
 
Example #2
Source File: GlobalKafkaConfiguration.java    From remoting-kafka-plugin with MIT License 6 votes vote down vote up
@RequirePOST
public ListBoxModel doFillKubernetesCredentialsIdItems() {
    Jenkins.get().checkPermission(Jenkins.ADMINISTER);
    return new StandardListBoxModel().withEmptySelection()
            .withMatching(
                    CredentialsMatchers.anyOf(
                            CredentialsMatchers.instanceOf(StandardUsernamePasswordCredentials.class),
                            CredentialsMatchers.instanceOf(FileCredentials.class),
                            CredentialsMatchers.instanceOf(TokenProducer.class),
                            CredentialsMatchers.instanceOf(StandardCertificateCredentials.class),
                            CredentialsMatchers.instanceOf(StringCredentials.class)),
                    CredentialsProvider.lookupCredentials(StandardCredentials.class,
                            Jenkins.get(),
                            ACL.SYSTEM,
                            Collections.EMPTY_LIST
                    ));
}
 
Example #3
Source File: GitPushStep.java    From simple-pull-request-job-plugin with Apache License 2.0 6 votes vote down vote up
protected Void run() throws Exception {
    FilePath ws = getContext().get(FilePath.class);
    TaskListener listener = this.getContext().get(TaskListener.class);
    EnvVars envVars = getContext().get(EnvVars.class);
    WorkflowJob job = getContext().get(WorkflowJob.class);
    GitOperations gitOperations = new GitOperations(ws, listener, envVars, url);
    StandardCredentials c = CredentialsMatchers.firstOrNull(
            CredentialsProvider.lookupCredentials(
                    StandardCredentials.class,
                    job,
                    Tasks.getAuthenticationOf((Queue.Task) job)),
            CredentialsMatchers.withId(credentialId));

    gitOperations.setUsernameAndPasswordCredential((StandardUsernameCredentials) c);
    gitOperations.setCurrentBranch(branch);
    gitOperations.push(true);
    return null;
}
 
Example #4
Source File: GiteaServer.java    From gitea-plugin with MIT License 6 votes vote down vote up
/**
 * Looks up the {@link StandardCredentials} to use for auto-management of hooks.
 *
 * @return the credentials or {@code null}.
 */
@CheckForNull
public StandardCredentials credentials() {
    return StringUtils.isBlank(credentialsId) ? null : CredentialsMatchers.firstOrNull(
            CredentialsProvider.lookupCredentials(
                    StandardCredentials.class,
                    Jenkins.get(),
                    ACL.SYSTEM,
                    URIRequirementBuilder.fromUri(serverUrl).build()
            ),
            CredentialsMatchers.allOf(
                    AuthenticationTokens.matcher(GiteaAuth.class),
                    CredentialsMatchers.withId(credentialsId)
            )
    );
}
 
Example #5
Source File: CliGitAPIImpl.java    From git-client-plugin with MIT License 6 votes vote down vote up
/** {@inheritDoc} */
@Override
public void prune(RemoteConfig repository) throws GitException, InterruptedException {
    String repoName = repository.getName();
    String repoUrl = getRemoteUrl(repoName);
    if (repoUrl != null && !repoUrl.isEmpty()) {
        ArgumentListBuilder args = new ArgumentListBuilder();
        args.add("remote", "prune", repoName);

        StandardCredentials cred = credentials.get(repoUrl);
        if (cred == null) cred = defaultCredentials;

        try {
            launchCommandWithCredentials(args, workspace, cred, new URIish(repoUrl));
        } catch (URISyntaxException ex) {
            throw new GitException("Invalid URL " + repoUrl, ex);
        }
    }
}
 
Example #6
Source File: GitLabServer.java    From gitlab-branch-source-plugin with MIT License 6 votes vote down vote up
/**
 * Stapler form completion.
 *
 * @param serverUrl the server URL.
 * @param credentialsId the credentials Id
 * @return the available credentials.
 */
@Restricted(NoExternalUse.class) // stapler
@SuppressWarnings("unused")
public ListBoxModel doFillCredentialsIdItems(@QueryParameter String serverUrl,
    @QueryParameter String credentialsId) {
    Jenkins jenkins = Jenkins.get();
    if (!jenkins.hasPermission(Jenkins.ADMINISTER)) {
        return new StandardListBoxModel().includeCurrentValue(credentialsId);
    }
    return new StandardListBoxModel()
        .includeEmptyValue()
        .includeMatchingAs(ACL.SYSTEM,
            jenkins,
            StandardCredentials.class,
            fromUri(serverUrl).build(),
            CREDENTIALS_MATCHER
        );
}
 
Example #7
Source File: CliGitAPIImpl.java    From git-client-plugin with MIT License 6 votes vote down vote up
/** {@inheritDoc} */
@Override
public ObjectId getHeadRev(String url, String branchSpec) throws GitException, InterruptedException {
    final String branchName = extractBranchNameFromBranchSpec(branchSpec);
    ArgumentListBuilder args = new ArgumentListBuilder("ls-remote");
    if(!branchName.startsWith("refs/tags/")) {
        args.add("-h");
    }

    StandardCredentials cred = credentials.get(url);
    if (cred == null) cred = defaultCredentials;

    addCheckedRemoteUrl(args, url);

    if (branchName.startsWith("refs/tags/")) {
        args.add(branchName+"^{}"); // JENKINS-23299 - tag SHA1 needs to be converted to commit SHA1
    } else {
        args.add(branchName);
    }
    String result = launchCommandWithCredentials(args, null, cred, url);
    return result.length()>=40 ? ObjectId.fromString(result.substring(0, 40)) : null;
}
 
Example #8
Source File: CliGitAPIImpl.java    From git-client-plugin with MIT License 6 votes vote down vote up
/** {@inheritDoc} */
@Override
public Map<String, ObjectId> getHeadRev(String url) throws GitException, InterruptedException {
    ArgumentListBuilder args = new ArgumentListBuilder("ls-remote");
    args.add("-h");
    addCheckedRemoteUrl(args, url);

    StandardCredentials cred = credentials.get(url);
    if (cred == null) cred = defaultCredentials;

    String result = launchCommandWithCredentials(args, null, cred, url);

    Map<String, ObjectId> heads = new HashMap<>();
    String[] lines = result.split("\n");
    for (String line : lines) {
        if (line.length() >= 41) {
            heads.put(line.substring(41), ObjectId.fromString(line.substring(0, 40)));
        } else {
            listener.getLogger().println("Unexpected ls-remote output line '" + line + "'");
        }
    }
    return heads;
}
 
Example #9
Source File: GiteaServer.java    From gitea-plugin with MIT License 6 votes vote down vote up
/**
 * Stapler form completion.
 *
 * @param serverUrl the server URL.
 * @return the available credentials.
 */
@Restricted(NoExternalUse.class) // stapler
@SuppressWarnings("unused")
public ListBoxModel doFillCredentialsIdItems(@QueryParameter String serverUrl) {
    Jenkins.get().checkPermission(Jenkins.ADMINISTER);
    StandardListBoxModel result = new StandardListBoxModel();
    serverUrl = GiteaServers.normalizeServerUrl(serverUrl);
    result.includeMatchingAs(
            ACL.SYSTEM,
            Jenkins.get(),
            StandardCredentials.class,
            URIRequirementBuilder.fromUri(serverUrl).build(),
            AuthenticationTokens.matcher(GiteaAuth.class)
    );
    return result;
}
 
Example #10
Source File: BuildScanner.java    From acunetix-plugin with MIT License 6 votes vote down vote up
private String getgApiKey() {
    StandardCredentials credentials = null;
    try {
        credentials = CredentialsMatchers.firstOrNull(
                lookupCredentials(StandardCredentials.class, (Item) null, ACL.SYSTEM, new ArrayList<DomainRequirement>()),
                CredentialsMatchers.withId(gApiKeyID));
    }
    catch (NullPointerException e) {
        throw new ConnectionException(SR.getString("api.key.not.set"));
    }
    if (credentials != null) {
        if (credentials instanceof StringCredentials) {
            return ((StringCredentials) credentials).getSecret().getPlainText();
        }
    }
    throw new IllegalStateException("Could not find Acunetix API Key ID: " + gApiKeyID);
}
 
Example #11
Source File: CredentialsHelper.java    From violation-comments-to-github-plugin with MIT License 6 votes vote down vote up
@SuppressFBWarnings("NP_NULL_PARAM_DEREF")
public static ListBoxModel doFillCredentialsIdItems(
    final Item item, final String credentialsId, final String uri) {
  final StandardListBoxModel result = new StandardListBoxModel();
  if (item == null) {
    if (!Jenkins.getInstance().hasPermission(Jenkins.ADMINISTER)) {
      return result.includeCurrentValue(credentialsId);
    }
  } else {
    if (!item.hasPermission(Item.EXTENDED_READ)
        && !item.hasPermission(CredentialsProvider.USE_ITEM)) {
      return result.includeCurrentValue(credentialsId);
    }
  }
  return result //
      .includeEmptyValue() //
      .includeMatchingAs(
          item instanceof Queue.Task ? Tasks.getAuthenticationOf((Queue.Task) item) : ACL.SYSTEM,
          item,
          StandardCredentials.class,
          URIRequirementBuilder.fromUri(uri).build(),
          CredentialsMatchers.anyOf(
              CredentialsMatchers.instanceOf(StandardUsernamePasswordCredentials.class),
              CredentialsMatchers.instanceOf(StringCredentials.class)))
      .includeCurrentValue(credentialsId);
}
 
Example #12
Source File: CredentialsHelper.java    From violation-comments-to-github-plugin with MIT License 6 votes vote down vote up
public static Optional<StandardCredentials> findCredentials(
    final Item item, final String credentialsId, final String uri) {
  if (isNullOrEmpty(credentialsId)) {
    return absent();
  }
  return fromNullable(
      CredentialsMatchers.firstOrNull(
          CredentialsProvider.lookupCredentials(
              StandardCredentials.class,
              item,
              item instanceof Queue.Task
                  ? Tasks.getAuthenticationOf((Queue.Task) item)
                  : ACL.SYSTEM,
              URIRequirementBuilder.fromUri(uri).build()),
          CredentialsMatchers.allOf(
              CredentialsMatchers.withId(credentialsId),
              CredentialsMatchers.anyOf(
                  CredentialsMatchers.instanceOf(StandardUsernamePasswordCredentials.class),
                  CredentialsMatchers.instanceOf(StringCredentials.class)))));
}
 
Example #13
Source File: GitScm.java    From blueocean-plugin with MIT License 6 votes vote down vote up
protected StandardCredentials getCredentialForCurrentRequest() {
    final StaplerRequest request = getStaplerRequest();

    String credentialId = null;

    if (request.hasParameter("credentialId")) {
        credentialId = request.getParameter("credentialId");
    } else {
        if (!request.hasParameter("repositoryUrl")) {
            // No linked credential unless a specific repo
            return null;
        }

        String repositoryUrl = request.getParameter("repositoryUrl");
        credentialId = makeCredentialId(repositoryUrl);
    }

    if (credentialId == null) {
        return null;
    }

    return CredentialsUtils.findCredential(credentialId, StandardCredentials.class, new BlueOceanDomainRequirement());
}
 
Example #14
Source File: GitPipelineCreateRequest.java    From blueocean-plugin with MIT License 6 votes vote down vote up
@Override
protected List<Error> validate(String name, BlueScmConfig scmConfig) {
    List<Error> errors = Lists.newArrayList();
    if (scmConfig.getUri() == null) {
        errors.add(new ErrorMessage.Error("scmConfig.uri", ErrorMessage.Error.ErrorCodes.MISSING.toString(), "uri is required"));
    }else {
        StandardCredentials credentials = null;
        String credentialId = computeCredentialId(scmConfig);
        if(credentialId != null){
            credentials = GitUtils.getCredentials(Jenkins.getInstance(), scmConfig.getUri(), credentialId);
            if (credentials == null) {
                errors.add(new ErrorMessage.Error("scmConfig.credentialId",
                    ErrorMessage.Error.ErrorCodes.NOT_FOUND.toString(),
                    String.format("credentialId: %s not found", credentialId)));
            }
        }
        //validate credentials if no credential id (perhaps git repo doesn't need auth or credentials is present)
        if(credentialId == null || credentials != null) {
            errors.addAll(GitUtils.validateCredentials(scmConfig.getUri(), credentials));
        }
    }
    return errors;
}
 
Example #15
Source File: GitReadSaveRequest.java    From blueocean-plugin with MIT License 6 votes vote down vote up
@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 #16
Source File: CredentialsHelper.java    From violation-comments-to-stash-plugin with MIT License 6 votes vote down vote up
@SuppressFBWarnings("NP_NULL_PARAM_DEREF")
public static ListBoxModel doFillCredentialsIdItems(
    final Item item, final String credentialsId, final String uri) {
  final StandardListBoxModel result = new StandardListBoxModel();
  if (item == null) {
    if (!Jenkins.getInstance().hasPermission(Jenkins.ADMINISTER)) {
      return result.includeCurrentValue(credentialsId);
    }
  } else {
    if (!item.hasPermission(Item.EXTENDED_READ)
        && !item.hasPermission(CredentialsProvider.USE_ITEM)) {
      return result.includeCurrentValue(credentialsId);
    }
  }
  return result //
      .includeEmptyValue() //
      .includeMatchingAs(
          item instanceof Queue.Task ? Tasks.getAuthenticationOf((Queue.Task) item) : ACL.SYSTEM,
          item,
          StandardCredentials.class,
          URIRequirementBuilder.fromUri(uri).build(),
          CredentialsMatchers.anyOf(
              CredentialsMatchers.instanceOf(StandardUsernamePasswordCredentials.class),
              CredentialsMatchers.instanceOf(StringCredentials.class)))
      .includeCurrentValue(credentialsId);
}
 
Example #17
Source File: CredentialsHelper.java    From violation-comments-to-stash-plugin with MIT License 6 votes vote down vote up
public static Optional<StandardCredentials> findCredentials(
    final Item item, final String credentialsId, final String uri) {
  if (isNullOrEmpty(credentialsId)) {
    return absent();
  }
  return fromNullable(
      CredentialsMatchers.firstOrNull(
          CredentialsProvider.lookupCredentials(
              StandardCredentials.class,
              item,
              item instanceof Queue.Task
                  ? Tasks.getAuthenticationOf((Queue.Task) item)
                  : ACL.SYSTEM,
              URIRequirementBuilder.fromUri(uri).build()),
          CredentialsMatchers.allOf(
              CredentialsMatchers.withId(credentialsId),
              CredentialsMatchers.anyOf(
                  CredentialsMatchers.instanceOf(StandardUsernamePasswordCredentials.class),
                  CredentialsMatchers.instanceOf(StringCredentials.class)))));
}
 
Example #18
Source File: ConduitCredentialsDescriptor.java    From phabricator-jenkins-plugin with MIT License 6 votes vote down vote up
public static ListBoxModel doFillCredentialsIDItems(@AncestorInPath Jenkins context) {
    if (context == null || !context.hasPermission(Item.CONFIGURE)) {
        return new StandardListBoxModel();
    }

    List<DomainRequirement> domainRequirements = new ArrayList<DomainRequirement>();
    return new StandardListBoxModel()
            .withEmptySelection()
            .withMatching(
                    CredentialsMatchers.anyOf(
                            CredentialsMatchers.instanceOf(ConduitCredentials.class)),
                    CredentialsProvider.lookupCredentials(
                            StandardCredentials.class,
                            context,
                            ACL.SYSTEM,
                            domainRequirements));
}
 
Example #19
Source File: GitLabConnection.java    From gitlab-plugin with GNU General Public License v2.0 6 votes vote down vote up
@Restricted(NoExternalUse.class)
private String getApiToken(String apiTokenId, Item item) {
    ItemGroup<?> context = null != item ? item.getParent() : Jenkins.get();
    StandardCredentials credentials = CredentialsMatchers.firstOrNull(
        lookupCredentials(
                StandardCredentials.class,
                context, 
                ACL.SYSTEM,
                URIRequirementBuilder.fromUri(url).build()),
        CredentialsMatchers.withId(apiTokenId));
    if (credentials != null) {
        if (credentials instanceof GitLabApiToken) {
            return ((GitLabApiToken) credentials).getApiToken().getPlainText();
        }
        if (credentials instanceof StringCredentials) {
            return ((StringCredentials) credentials).getSecret().getPlainText();
        }
    }
    throw new IllegalStateException("No credentials found for credentialsId: " + apiTokenId);
}
 
Example #20
Source File: GitHubSCMNavigator.java    From github-branch-source-plugin with MIT License 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void afterSave(@NonNull SCMNavigatorOwner owner) {
    GitHubWebHook.get().registerHookFor(owner);
    try {
        // FIXME MINOR HACK ALERT
        StandardCredentials credentials = Connector.lookupScanCredentials((Item)owner, getApiUri(), credentialsId);
        GitHub hub = Connector.connect(getApiUri(), credentials);
        try {
            GitHubOrgWebHook.register(hub, repoOwner);
        } finally {
            Connector.release(hub);
        }
    } catch (IOException e) {
        DescriptorImpl.LOGGER.log(Level.WARNING, e.getMessage(), e);
    }
}
 
Example #21
Source File: SmartCredentialsProvider.java    From git-client-plugin with MIT License 6 votes vote down vote up
/** {@inheritDoc} */
@Override
public synchronized boolean supports(CredentialItem... credentialItems) {
    items:
    for (CredentialItem item : credentialItems) {
        if (supports(defaultCredentials, item)) {
            continue;
        }
        for (StandardCredentials c : specificCredentials.values()) {
            if (supports(c, item)) {
                continue items;
            }
        }
        return false;
    }
    return true;
}
 
Example #22
Source File: Connector.java    From github-branch-source-plugin with MIT License 6 votes vote down vote up
/**
 * Resolves the specified scan credentials in the specified context for use against the specified API endpoint.
 *
 * @param context           the context.
 * @param apiUri            the API endpoint.
 * @param scanCredentialsId the credentials to resolve.
 * @return the {@link StandardCredentials} or {@code null}
 */
@CheckForNull
public static StandardCredentials lookupScanCredentials(@CheckForNull Item context,
                                                        @CheckForNull String apiUri,
                                                        @CheckForNull String scanCredentialsId) {
    if (Util.fixEmpty(scanCredentialsId) == null) {
        return null;
    } else {
        return CredentialsMatchers.firstOrNull(
            CredentialsProvider.lookupCredentials(
                StandardUsernameCredentials.class,
                context,
                context instanceof Queue.Task
                        ? ((Queue.Task) context).getDefaultAuthentication()
                        : ACL.SYSTEM,
                githubDomainRequirements(apiUri)
            ),
            CredentialsMatchers.allOf(CredentialsMatchers.withId(scanCredentialsId), githubScanCredentialsMatcher())
        );
    }
}
 
Example #23
Source File: Connector.java    From github-branch-source-plugin with MIT License 6 votes vote down vote up
public static void checkApiUrlValidity(@Nonnull GitHub gitHub, @CheckForNull StandardCredentials credentials) throws IOException {
    String hash;
    if (credentials == null) {
        hash = "anonymous";
    } else if (credentials instanceof StandardUsernamePasswordCredentials) {
        StandardUsernamePasswordCredentials c = (StandardUsernamePasswordCredentials) credentials;
        hash = Util.getDigestOf(c.getPassword().getPlainText() + SALT);
    } else {
        // TODO OAuth support
        throw new IOException("Unsupported credential type: " + credentials.getClass().getName());
    }
    String key = gitHub.getApiUrl() + "::" + hash;
    synchronized (apiUrlValid) {
        Long last = apiUrlValid.get(key);
        if (last != null && last > System.currentTimeMillis() - API_URL_REVALIDATE_MILLIS) {
            return;
        }
        gitHub.checkApiUrlValidity();
        apiUrlValid.put(key, System.currentTimeMillis());
    }
}
 
Example #24
Source File: DockerRegistryEndpoint.java    From docker-commons-plugin with MIT License 6 votes vote down vote up
public ListBoxModel doFillCredentialsIdItems(@AncestorInPath Item item) {
    if (item == null && !Jenkins.getActiveInstance().hasPermission(Jenkins.ADMINISTER) ||
        item != null && !item.hasPermission(Item.EXTENDED_READ)) {
        return new StandardListBoxModel();
    }
    // TODO may also need to specify a specific authentication and domain requirements
    return new StandardListBoxModel()
            .withEmptySelection()
            .withMatching(AuthenticationTokens.matcher(DockerRegistryToken.class),
                    CredentialsProvider.lookupCredentials(
                            StandardCredentials.class,
                            item,
                            null,
                            Collections.<DomainRequirement>emptyList()
                    )
            );
}
 
Example #25
Source File: KubernetesCloud.java    From kubernetes-plugin with Apache License 2.0 6 votes vote down vote up
@RequirePOST
@SuppressWarnings("unused") // used by jelly
public ListBoxModel doFillCredentialsIdItems(@AncestorInPath ItemGroup context, @QueryParameter String serverUrl) {
    Jenkins.get().checkPermission(Jenkins.ADMINISTER);
    StandardListBoxModel result = new StandardListBoxModel();
    result.includeEmptyValue();
    result.includeMatchingAs(
        ACL.SYSTEM,
        context,
        StandardCredentials.class,
        serverUrl != null ? URIRequirementBuilder.fromUri(serverUrl).build()
                    : Collections.EMPTY_LIST,
        CredentialsMatchers.anyOf(
            AuthenticationTokens.matcher(KubernetesAuth.class)
        )
    );
    return result;
}
 
Example #26
Source File: KubernetesFactoryAdapter.java    From kubernetes-plugin with Apache License 2.0 6 votes vote down vote up
@CheckForNull
private static StandardCredentials resolveCredentials(@CheckForNull String credentialsId) {
    if (credentialsId == null) {
        return null;
    }
    return CredentialsMatchers.firstOrNull(
            CredentialsProvider.lookupCredentials(
                    StandardCredentials.class,
                    Jenkins.get(),
                    ACL.SYSTEM,
                    Collections.emptyList()
            ),
            CredentialsMatchers.allOf(
                    AuthenticationTokens.matcher(KubernetesAuth.class),
                    CredentialsMatchers.withId(credentialsId)
            )
    );
}
 
Example #27
Source File: GitUtils.java    From blueocean-plugin with MIT License 6 votes vote down vote up
public static void fetch(final Repository repo, final StandardCredentials credential) {
    try (org.eclipse.jgit.api.Git git = new org.eclipse.jgit.api.Git(repo)) {
        FetchCommand fetchCommand = git.fetch();

        addCredential(repo, fetchCommand, credential);

        fetchCommand.setRemote("origin")
            .setRemoveDeletedRefs(true)
            .setRefSpecs(new RefSpec("+refs/heads/*:refs/remotes/origin/*"))
            .call();
    } catch (GitAPIException ex) {
        if (ex.getMessage().contains("Auth fail")) {
            throw new ServiceException.UnauthorizedException("Not authorized", ex);
        }
        throw new RuntimeException(ex);
    }
}
 
Example #28
Source File: GitHubSCMSource.java    From github-branch-source-plugin with MIT License 5 votes vote down vote up
public LazyContributorNames(GitHubSCMSourceRequest request,
                            TaskListener listener, GitHub github, GHRepository repo,
                            StandardCredentials credentials) {
    this.request = request;
    this.listener = listener;
    this.github = github;
    this.repo = repo;
    this.credentials = credentials;
}
 
Example #29
Source File: GitHubSCMSource.java    From github-branch-source-plugin with MIT License 5 votes vote down vote up
@Override
public GHPermissionType fetch(String username) throws IOException, InterruptedException {
    if (repo == null) {
        listener.getLogger().format("Connecting to %s to check permissions of obtain list of %s for %s/%s%n",
                apiUri, username, repoOwner, repository);
        StandardCredentials credentials = Connector.lookupScanCredentials(
                (Item) getOwner(), apiUri, credentialsId
        );
        github = Connector.connect(apiUri, credentials);
        String fullName = repoOwner + "/" + repository;
        repo = github.getRepository(fullName);
    }
    return repo.getPermission(username);
}
 
Example #30
Source File: GiteaSCMNavigator.java    From gitea-plugin with MIT License 5 votes vote down vote up
public FormValidation doCheckCredentialsId(@AncestorInPath SCMSourceOwner context,
                                           @QueryParameter String serverUrl,
                                           @QueryParameter String value)
        throws IOException, InterruptedException {
    if (context == null) {
        if (!Jenkins.get().hasPermission(Jenkins.ADMINISTER)) {
            return FormValidation.ok();
        }
    } else {
        if (!context.hasPermission(Item.EXTENDED_READ)
                && !context.hasPermission(CredentialsProvider.USE_ITEM)) {
            return FormValidation.ok();
        }
    }
    GiteaServer server = GiteaServers.get().findServer(serverUrl);
    if (server == null) {
        return FormValidation.ok();
    }
    if (StringUtils.isBlank(value)) {
        return FormValidation.ok();
    }
    if (CredentialsProvider.listCredentials(
            StandardCredentials.class,
            context,
            context instanceof Queue.Task ?
                    ((Queue.Task) context).getDefaultAuthentication()
                    : ACL.SYSTEM,
            URIRequirementBuilder.fromUri(serverUrl).build(),
            CredentialsMatchers.allOf(
                    CredentialsMatchers.withId(value),
                    AuthenticationTokens.matcher(GiteaAuth.class)

            )).isEmpty()) {
        return FormValidation.error(Messages.GiteaSCMNavigator_selectedCredentialsMissing());
    }
    return FormValidation.ok();
}