Search in sources :

Example 6 with UnauthorizedException

use of org.eclipse.che.api.core.UnauthorizedException in project che by eclipse.

the class RemoteOAuthTokenProvider method getToken.

/** {@inheritDoc} */
@Override
public OAuthToken getToken(String oauthProviderName, String userId) throws IOException {
    if (userId.isEmpty()) {
        return null;
    }
    try {
        UriBuilder ub = UriBuilder.fromUri(apiEndpoint).path(OAuthAuthenticationService.class).path(OAuthAuthenticationService.class, "token").queryParam("oauth_provider", oauthProviderName);
        Link getTokenLink = DtoFactory.newDto(Link.class).withHref(ub.build().toString()).withMethod("GET");
        return httpJsonRequestFactory.fromLink(getTokenLink).request().asDto(OAuthToken.class);
    } catch (NotFoundException ne) {
        LOG.warn("Token not found for user {}", userId);
        return null;
    } catch (ServerException | UnauthorizedException | ForbiddenException | ConflictException | BadRequestException e) {
        LOG.warn("Exception on token retrieval, message : {}", e.getLocalizedMessage());
        return null;
    }
}
Also used : ForbiddenException(org.eclipse.che.api.core.ForbiddenException) ServerException(org.eclipse.che.api.core.ServerException) ConflictException(org.eclipse.che.api.core.ConflictException) UnauthorizedException(org.eclipse.che.api.core.UnauthorizedException) NotFoundException(org.eclipse.che.api.core.NotFoundException) BadRequestException(org.eclipse.che.api.core.BadRequestException) UriBuilder(javax.ws.rs.core.UriBuilder) Link(org.eclipse.che.api.core.rest.shared.dto.Link)

Example 7 with UnauthorizedException

use of org.eclipse.che.api.core.UnauthorizedException in project che by eclipse.

the class ProjectManager method doImportProject.

/** Note: Use {@link FileWatcherManager#suspend()} and {@link FileWatcherManager#resume()} while importing source code */
private RegisteredProject doImportProject(String path, SourceStorage sourceStorage, boolean rewrite, LineConsumerFactory lineConsumerFactory) throws ServerException, IOException, ForbiddenException, UnauthorizedException, ConflictException, NotFoundException {
    final ProjectImporter importer = importers.getImporter(sourceStorage.getType());
    if (importer == null) {
        throw new NotFoundException(format("Unable import sources project from '%s'. Sources type '%s' is not supported.", sourceStorage.getLocation(), sourceStorage.getType()));
    }
    String normalizePath = (path.startsWith("/")) ? path : "/".concat(path);
    FolderEntry folder = asFolder(normalizePath);
    if (folder != null && !rewrite) {
        throw new ConflictException(format("Project %s already exists ", path));
    }
    if (folder == null) {
        folder = getProjectsRoot().createFolder(normalizePath);
    }
    try {
        importer.importSources(folder, sourceStorage, lineConsumerFactory);
    } catch (final Exception e) {
        folder.remove();
        throw e;
    }
    final String name = folder.getPath().getName();
    for (ProjectConfig project : workspaceProjectsHolder.getProjects()) {
        if (normalizePath.equals(project.getPath())) {
            // TODO Needed for factory project importing with keepDir. It needs to find more appropriate solution
            List<String> innerProjects = projectRegistry.getProjects(normalizePath);
            for (String innerProject : innerProjects) {
                RegisteredProject registeredProject = projectRegistry.getProject(innerProject);
                projectRegistry.putProject(registeredProject, asFolder(registeredProject.getPath()), true, false);
            }
            RegisteredProject rp = projectRegistry.putProject(project, folder, true, false);
            workspaceProjectsHolder.sync(projectRegistry);
            return rp;
        }
    }
    RegisteredProject rp = projectRegistry.putProject(new NewProjectConfigImpl(normalizePath, name, BaseProjectType.ID, sourceStorage), folder, true, false);
    workspaceProjectsHolder.sync(projectRegistry);
    return rp;
}
Also used : ProjectConfig(org.eclipse.che.api.core.model.project.ProjectConfig) NewProjectConfig(org.eclipse.che.api.core.model.project.NewProjectConfig) ConflictException(org.eclipse.che.api.core.ConflictException) NotFoundException(org.eclipse.che.api.core.NotFoundException) UnauthorizedException(org.eclipse.che.api.core.UnauthorizedException) BadRequestException(org.eclipse.che.api.core.BadRequestException) ConflictException(org.eclipse.che.api.core.ConflictException) IOException(java.io.IOException) NotFoundException(org.eclipse.che.api.core.NotFoundException) ServerException(org.eclipse.che.api.core.ServerException) ForbiddenException(org.eclipse.che.api.core.ForbiddenException) ProjectImporter(org.eclipse.che.api.project.server.importer.ProjectImporter)

