Search in sources :

Example 1 with HostUrlProvider

use of ch.cyberduck.core.HostUrlProvider in project cyberduck by iterate-ch.

the class BrickPairingSchedulerFeature method operate.

/**
 * Pool for pairing key from service
 *
 * @param callback Callback when service returns 200
 */
private void operate(final PasswordCallback callback) throws BackgroundException {
    try {
        final HttpPost resource = new HttpPost(String.format("%s/api/rest/v1/sessions/pairing_key/%s", new HostUrlProvider().withUsername(false).withPath(false).get(session.getHost()), token));
        resource.setHeader(HttpHeaders.ACCEPT, "application/json");
        resource.setHeader(HttpHeaders.CONTENT_TYPE, "application/json");
        if (log.isInfoEnabled()) {
            log.info(String.format("Fetch credentials for paring key %s from %s", token, resource));
        }
        final JsonObject json = session.getClient().execute(resource, new AbstractResponseHandler<JsonObject>() {

            @Override
            public JsonObject handleEntity(final HttpEntity entity) throws IOException {
                final ByteArrayOutputStream out = new ByteArrayOutputStream();
                IOUtils.copy(entity.getContent(), out);
                return JsonParser.parseReader(new InputStreamReader(new ByteArrayInputStream(out.toByteArray()))).getAsJsonObject();
            }
        });
        if (json.has("nickname")) {
            if (new HostPreferences(session.getHost()).getBoolean("brick.pairing.nickname.configure")) {
                final JsonPrimitive nickname = json.getAsJsonPrimitive("nickname");
                if (StringUtils.isNotBlank(host.getNickname())) {
                    if (!StringUtils.equals(host.getNickname(), nickname.getAsString())) {
                        log.warn(String.format("Mismatch of nickname. Previously authorized as %s and now paired as %s", host.getNickname(), nickname.getAsString()));
                        callback.close(null);
                        throw new LoginCanceledException();
                    }
                }
                host.setNickname(nickname.getAsString());
            }
        }
        final Credentials credentials = host.getCredentials();
        if (json.has("user_username")) {
            credentials.setUsername(json.getAsJsonPrimitive("user_username").getAsString());
        } else {
            throw new LoginFailureException(String.format("Invalid response for pairing key %s", token));
        }
        if (json.has("password")) {
            credentials.setPassword(json.getAsJsonPrimitive("password").getAsString());
        } else {
            throw new LoginFailureException(String.format("Invalid response for pairing key %s", token));
        }
        if (json.has("server")) {
            if (new HostPreferences(session.getHost()).getBoolean("brick.pairing.hostname.configure")) {
                host.setHostname(URI.create(json.getAsJsonPrimitive("server").getAsString()).getHost());
            }
        }
        callback.close(credentials.getUsername());
    } catch (JsonParseException e) {
        throw new DefaultIOExceptionMappingService().map(new IOException(e.getMessage(), e));
    } catch (HttpResponseException e) {
        switch(e.getStatusCode()) {
            case HttpStatus.SC_NOT_FOUND:
                log.warn(String.format("Missing login for pairing key %s", token));
                cancel.verify();
                break;
            default:
                throw new DefaultHttpResponseExceptionMappingService().map(e);
        }
    } catch (IOException e) {
        throw new DefaultIOExceptionMappingService().map(e);
    }
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) DefaultHttpResponseExceptionMappingService(ch.cyberduck.core.http.DefaultHttpResponseExceptionMappingService) HostUrlProvider(ch.cyberduck.core.HostUrlProvider) HttpEntity(org.apache.http.HttpEntity) InputStreamReader(java.io.InputStreamReader) JsonPrimitive(com.google.gson.JsonPrimitive) LoginCanceledException(ch.cyberduck.core.exception.LoginCanceledException) JsonObject(com.google.gson.JsonObject) HttpResponseException(org.apache.http.client.HttpResponseException) IOException(java.io.IOException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) JsonParseException(com.google.gson.JsonParseException) HostPreferences(ch.cyberduck.core.preferences.HostPreferences) LoginFailureException(ch.cyberduck.core.exception.LoginFailureException) ByteArrayInputStream(java.io.ByteArrayInputStream) DefaultIOExceptionMappingService(ch.cyberduck.core.DefaultIOExceptionMappingService) Credentials(ch.cyberduck.core.Credentials)

