Search in sources :

Example 11 with User

use of hudson.model.User in project blueocean-plugin by jenkinsci.

the class GitCacheCloneReadSaveRequest method getActiveRepository.

@Nonnull
private Git getActiveRepository(Repository repository) throws IOException {
    try {
        // Clone the bare repository
        File cloneDir = File.createTempFile("clone", "");
        if (cloneDir.exists()) {
            if (cloneDir.isDirectory()) {
                FileUtils.deleteDirectory(cloneDir);
            } else {
                if (!cloneDir.delete()) {
                    throw new ServiceException.UnexpectedErrorException("Unable to delete repository clone");
                }
            }
        }
        if (!cloneDir.mkdirs()) {
            throw new ServiceException.UnexpectedErrorException("Unable to create repository clone directory");
        }
        String url = repository.getConfig().getString("remote", "origin", "url");
        Git gitClient = Git.cloneRepository().setCloneAllBranches(false).setProgressMonitor(new CloneProgressMonitor(url)).setURI(repository.getDirectory().getCanonicalPath()).setDirectory(cloneDir).call();
        RemoteRemoveCommand remove = gitClient.remoteRemove();
        remove.setName("origin");
        remove.call();
        RemoteAddCommand add = gitClient.remoteAdd();
        add.setName("origin");
        add.setUri(new URIish(gitSource.getRemote()));
        add.call();
        if (GitUtils.isSshUrl(gitSource.getRemote())) {
            // Get committer info and credentials
            User user = User.current();
            if (user == null) {
                throw new ServiceException.UnauthorizedException("Not authenticated");
            }
            BasicSSHUserPrivateKey privateKey = UserSSHKeyManager.getOrCreate(user);
            // Make sure up-to-date and credentials work
            GitUtils.fetch(repository, privateKey);
        } else {
            FetchCommand fetch = gitClient.fetch();
            fetch.call();
        }
        if (!StringUtils.isEmpty(sourceBranch) && !sourceBranch.equals(branch)) {
            CheckoutCommand checkout = gitClient.checkout();
            checkout.setStartPoint("origin/" + sourceBranch);
            checkout.setName(sourceBranch);
            // to create a new local branch
            checkout.setCreateBranch(true);
            checkout.setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.NOTRACK);
            checkout.call();
            checkout = gitClient.checkout();
            checkout.setName(branch);
            // this *should* be a new branch
            checkout.setCreateBranch(true);
            checkout.setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.NOTRACK);
            checkout.call();
        } else {
            CheckoutCommand checkout = gitClient.checkout();
            checkout.setStartPoint("origin/" + branch);
            checkout.setName(branch);
            // to create a new local branch
            checkout.setCreateBranch(true);
            checkout.setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.NOTRACK);
            checkout.call();
        }
        return gitClient;
    } catch (GitAPIException | URISyntaxException ex) {
        throw new ServiceException.UnexpectedErrorException("Unable to get working repository directory", ex);
    }
}
Also used : URIish(org.eclipse.jgit.transport.URIish) CheckoutCommand(org.eclipse.jgit.api.CheckoutCommand) User(hudson.model.User) RemoteRemoveCommand(org.eclipse.jgit.api.RemoteRemoveCommand) RemoteAddCommand(org.eclipse.jgit.api.RemoteAddCommand) URISyntaxException(java.net.URISyntaxException) BasicSSHUserPrivateKey(com.cloudbees.jenkins.plugins.sshcredentials.impl.BasicSSHUserPrivateKey) GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) Git(org.eclipse.jgit.api.Git) ServiceException(io.jenkins.blueocean.commons.ServiceException) FetchCommand(org.eclipse.jgit.api.FetchCommand) File(java.io.File) Nonnull(javax.annotation.Nonnull)

Example 12 with User

use of hudson.model.User in project blueocean-plugin by jenkinsci.

the class GitReadSaveRequest method getCredential.

@CheckForNull
StandardCredentials getCredential() {
    StandardCredentials credential = null;
    if (GitUtils.isSshUrl(gitSource.getRemote()) || GitUtils.isLocalUnixFileUrl(gitSource.getRemote())) {
        // Get committer info and credentials
        User user = User.current();
        if (user == null) {
            throw new ServiceException.UnauthorizedException("Not authenticated");
        }
        credential = UserSSHKeyManager.getOrCreate(user);
    } else {
        throw new ServiceException.UnauthorizedException("Editing only supported for repositories using SSH");
    }
    return credential;
}
Also used : User(hudson.model.User) StandardCredentials(com.cloudbees.plugins.credentials.common.StandardCredentials) CheckForNull(javax.annotation.CheckForNull)

Example 13 with User

use of hudson.model.User in project blueocean-plugin by jenkinsci.

the class GitReadSaveService method getContent.