Example 8 with UnauthorizedException

use of org.eclipse.che.api.core.UnauthorizedException in project che by eclipse.

the class SubversionApi method runCommand.

private CommandLineResult runCommand(@Nullable Map<String, String> env, List<String> args, File projectPath, List<String> paths, @Nullable String username, @Nullable String password, String repoUrl) throws SubversionException, UnauthorizedException {
    final List<String> lines = new ArrayList<>();
    final CommandLineResult result;
    final StringBuffer buffer;
    boolean isWarning = false;
    // Add paths to the end of the list of arguments
    for (final String path : paths) {
        args.add(path);
    }
    String[] credentialsArgs;
    if (!isNullOrEmpty(username) && !isNullOrEmpty(password)) {
        credentialsArgs = new String[] { "--username", username, "--password", password };
    } else {
        credentialsArgs = null;
    }
    SshEnvironment sshEnvironment = null;
    if (SshEnvironment.isSSH(repoUrl)) {
        sshEnvironment = new SshEnvironment(sshScriptProvider, repoUrl);
        if (env == null) {
            env = new HashMap<>();
        }
        env.putAll(sshEnvironment.get());
    }
    try {
        result = UpstreamUtils.executeCommandLine(env, "svn", args.toArray(new String[args.size()]), credentialsArgs, -1, projectPath, svnOutputPublisherFactory);
    } catch (IOException e) {
        throw new SubversionException(e);
    } finally {
        if (sshEnvironment != null) {
            sshEnvironment.cleanUp();
        }
    }
    if (result.getExitCode() != 0) {
        buffer = new StringBuffer();
        lines.addAll(result.getStdout());
        lines.addAll(result.getStderr());
        for (final String line : lines) {
            // Subversion returns an error code of 1 even when the "error" is just a warning
            if (line.startsWith("svn: warning: ")) {
                isWarning = true;
            }
            buffer.append(line);
            buffer.append("\n");
        }
        if (!isWarning) {
            String errorMessage = buffer.toString();
            if (errorMessage.endsWith("Authentication failed\n")) {
                throw new UnauthorizedException("Authentication failed", ErrorCodes.UNAUTHORIZED_SVN_OPERATION);
            } else {
                throw new SubversionException(errorMessage);
            }
        }
    }
    return result;
}
Also used : SshEnvironment(org.eclipse.che.plugin.svn.server.utils.SshEnvironment) CommandLineResult(org.eclipse.che.plugin.svn.server.upstream.CommandLineResult) ArrayList(java.util.ArrayList) UnauthorizedException(org.eclipse.che.api.core.UnauthorizedException) IOException(java.io.IOException)

Example 9 with UnauthorizedException

use of org.eclipse.che.api.core.UnauthorizedException in project che by eclipse.

the class SshKeyProviderImpl method getPrivateKey.

/**
     * Get private ssh key and upload public ssh key to repository hosting service.
     *
     * @param url
     *         url to the repository
     * @return private ssh key
     * @throws ServerException
     *         if an error occurs while generating or uploading keys
     */
