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);
}
}
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;
}
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;
}
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;
}
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);
}
}
Aggregations