Search in sources :

Example 31 with UsernamePasswordCredentialsProvider

use of org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider in project gerrit by GerritCodeReview.

the class AbstractHttpPushTag method cloneProjectOverHttp.

@Before
public void cloneProjectOverHttp() throws Exception {
    // clone with user to avoid inherited tag permissions of admin user
    CredentialsProvider.setDefault(new UsernamePasswordCredentialsProvider(user.username(), user.httpPassword()));
    testRepo = GitUtil.cloneProject(project, user.getHttpUrl(server) + "/" + project.get());
}
Also used : UsernamePasswordCredentialsProvider(org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider) Before(org.junit.Before)

Example 32 with UsernamePasswordCredentialsProvider

use of org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider in project che by eclipse.

the class JGitConnection method executeRemoteCommand.

/**
     * Execute remote jgit command.
     *
     * @param remoteUrl
     *         remote url
     * @param command
     *         command to execute
     * @return executed command
     * @throws GitException
     * @throws GitAPIException
     * @throws UnauthorizedException
     */
@VisibleForTesting
Object executeRemoteCommand(String remoteUrl, TransportCommand command, @Nullable String username, @Nullable String password) throws GitException, GitAPIException, UnauthorizedException {
    File keyDirectory = null;
    UserCredential credentials = null;
    try {
        if (GitUrlUtils.isSSH(remoteUrl)) {
            keyDirectory = Files.createTempDir();
            final File sshKey = writePrivateKeyFile(remoteUrl, keyDirectory);
            SshSessionFactory sshSessionFactory = new JschConfigSessionFactory() {

                @Override
                protected void configure(OpenSshConfig.Host host, Session session) {
                    session.setConfig("StrictHostKeyChecking", "no");
                }

                @Override
                protected JSch getJSch(final OpenSshConfig.Host hc, FS fs) throws JSchException {
                    JSch jsch = super.getJSch(hc, fs);
                    jsch.removeAllIdentity();
                    jsch.addIdentity(sshKey.getAbsolutePath());
                    return jsch;
                }
            };
            command.setTransportConfigCallback(transport -> {
                if (transport instanceof SshTransport) {
                    ((SshTransport) transport).setSshSessionFactory(sshSessionFactory);
                }
            });
        } else {
            if (remoteUrl != null && GIT_URL_WITH_CREDENTIALS_PATTERN.matcher(remoteUrl).matches()) {
                username = remoteUrl.substring(remoteUrl.indexOf("://") + 3, remoteUrl.lastIndexOf(":"));
                password = remoteUrl.substring(remoteUrl.lastIndexOf(":") + 1, remoteUrl.indexOf("@"));
                command.setCredentialsProvider(new UsernamePasswordCredentialsProvider(username, password));
            } else {
                if (username != null && password != null) {
                    command.setCredentialsProvider(new UsernamePasswordCredentialsProvider(username, password));
                } else {
                    credentials = credentialsLoader.getUserCredential(remoteUrl);
                    if (credentials != null) {
                        command.setCredentialsProvider(new UsernamePasswordCredentialsProvider(credentials.getUserName(), credentials.getPassword()));
                    }
                }
            }
        }
        ProxyAuthenticator.initAuthenticator(remoteUrl);
        return command.call();
    } catch (GitException | TransportException exception) {
        if ("Unable get private ssh key".equals(exception.getMessage())) {
            throw new UnauthorizedException(exception.getMessage(), ErrorCodes.UNABLE_GET_PRIVATE_SSH_KEY);
        } else if (exception.getMessage().contains(ERROR_AUTHENTICATION_REQUIRED)) {
            final ProviderInfo info = credentialsLoader.getProviderInfo(remoteUrl);
            if (info != null) {
                throw new UnauthorizedException(exception.getMessage(), ErrorCodes.UNAUTHORIZED_GIT_OPERATION, ImmutableMap.of(PROVIDER_NAME, info.getProviderName(), AUTHENTICATE_URL, info.getAuthenticateUrl(), "authenticated", Boolean.toString(credentials != null)));
            }
            throw new UnauthorizedException(exception.getMessage(), ErrorCodes.UNAUTHORIZED_GIT_OPERATION);
        } else {
            throw exception;
        }
    } finally {
        if (keyDirectory != null && keyDirectory.exists()) {
            try {
                FileUtils.delete(keyDirectory, FileUtils.RECURSIVE);
            } catch (IOException exception) {
                throw new GitException("Can't remove SSH key directory", exception);
            }
        }
        ProxyAuthenticator.resetAuthenticator();
    }
}
Also used : UserCredential(org.eclipse.che.api.git.UserCredential) UsernamePasswordCredentialsProvider(org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider) GitException(org.eclipse.che.api.git.exception.GitException) IOException(java.io.IOException) SshSessionFactory(org.eclipse.jgit.transport.SshSessionFactory) JSch(com.jcraft.jsch.JSch) FS(org.eclipse.jgit.util.FS) TransportException(org.eclipse.jgit.api.errors.TransportException) ProviderInfo(org.eclipse.che.api.git.shared.ProviderInfo) UnauthorizedException(org.eclipse.che.api.core.UnauthorizedException) JschConfigSessionFactory(org.eclipse.jgit.transport.JschConfigSessionFactory) DiffCommitFile(org.eclipse.che.api.git.shared.DiffCommitFile) File(java.io.File) SshTransport(org.eclipse.jgit.transport.SshTransport) Session(com.jcraft.jsch.Session) VisibleForTesting(com.google.common.annotations.VisibleForTesting)