@Override
public byte[] getPrivateKey(String url) throws ServerException {
    String host = UrlUtils.getHost(url);
    SshPair pair;
    try {
        pair = sshService.getPair("vcs", host);
    } catch (ServerException | NotFoundException e) {
        throw new ServerException(DtoFactory.newDto(ExtendedError.class).withMessage("Unable get private ssh key").withErrorCode(ErrorCodes.UNABLE_GET_PRIVATE_SSH_KEY));
    }
    // check keys existence
    String privateKey = pair.getPrivateKey();
    if (privateKey == null) {
        throw new ServerException(DtoFactory.newDto(ExtendedError.class).withMessage("Unable get private ssh key").withErrorCode(ErrorCodes.UNABLE_GET_PRIVATE_SSH_KEY));
    }
    final String publicKey = pair.getPublicKey();
    if (publicKey != null) {
        final Optional<SshKeyUploader> optionalKeyUploader = sshKeyUploaders.stream().filter(keyUploader -> keyUploader.match(url)).findFirst();
        if (optionalKeyUploader.isPresent()) {
            final SshKeyUploader uploader = optionalKeyUploader.get();
            try {
                uploader.uploadKey(publicKey);
            } catch (IOException e) {
                throw new ServerException(e.getMessage(), e);
            } catch (UnauthorizedException e) {
                // action might fail without uploaded public SSH key.
                LOG.warn(String.format("Unable upload public SSH key with %s", uploader.getClass().getSimpleName()), e);
            }
        } else {
            // action might fail without uploaded public SSH key.
            LOG.warn(String.format("Not found ssh key uploader for %s", host));
        }
    }
    return privateKey.getBytes();
}
Also used : Logger(org.slf4j.Logger) ErrorCodes(org.eclipse.che.api.core.ErrorCodes) Inject(com.google.inject.Inject) LoggerFactory(org.slf4j.LoggerFactory) Set(java.util.Set) IOException(java.io.IOException) NotFoundException(org.eclipse.che.api.core.NotFoundException) UrlUtils(org.eclipse.che.plugin.ssh.key.utils.UrlUtils) SshPair(org.eclipse.che.api.ssh.shared.model.SshPair) ServerException(org.eclipse.che.api.core.ServerException) Optional(java.util.Optional) SshServiceClient(org.eclipse.che.plugin.ssh.key.SshServiceClient) ExtendedError(org.eclipse.che.api.core.rest.shared.dto.ExtendedError) UnauthorizedException(org.eclipse.che.api.core.UnauthorizedException) DtoFactory(org.eclipse.che.dto.server.DtoFactory) SshPair(org.eclipse.che.api.ssh.shared.model.SshPair) ServerException(org.eclipse.che.api.core.ServerException) ExtendedError(org.eclipse.che.api.core.rest.shared.dto.ExtendedError) UnauthorizedException(org.eclipse.che.api.core.UnauthorizedException) NotFoundException(org.eclipse.che.api.core.NotFoundException) IOException(java.io.IOException)

Example 10 with UnauthorizedException

use of org.eclipse.che.api.core.UnauthorizedException in project che by eclipse.

the class GitHubFactory method getToken.

private String getToken() throws ServerException, UnauthorizedException {
    OAuthToken token;
    try {
        token = oauthTokenProvider.getToken("github", EnvironmentContext.getCurrent().getSubject().getUserId());
    } catch (IOException e) {
        throw new ServerException(e.getMessage());
    }
    String oauthToken = token != null ? token.getToken() : null;
    if (oauthToken == null || oauthToken.isEmpty()) {
        throw new UnauthorizedException("User doesn't have access token to github");
    }
    return oauthToken;
}
Also used : OAuthToken(org.eclipse.che.api.auth.shared.dto.OAuthToken) ServerException(org.eclipse.che.api.core.ServerException) UnauthorizedException(org.eclipse.che.api.core.UnauthorizedException) IOException(java.io.IOException)

Aggregations

UnauthorizedException (org.eclipse.che.api.core.UnauthorizedException)11 IOException (java.io.IOException)10 ServerException (org.eclipse.che.api.core.ServerException)8 ArrayList (java.util.ArrayList)4 NotFoundException (org.eclipse.che.api.core.NotFoundException)4 Logger (org.slf4j.Logger)4 LoggerFactory (org.slf4j.LoggerFactory)4 Strings.isNullOrEmpty (com.google.common.base.Strings.isNullOrEmpty)3 File (java.io.File)3 HashMap (java.util.HashMap)3 BadRequestException (org.eclipse.che.api.core.BadRequestException)3 ConflictException (org.eclipse.che.api.core.ConflictException)3 ForbiddenException (org.eclipse.che.api.core.ForbiddenException)3 VisibleForTesting (com.google.common.annotations.VisibleForTesting)2 Files (com.google.common.io.Files)2 JSch (com.jcraft.jsch.JSch)2 Session (com.jcraft.jsch.Session)2 OutputStream (java.io.OutputStream)2 String.format (java.lang.String.format)2 Date (java.util.Date)2