Skip to content

Commit abd6caf

Browse files
committed
Factor out POST requests
1 parent dadfb64 commit abd6caf

File tree

2 files changed

+32
-15
lines changed

2 files changed

+32
-15
lines changed

src/net/http.rs

+29
Original file line numberDiff line numberDiff line change
@@ -221,3 +221,32 @@ pub(crate) async fn get_client(context: &Context, load_cache: bool) -> Result<re
221221
};
222222
Ok(builder.build()?)
223223
}
224+
225+
/// Sends an empty POST request to the URL.
226+
///
227+
/// Returns response text and whether request was successful or not.
228+
pub(crate) async fn post_empty(context: &Context, url: &str) -> Result<(String, bool)> {
229+
let parsed_url = url
230+
.parse::<hyper::Uri>()
231+
.with_context(|| format!("Failed to parse URL {url:?}"))?;
232+
let scheme = parsed_url.scheme_str().context("URL has no scheme")?;
233+
if scheme != "https" {
234+
bail!("POST requests to non-HTTPS URLs are not allowed");
235+
}
236+
237+
// As only HTTPS is used, it is safe to load DNS cache.
238+
let load_cache = true;
239+
240+
let response = crate::net::http::get_client(context, load_cache)
241+
.await?
242+
.post(url)
243+
.send()
244+
.await?;
245+
let response_status = response.status();
246+
let response_text = response
247+
.text()
248+
.await
249+
.context("Request failed: empty response")?;
250+
251+
Ok((response_text, response_status.is_success()))
252+
}

src/qr.rs

+3-15
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ use crate::context::Context;
1919
use crate::events::EventType;
2020
use crate::key::Fingerprint;
2121
use crate::message::Message;
22+
use crate::net::http::post_empty;
2223
use crate::peerstate::Peerstate;
2324
use crate::token;
2425
use crate::tools::validate_id;
@@ -645,21 +646,8 @@ async fn set_account_from_qr(context: &Context, qr: &str) -> Result<()> {
645646
bail!("DCACCOUNT QR codes must use HTTPS scheme");
646647
}
647648

648-
// As only HTTPS is used, it is safe to load DNS cache.
649-
let load_cache = true;
650-
651-
let response = crate::net::http::get_client(context, load_cache)
652-
.await?
653-
.post(url_str)
654-
.send()
655-
.await?;
656-
let response_status = response.status();
657-
let response_text = response
658-
.text()
659-
.await
660-
.context("Cannot create account, request failed: empty response")?;
661-
662-
if response_status.is_success() {
649+
let (response_text, response_success) = post_empty(context, url_str).await?;
650+
if response_success {
663651
let CreateAccountSuccessResponse { password, email } = serde_json::from_str(&response_text)
664652
.with_context(|| {
665653
format!("Cannot create account, response is malformed:\n{response_text:?}")

0 commit comments

Comments
 (0)