Example 33 with UsernamePasswordCredentialsProvider

use of org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider in project che by eclipse.

the class JGitConnectionTest method shouldExecuteRemoteCommandByHttpOrHttpsUrlWithCredentials.

@Test(dataProvider = "gitUrlsWithCredentials")
public void shouldExecuteRemoteCommandByHttpOrHttpsUrlWithCredentials(String url) throws Exception {
    //given
    ArgumentCaptor<UsernamePasswordCredentialsProvider> captor = ArgumentCaptor.forClass(UsernamePasswordCredentialsProvider.class);
    Field usernameField = UsernamePasswordCredentialsProvider.class.getDeclaredField("username");
    Field passwordField = UsernamePasswordCredentialsProvider.class.getDeclaredField("password");
    usernameField.setAccessible(true);
    passwordField.setAccessible(true);
    //when
    jGitConnection.executeRemoteCommand(url, transportCommand, null, null);
    //then
    verify(transportCommand).setCredentialsProvider(captor.capture());
    UsernamePasswordCredentialsProvider credentialsProvider = captor.getValue();
    String username = (String) usernameField.get(credentialsProvider);
    char[] password = (char[]) passwordField.get(credentialsProvider);
    assertEquals(username, "username");
    assertEquals(String.valueOf(password), "password");
}
Also used : Field(java.lang.reflect.Field) UsernamePasswordCredentialsProvider(org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider) Matchers.anyString(org.mockito.Matchers.anyString) Test(org.testng.annotations.Test)

Example 34 with UsernamePasswordCredentialsProvider

use of org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider in project gerrit by GerritCodeReview.

the class HttpPushForReviewIT method selectHttpUrl.

@Before
public void selectHttpUrl() throws Exception {
    CredentialsProvider.setDefault(new UsernamePasswordCredentialsProvider(admin.username, admin.httpPassword));
    selectProtocol(Protocol.HTTP);
}
Also used : UsernamePasswordCredentialsProvider(org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider) Before(org.junit.Before)

Example 35 with UsernamePasswordCredentialsProvider

use of org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider in project camel by apache.

the class GitProducer method doPush.

protected void doPush(Exchange exchange, String operation) throws Exception {
    Iterable<PushResult> result = null;
    try {
        if (ObjectHelper.isEmpty(endpoint.getRemoteName())) {
            throw new IllegalArgumentException("Remote name must be specified to execute " + operation);
        }
        if (ObjectHelper.isNotEmpty(endpoint.getBranchName())) {
            git.checkout().setCreateBranch(false).setName(endpoint.getBranchName()).call();
        }
        if (ObjectHelper.isNotEmpty(endpoint.getUsername()) && ObjectHelper.isNotEmpty(endpoint.getPassword())) {
            UsernamePasswordCredentialsProvider credentials = new UsernamePasswordCredentialsProvider(endpoint.getUsername(), endpoint.getPassword());
            result = git.push().setCredentialsProvider(credentials).setRemote(endpoint.getRemoteName()).call();
        } else {
            result = git.push().setRemote(endpoint.getRemoteName()).call();
        }
    } catch (Exception e) {
        LOG.error("There was an error in Git " + operation + " operation");
        throw e;
    }
    updateExchange(exchange, result);
}
Also used : UsernamePasswordCredentialsProvider(org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider) PushResult(org.eclipse.jgit.transport.PushResult) IOException(java.io.IOException)

Aggregations

UsernamePasswordCredentialsProvider (org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider)76 Git (org.eclipse.jgit.api.Git)47 File (java.io.File)34 CredentialsProvider (org.eclipse.jgit.transport.CredentialsProvider)23 IOException (java.io.IOException)19 Test (org.junit.Test)18 CloneCommand (org.eclipse.jgit.api.CloneCommand)17 GitAPIException (org.eclipse.jgit.api.errors.GitAPIException)15 RepositoryModel (com.gitblit.models.RepositoryModel)12 PushResult (org.eclipse.jgit.transport.PushResult)12 RemoteRefUpdate (org.eclipse.jgit.transport.RemoteRefUpdate)9 FileOutputStream (java.io.FileOutputStream)8 PushCommand (org.eclipse.jgit.api.PushCommand)8 RevCommit (org.eclipse.jgit.revwalk.RevCommit)8 BufferedWriter (java.io.BufferedWriter)7 OutputStreamWriter (java.io.OutputStreamWriter)7 Date (java.util.Date)7 Ref (org.eclipse.jgit.lib.Ref)7 Repository (org.eclipse.jgit.lib.Repository)7 URIish (org.eclipse.jgit.transport.URIish)7