Example 2 with HostUrlProvider

use of ch.cyberduck.core.HostUrlProvider in project cyberduck by iterate-ch.

the class DefaultUrlProvider method toUrl.

@Override
public DescriptiveUrlBag toUrl(final Path file) {
    final DescriptiveUrlBag list = new DescriptiveUrlBag();
    if (file.attributes().getLink() != DescriptiveUrl.EMPTY) {
        list.add(file.attributes().getLink());
    }
    list.add(new DescriptiveUrl(URI.create(String.format("%s%s", new HostUrlProvider().withUsername(false).get(host), URIEncoder.encode(file.getAbsolute()))), DescriptiveUrl.Type.provider, MessageFormat.format(LocaleFactory.localizedString("{0} URL"), host.getProtocol().getScheme().toString().toUpperCase(Locale.ROOT))));
    list.addAll(new HostWebUrlProvider(host).toUrl(file));
    return list;
}
Also used : HostWebUrlProvider(ch.cyberduck.core.HostWebUrlProvider) DescriptiveUrl(ch.cyberduck.core.DescriptiveUrl) HostUrlProvider(ch.cyberduck.core.HostUrlProvider) DescriptiveUrlBag(ch.cyberduck.core.DescriptiveUrlBag)

Example 3 with HostUrlProvider

use of ch.cyberduck.core.HostUrlProvider in project cyberduck by iterate-ch.

the class NextcloudUrlProvider method toUrl.

@Override
public DescriptiveUrlBag toUrl(final Path file) {
    final DescriptiveUrlBag list = new DescriptiveUrlBag();
    list.add(new DescriptiveUrl(URI.create(String.format("%s%s", new HostUrlProvider().withUsername(false).get(session.getHost()), URIEncoder.encode(file.getAbsolute()))), DescriptiveUrl.Type.provider, MessageFormat.format(LocaleFactory.localizedString("{0} URL"), session.getHost().getProtocol().getScheme().toString().toUpperCase(Locale.ROOT))));
    return list;
}
Also used : DescriptiveUrl(ch.cyberduck.core.DescriptiveUrl) HostUrlProvider(ch.cyberduck.core.HostUrlProvider) DescriptiveUrlBag(ch.cyberduck.core.DescriptiveUrlBag)

Example 4 with HostUrlProvider

use of ch.cyberduck.core.HostUrlProvider in project cyberduck by iterate-ch.

the class StoregateSession method connect.

