Skip to content

Commit

Permalink
Merge pull request #53 from go-bazzinga/9-add-login-page
Browse files Browse the repository at this point in the history
added error handling of cloudflare api
  • Loading branch information
rosarp-gobazzinga authored Feb 2, 2024
2 parents 9edd279 + 72b5614 commit afcb319
Show file tree
Hide file tree
Showing 7 changed files with 104 additions and 47 deletions.
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions cloudflare-api/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,5 +11,6 @@ serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
serde_urlencoded = "0.7"
serde_with = { version = "3.5", features = ["base64"] }
thiserror = "1.0"
tracing = "0.1"
url = "2.5"
43 changes: 33 additions & 10 deletions cloudflare-api/src/connect/client.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
use super::EndPoint;
use crate::connect::Credentials;
use reqwest::{header, Client, Error, Method, RequestBuilder};
use crate::{connect::Credentials, endpoints::CloudflareResponse, errors::CloudflareError};
use reqwest::{header, Client, Error, Method, RequestBuilder, StatusCode};
use serde::Deserialize;
use tracing::log::info;
use tracing::log::{error, info};

#[derive(Debug, Clone)]
pub struct HttpApiClient {
Expand All @@ -29,7 +29,10 @@ impl HttpApiClient {
HttpApiClient { client }
}

pub async fn send<T>(&self, end_point: impl EndPoint<T>) -> Result<T, Error>
pub async fn send<T>(
&self,
end_point: impl EndPoint<T>,
) -> Result<T, crate::errors::CloudflareError>
where
for<'de> T: Deserialize<'de>,
{
Expand All @@ -44,13 +47,33 @@ impl HttpApiClient {
if end_point.body().is_some() {
request_builder = request_builder.body(end_point.body().unwrap());
}
info!("RequestBuilder: {:?}", request_builder);
let response = request_builder.send().await?;
let txt = response.text().await?;
info!("KV Response: {}", txt);
let body: T = serde_json::from_str(&txt).unwrap();
// let body = response.json::<T>().await?;
Ok(body)
match response.status() {
StatusCode::OK => Ok(response.json::<T>().await?),
StatusCode::NOT_FOUND => {
let error_response = response
.json::<CloudflareResponse<Option<String>>>()
.await?;
Err(CloudflareError::CloudflareError(format!(
"{:?}",
error_response.errors
)))
}
_ => Err(CloudflareError::SerdeError(format!(
"Unhandled status code: {}",
response.status().as_str()
))),
}
// let txt = response.text().await?;
// info!("KV Response: {}", txt);
// let body: T = match serde_json::from_str(&txt) {
// Ok(b) => b,
// Err(error) => {
// let error = format!("{}", error);
// error!("{error}");
// return Err(CloudflareError::SerdeError(error));
// }
// };
}

fn request_builder(&self, url: &str, method: Method) -> RequestBuilder {
Expand Down
11 changes: 11 additions & 0 deletions cloudflare-api/src/errors.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
use thiserror::Error;

#[derive(Error, Debug)]
pub enum CloudflareError {
#[error("Failed to send reqwest: {0}")]
ReqwestError(#[from] reqwest::Error),
#[error("serde json failed to convert: {0}")]
SerdeError(String),
#[error("cloudflare call failed: {0}")]
CloudflareError(String),
}
1 change: 1 addition & 0 deletions cloudflare-api/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
pub mod connect;
pub mod endpoints;
pub mod errors;
61 changes: 38 additions & 23 deletions src/auth/identity.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ use leptos::*;
use leptos_axum::ResponseOptions;
use leptos_router::RouteListing;
use std::collections::HashMap;
use tracing::log::info;
use tracing::log::{error, info, warn};

#[server(endpoint = "generate_session")]
pub async fn generate_session() -> Result<agent_js::SessionResponse, ServerFnError> {
Expand All @@ -25,28 +25,43 @@ pub async fn generate_session() -> Result<agent_js::SessionResponse, ServerFnErr
None => None,
};

info!("User check: {:?}", user_identity);
// client identity
let user_key_pair: Option<generate::KeyPair> = if user_identity.is_none() {
None
} else {
let public_key = user_identity.unwrap();
let private_key = read_kv(&public_key, &app_state.cloudflare_config)
.await
.unwrap();
let private_key = general_purpose::STANDARD_NO_PAD
.decode(private_key)
.unwrap();
let metadata: HashMap<String, String> =
read_metadata(&public_key, &app_state.cloudflare_config)
.await
.unwrap();
let private_pem = metadata.get("private_pem").unwrap();
Some(generate::KeyPair {
public_key,
private_key,
private_pem: private_pem.to_owned(),
})
let user_key_pair: Option<generate::KeyPair> = match user_identity {
None => {
info!("User check: None");
None
}
Some(public_key) => {
info!("User check: {}", public_key.len());
match read_kv(&public_key, &app_state.cloudflare_config).await {
Some(private_key) => {
let private_key = match general_purpose::STANDARD_NO_PAD.decode(private_key) {
Ok(pk) => Some(pk),
Err(error) => {
error!("Could not decode pk: {}", error);
None
}
};
let metadata: Option<HashMap<String, String>> =
read_metadata(&public_key, &app_state.cloudflare_config).await;
if private_key.is_none() || metadata.is_none() {
None
} else {
let metadata = metadata.unwrap();
let private_pem = metadata.get("private_pem").unwrap();
Some(generate::KeyPair {
public_key,
private_key: private_key.unwrap(),
private_pem: private_pem.to_owned(),
})
}
}
None => {
warn!("Found in cookie, not in KV");
None
}
}
}
};
let user_key_pair = match user_key_pair {
Some(kp) => kp,
Expand Down Expand Up @@ -137,7 +152,7 @@ pub async fn generate_session() -> Result<agent_js::SessionResponse, ServerFnErr
delegation_identity: shareable_delegated_identity,
};

info!("user_pubkey: {}", user_key_pair.public_key);
info!("user_pubkey: {}", user_key_pair.public_key.len());

let mut user_cookie = Cookie::new("user_identity", user_key_pair.public_key.to_owned());
user_cookie.set_domain(app_state.auth_cookie_domain.to_owned());
Expand Down
33 changes: 19 additions & 14 deletions src/store/cloudflare.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use cloudflare_api::{
endpoints::storage_kv::{DeleteKV, ReadKV, ReadMetadata, WriteKVWithMetadata},
};
use std::collections::HashMap;
use tracing::log::{error, info};
use tracing::log::{error, info, warn};

pub async fn read_kv(key_name: &str, cloudflare_config: &ApiClientConfig) -> Option<String> {
let end_point = ReadKV {
Expand All @@ -14,7 +14,7 @@ pub async fn read_kv(key_name: &str, cloudflare_config: &ApiClientConfig) -> Opt
match cloudflare_config.cloudflare_client.send(end_point).await {
Ok(response) => Some(response),
Err(error) => {
info!("Error read_kv: {}", error);
warn!("Error read_kv: {}", error);
None
}
}
Expand All @@ -30,19 +30,18 @@ pub async fn read_metadata(
key_name,
};
match cloudflare_config.cloudflare_client.send(end_point).await {
Ok(response) => {
if response.success == true {
Some(response.result.unwrap())
} else {
info!("Error read_metadata: ");
Ok(response) => match response.success {
true => Some(response.result.unwrap()),
false => {
warn!("Error read_metadata: ");
for error in response.errors {
info!("code: {}, message: {}", error.code, error.message);
warn!("code: {}, message: {}", error.code, error.message);
}
None
}
}
},
Err(error) => {
info!("Error read_metadata: {}", error);
error!("Error read_metadata: {}", error);
None
}
}
Expand All @@ -63,10 +62,16 @@ pub async fn write_kv(
};
let result = cloudflare_config.cloudflare_client.send(end_point).await;
match result {
Ok(result) => {
info!("write kv: {:?}", result);
Some(result.success.to_string())
}
Ok(result) => match result.success {
true => {
warn!("write kv success");
Some(result.success.to_string())
}
false => {
warn!("write kv failed: {:?}", result.errors);
None
}
},
Err(error) => {
error!("write kv error: {}", error);
None
Expand Down

0 comments on commit afcb319

Please sign in to comment.