@Override
public Object getContent(@Nonnull StaplerRequest req, @Nonnull Item item) {
    item.checkPermission(Item.READ);
    User user = User.current();
    if (user == null) {
        throw new ServiceException.UnauthorizedException("Not authenticated");
    }
    GitReadSaveRequest r = makeSaveRequest(item, req);
    try {
        String encoded = Base64.encode(r.read());
        return new GitFile(new GitContent(r.filePath, user.getId(), r.gitSource.getRemote(), r.filePath, 0, "sha", encoded, "", r.branch, r.sourceBranch, true, ""));
    } catch (ServiceException.UnauthorizedException e) {
        // if (r.gitSource.getRemote().matches("([^@:]+@.*|ssh://.*)"))
        throw new ServiceException.PreconditionRequired("Invalid credential", e);
    } catch (IOException e) {
        throw new ServiceException.UnexpectedErrorException("Unable to get file content", e);
    }
}
Also used : User(hudson.model.User) ServiceException(io.jenkins.blueocean.commons.ServiceException) IOException(java.io.IOException) GitContent(io.jenkins.blueocean.rest.impl.pipeline.scm.GitContent)

Example 14 with User

use of hudson.model.User in project blueocean-plugin by jenkinsci.

the class GitReadSaveTest method bareRepoReadWriteNoEmail.

@Test
public void bareRepoReadWriteNoEmail() throws Exception {
    if (!OsUtils.isUNIX()) {
        // can't really run this on windows
        return;
    }
    User user = login("bob", "Bob Smith", null);
    startSSH(user);
    String userHostPort = "bob@127.0.0.1:" + sshd.getPort();
    String remote = "ssh://" + userHostPort + "" + repoForSSH.getRoot().getCanonicalPath() + "/.git";
    testGitReadWrite(GitReadSaveService.ReadSaveType.CACHE_BARE, remote, repoForSSH, masterPipelineScript, user);
}
Also used : User(hudson.model.User) PipelineBaseTest(io.jenkins.blueocean.rest.impl.pipeline.PipelineBaseTest) Test(org.junit.Test)

Example 15 with User

use of hudson.model.User in project blueocean-plugin by jenkinsci.

the class GitReadSaveTest method startSSH.

private void startSSH(@Nullable User u) throws Exception {
    if (sshd == null) {
        // Set up an SSH server with access to a git repo
        User user;
        if (u == null) {
            user = login();
        } else {
            user = u;
        }
        final BasicSSHUserPrivateKey key = UserSSHKeyManager.getOrCreate(user);
        final JSch jsch = new JSch();
        final KeyPair pair = KeyPair.load(jsch, key.getPrivateKey().getBytes(), null);
        File keyFile = new File(System.getProperty("TEST_SSH_SERVER_KEY_FILE", File.createTempFile("hostkey", "ser").getCanonicalPath()));
        int port = Integer.parseInt(System.getProperty("TEST_SSH_SERVER_PORT", "0"));
        boolean allowLocalUser = Boolean.getBoolean("TEST_SSH_SERVER_ALLOW_LOCAL");
        String userPublicKey = Base64.encode(pair.getPublicKeyBlob());
        sshd = new SSHServer(repoForSSH.getRoot(), keyFile, port, allowLocalUser, ImmutableMap.of("bob", userPublicKey), true);
        // Go, go, go
        sshd.start();
    }
}
Also used : KeyPair(com.jcraft.jsch.KeyPair) SSHServer(io.jenkins.blueocean.test.ssh.SSHServer) User(hudson.model.User) JSch(com.jcraft.jsch.JSch) File(java.io.File) BasicSSHUserPrivateKey(com.cloudbees.jenkins.plugins.sshcredentials.impl.BasicSSHUserPrivateKey)

Aggregations

User (hudson.model.User)105 Test (org.junit.Test)71 Map (java.util.Map)42 ImmutableMap (com.google.common.collect.ImmutableMap)38 PipelineBaseTest (io.jenkins.blueocean.rest.impl.pipeline.PipelineBaseTest)26 Mailer (hudson.tasks.Mailer)24 ServiceException (io.jenkins.blueocean.commons.ServiceException)21 StaplerRequest (org.kohsuke.stapler.StaplerRequest)14 MultiBranchProject (jenkins.branch.MultiBranchProject)13 List (java.util.List)12 JSONObject (net.sf.json.JSONObject)12 GitContent (io.jenkins.blueocean.rest.impl.pipeline.scm.GitContent)8 IOException (java.io.IOException)8 Domain (com.cloudbees.plugins.credentials.domains.Domain)7 BlueOceanDomainRequirement (io.jenkins.blueocean.rest.impl.pipeline.credential.BlueOceanDomainRequirement)7 Authentication (org.acegisecurity.Authentication)7 CredentialsStore (com.cloudbees.plugins.credentials.CredentialsStore)6 StandardUsernamePasswordCredentials (com.cloudbees.plugins.credentials.common.StandardUsernamePasswordCredentials)6 BufferedReader (java.io.BufferedReader)6 StringReader (java.io.StringReader)6