@Override
protected StoregateApiClient connect(final Proxy proxy, final HostKeyCallback key, final LoginCallback prompt, final CancelCallback cancel) {
    final HttpClientBuilder configuration = builder.build(proxy, this, prompt);
    final PreferencesReader preferences = new HostPreferences(host);
    authorizationService = new OAuth2RequestInterceptor(builder.build(proxy, this, prompt).addInterceptorLast(new HttpRequestInterceptor() {

        @Override
        public void process(final HttpRequest request, final HttpContext context) {
            request.addHeader(HttpHeaders.AUTHORIZATION, String.format("Basic %s", Base64.encodeToString(String.format("%s:%s", host.getProtocol().getOAuthClientId(), host.getProtocol().getOAuthClientSecret()).getBytes(StandardCharsets.UTF_8), false)));
        }
    }).build(), host).withRedirectUri(CYBERDUCK_REDIRECT_URI.equals(host.getProtocol().getOAuthRedirectUrl()) ? host.getProtocol().getOAuthRedirectUrl() : Scheme.isURL(host.getProtocol().getOAuthRedirectUrl()) ? host.getProtocol().getOAuthRedirectUrl() : new HostUrlProvider().withUsername(false).withPath(true).get(host.getProtocol().getScheme(), host.getPort(), null, host.getHostname(), host.getProtocol().getOAuthRedirectUrl())).withParameter("login_hint", preferences.getProperty("storegate.login.hint"));
    // Force login even if browser session already exists
    authorizationService.withParameter("prompt", "login");
    configuration.setServiceUnavailableRetryStrategy(new OAuth2ErrorResponseInterceptor(host, authorizationService, prompt));
    configuration.addInterceptorLast(authorizationService);
    final CloseableHttpClient apache = configuration.build();
    final StoregateApiClient client = new StoregateApiClient(apache);
    client.setBasePath(new HostUrlProvider().withUsername(false).withPath(true).get(host.getProtocol().getScheme(), host.getPort(), null, host.getHostname(), host.getProtocol().getContext()));
    client.setHttpClient(ClientBuilder.newClient(new ClientConfig().register(new InputStreamProvider()).register(MultiPartFeature.class).register(new JSON()).register(JacksonFeature.class).connectorProvider(new HttpComponentsProvider(apache))));
    final int timeout = preferences.getInteger("connection.timeout.seconds") * 1000;
    client.setConnectTimeout(timeout);
    client.setReadTimeout(timeout);
    client.setUserAgent(new PreferencesUseragentProvider().get());
    return client;
}
Also used : HttpRequest(org.apache.http.HttpRequest) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) HostUrlProvider(ch.cyberduck.core.HostUrlProvider) InputStreamProvider(org.glassfish.jersey.message.internal.InputStreamProvider) HttpContext(org.apache.http.protocol.HttpContext) OAuth2ErrorResponseInterceptor(ch.cyberduck.core.oauth.OAuth2ErrorResponseInterceptor) JSON(ch.cyberduck.core.storegate.io.swagger.client.JSON) PreferencesUseragentProvider(ch.cyberduck.core.PreferencesUseragentProvider) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) PreferencesReader(ch.cyberduck.core.preferences.PreferencesReader) HostPreferences(ch.cyberduck.core.preferences.HostPreferences) JacksonFeature(org.glassfish.jersey.jackson.JacksonFeature) OAuth2RequestInterceptor(ch.cyberduck.core.oauth.OAuth2RequestInterceptor) MultiPartFeature(org.glassfish.jersey.media.multipart.MultiPartFeature) HttpRequestInterceptor(org.apache.http.HttpRequestInterceptor) ClientConfig(org.glassfish.jersey.client.ClientConfig) HttpComponentsProvider(ch.cyberduck.core.jersey.HttpComponentsProvider)

Example 5 with HostUrlProvider

use of ch.cyberduck.core.HostUrlProvider in project cyberduck by iterate-ch.

the class StoregateSession method login.

