Skip to content

Commit

Permalink
Factor out POST requests
Browse files Browse the repository at this point in the history
  • Loading branch information
link2xt committed Aug 27, 2024
1 parent a3fcbd0 commit b3e1471
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 15 deletions.
29 changes: 29 additions & 0 deletions src/net/http.rs
Original file line number Diff line number Diff line change
Expand Up @@ -221,3 +221,32 @@ pub(crate) async fn get_client(context: &Context, load_cache: bool) -> Result<re
};
Ok(builder.build()?)
}

/// Sends an empty POST request to the URL.
///
/// Returns response text and whether request was successful or not.
pub(crate) async fn post_empty(context: &Context, url: &str) -> Result<(String, bool)> {
let parsed_url = url
.parse::<hyper::Uri>()
.with_context(|| format!("Failed to parse URL {url:?}"))?;
let scheme = parsed_url.scheme_str().context("URL has no scheme")?;
if scheme != "https" {
bail!("POST requests to non-HTTPS URLs are not allowed");
}

// As only HTTPS is used, it is safe to load DNS cache.
let load_cache = true;

let response = crate::net::http::get_client(context, load_cache)
.await?
.post(url)
.send()
.await?;
let response_status = response.status();
let response_text = response
.text()
.await
.context("Request failed: empty response")?;

Ok((response_text, response_status.is_success()))
}
18 changes: 3 additions & 15 deletions src/qr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ use crate::context::Context;
use crate::events::EventType;
use crate::key::Fingerprint;
use crate::message::Message;
use crate::net::http::post_empty;
use crate::peerstate::Peerstate;
use crate::token;
use crate::tools::validate_id;
Expand Down Expand Up @@ -645,21 +646,8 @@ async fn set_account_from_qr(context: &Context, qr: &str) -> Result<()> {
bail!("DCACCOUNT QR codes must use HTTPS scheme");
}

// As only HTTPS is used, it is safe to load DNS cache.
let load_cache = true;

let response = crate::net::http::get_client(context, load_cache)
.await?
.post(url_str)
.send()
.await?;
let response_status = response.status();
let response_text = response
.text()
.await
.context("Cannot create account, request failed: empty response")?;

if response_status.is_success() {
let (response_text, response_success) = post_empty(context, url_str).await?;
if response_success {
let CreateAccountSuccessResponse { password, email } = serde_json::from_str(&response_text)
.with_context(|| {
format!("Cannot create account, response is malformed:\n{response_text:?}")
Expand Down

0 comments on commit b3e1471

Please sign in to comment.