@Override
public void login(final Proxy proxy, final LoginCallback controller, final CancelCallback cancel) throws BackgroundException {
    authorizationService.setTokens(authorizationService.authorize(host, controller, cancel, OAuth2AuthorizationService.FlowType.AuthorizationCode));
    try {
        final HttpRequestBase request = new HttpPost(new HostUrlProvider().withUsername(false).withPath(true).get(host.getProtocol().getScheme(), host.getPort(), null, host.getHostname(), "/identity/core/connect/userinfo"));
        request.addHeader(HttpHeaders.CONTENT_TYPE, MEDIA_TYPE);
        final CloseableHttpResponse response = client.getClient().execute(request);
        try {
            switch(response.getStatusLine().getStatusCode()) {
                case HttpStatus.SC_OK:
                    try {
                        final JsonElement element = JsonParser.parseReader(new InputStreamReader(response.getEntity().getContent()));
                        if (element.isJsonObject()) {
                            final JsonObject json = element.getAsJsonObject();
                            final URI url = URI.create(json.getAsJsonPrimitive("web_url_api").getAsString());
                            if (log.isInfoEnabled()) {
                                log.info(String.format("Set base path to %s", url));
                            }
                            client.setBasePath(StringUtils.removeEnd(url.toString(), String.valueOf(Path.DELIMITER)));
                        }
                    } catch (JsonParseException | IllegalArgumentException e) {
                        log.warn(String.format("Ignore failure %s", e));
                    }
                    break;
                case HttpStatus.SC_FORBIDDEN:
                    // Insufficient scope
                    final BackgroundException failure = new StoregateExceptionMappingService(fileid).map(new ApiException(response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase(), Collections.emptyMap(), EntityUtils.toString(response.getEntity())));
                    throw new LoginFailureException(failure.getDetail(), failure);
                default:
                    throw new StoregateExceptionMappingService(fileid).map(new ApiException(response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase(), Collections.emptyMap(), EntityUtils.toString(response.getEntity())));
            }
        } finally {
            EntityUtils.consume(response.getEntity());
        }
        final Credentials credentials = host.getCredentials();
        // Get username
        final ExtendedUser me = new UsersApi(client).usersGetMe();
        if (log.isDebugEnabled()) {
            log.debug(String.format("Authenticated for user %s", me));
        }
        credentials.setUsername(me.getUsername());
        credentials.setSaved(true);
        // Get root folders
        roots = new SettingsApi(client).settingsGetRootfolders();
    } catch (ApiException e) {
        throw new StoregateExceptionMappingService(fileid).map(e);
    } catch (IOException e) {
        throw new DefaultIOExceptionMappingService().map(e);
    }
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) HttpRequestBase(org.apache.http.client.methods.HttpRequestBase) HostUrlProvider(ch.cyberduck.core.HostUrlProvider) InputStreamReader(java.io.InputStreamReader) JsonObject(com.google.gson.JsonObject) ExtendedUser(ch.cyberduck.core.storegate.io.swagger.client.model.ExtendedUser) IOException(java.io.IOException) JsonParseException(com.google.gson.JsonParseException) URI(java.net.URI) CYBERDUCK_REDIRECT_URI(ch.cyberduck.core.oauth.OAuth2AuthorizationService.CYBERDUCK_REDIRECT_URI) LoginFailureException(ch.cyberduck.core.exception.LoginFailureException) JsonElement(com.google.gson.JsonElement) UsersApi(ch.cyberduck.core.storegate.io.swagger.client.api.UsersApi) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) SettingsApi(ch.cyberduck.core.storegate.io.swagger.client.api.SettingsApi) DefaultIOExceptionMappingService(ch.cyberduck.core.DefaultIOExceptionMappingService) BackgroundException(ch.cyberduck.core.exception.BackgroundException) Credentials(ch.cyberduck.core.Credentials) ApiException(ch.cyberduck.core.storegate.io.swagger.client.ApiException)

Aggregations

HostUrlProvider (ch.cyberduck.core.HostUrlProvider)17 DescriptiveUrl (ch.cyberduck.core.DescriptiveUrl)5 DescriptiveUrlBag (ch.cyberduck.core.DescriptiveUrlBag)5 HttpClientBuilder (org.apache.http.impl.client.HttpClientBuilder)5 DefaultIOExceptionMappingService (ch.cyberduck.core.DefaultIOExceptionMappingService)3 Location (ch.cyberduck.core.features.Location)3 AwsClientBuilder (com.amazonaws.client.builder.AwsClientBuilder)3 IOException (java.io.IOException)3 Credentials (ch.cyberduck.core.Credentials)2 PreferencesUseragentProvider (ch.cyberduck.core.PreferencesUseragentProvider)2 DAVClient (ch.cyberduck.core.dav.DAVClient)2 DAVRedirectStrategy (ch.cyberduck.core.dav.DAVRedirectStrategy)2 BackgroundException (ch.cyberduck.core.exception.BackgroundException)2 LoginCanceledException (ch.cyberduck.core.exception.LoginCanceledException)2 LoginFailureException (ch.cyberduck.core.exception.LoginFailureException)2 DefaultHttpResponseExceptionMappingService (ch.cyberduck.core.http.DefaultHttpResponseExceptionMappingService)2 PreferencesRedirectCallback (ch.cyberduck.core.http.PreferencesRedirectCallback)2 HostPreferences (ch.cyberduck.core.preferences.HostPreferences)2 JsonObject (com.google.gson.JsonObject)2 JsonParseException (com.google.gson.JsonParseException)2