Skip to content

Commit

Permalink
Add basic auth support
Browse files Browse the repository at this point in the history
  • Loading branch information
hewigovens committed Apr 5, 2024
1 parent c4f82af commit f079464
Show file tree
Hide file tree
Showing 10 changed files with 76 additions and 23 deletions.
5 changes: 3 additions & 2 deletions Cargo.lock

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

4 changes: 2 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
[workspace]
package.version = "0.1.1"
package.version = "0.2.0"
package.edition = "2021"
package.documentation = "https://docs.rs/reqwest_enum"
package.authors = ["Tao Xu <[email protected]>"]
Expand All @@ -16,5 +16,5 @@ reqwest = { version = "^0.12.0", features = ["json"] }
serde = { version = "^1.0.0", features = ["derive"] }
serde_json = "^1.0.0"

async-trait = "^0.1.0"
futures = "^0.3.0"
tokio-test = "0.4.2"
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ Features:

```toml
[dependencies]
reqwest-enum = "0.1.0"
reqwest-enum = "0.2.0"
```

## Example
Expand All @@ -30,6 +30,7 @@ reqwest-enum = "0.1.0"
pub enum HttpBin {
Get,
Post,
Bearer,
}
```

Expand All @@ -42,6 +43,7 @@ pub trait Target {
fn path(&self) -> &'static str;
fn query(&self) -> HashMap<&'static str, &'static str>;
fn headers(&self) -> HashMap<&'static str, &'static str>;
fn authentication(&self) -> Option<AuthMethod>;
fn body(&self) -> HTTPBody;
}
```
Expand Down
2 changes: 1 addition & 1 deletion examples/ethereum-rpc/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,4 @@ reqwest = { workspace = true }
reqwest-enum = { workspace = true, features = ["jsonrpc"] }

[dev-dependencies]
tokio-test = "0.4.2"
tokio-test = { workspace = true }
10 changes: 7 additions & 3 deletions examples/ethereum-rpc/src/ethereum_rpc.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
extern crate reqwest;
extern crate reqwest_enum;
use reqwest_enum::jsonrpc::{JsonRpcRequest, JsonRpcTarget};
use reqwest_enum::jsonrpc::JsonRpcRequest;
use reqwest_enum::{
http::{HTTPBody, HTTPMethod},
target::Target,
http::{AuthMethod, HTTPBody, HTTPMethod},
target::{JsonRpcTarget, Target},
};
use serde::{Deserialize, Serialize};
use serde_json::{Number, Value};
Expand Down Expand Up @@ -158,6 +158,10 @@ impl Target for EthereumRPC {
headers
}

fn authentication(&self) -> Option<AuthMethod> {
None
}

fn body(&self) -> HTTPBody {
let method = self.method_name();
let params = self.params();
Expand Down
3 changes: 3 additions & 0 deletions reqwest-enum/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,3 +20,6 @@ reqwest = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
futures = { workspace = true, optional = true }

[dev-dependencies]
tokio-test = { workspace = true }
7 changes: 7 additions & 0 deletions reqwest-enum/src/http.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,3 +56,10 @@ impl HTTPBody {
}
}
}

pub enum AuthMethod {
// Basic(username, password)
Basic(&'static str, &'static str),
// Bearer(token)
Bearer(&'static str),
}
8 changes: 1 addition & 7 deletions reqwest-enum/src/jsonrpc.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::{http::HTTPBody, target::Target};
use crate::http::HTTPBody;
use serde::{Deserialize, Serialize};
use serde_json::Value;

Expand Down Expand Up @@ -88,12 +88,6 @@ pub enum JsonRpcResult<T> {
Error(JsonRpcErrorResponse),
}

#[cfg(feature = "jsonrpc")]
pub trait JsonRpcTarget: Target {
fn method_name(&self) -> &'static str;
fn params(&self) -> Vec<Value>;
}

#[cfg(feature = "jsonrpc")]
#[derive(Debug, Serialize, Deserialize)]
#[serde(untagged)]
Expand Down
47 changes: 41 additions & 6 deletions reqwest-enum/src/provider.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
#[cfg(feature = "jsonrpc")]
use crate::jsonrpc::{JsonRpcError, JsonRpcRequest, JsonRpcResult, JsonRpcTarget};
use crate::jsonrpc::{JsonRpcError, JsonRpcRequest, JsonRpcResult};
#[cfg(feature = "jsonrpc")]
use crate::target::JsonRpcTarget;
#[cfg(feature = "jsonrpc")]
use futures::future::join_all;

use crate::{
http::{HTTPBody, HTTPResponse},
http::{AuthMethod, HTTPBody, HTTPResponse},
target::Target,
};
use core::future::Future;
Expand Down Expand Up @@ -189,6 +191,16 @@ where
request = request.header(k, v);
}
}
if let Some(auth) = target.authentication() {
match auth {
AuthMethod::Basic(username, password) => {
request = request.basic_auth(username, Some(password));
}
AuthMethod::Bearer(token) => {
request = request.bearer_auth(token);
}
}
}
request
}
}
Expand All @@ -208,13 +220,13 @@ where
#[cfg(test)]
mod tests {
use crate::{
http::{HTTPBody, HTTPMethod},
provider::Provider,
http::{AuthMethod, HTTPBody, HTTPMethod},
provider::{JsonProviderType, Provider},
target::Target,
};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

use tokio_test::block_on;
#[derive(Serialize, Deserialize)]
struct Person {
name: String,
Expand All @@ -225,6 +237,7 @@ mod tests {
enum HttpBin {
Get,
Post,
Bearer,
}

impl Target for HttpBin {
Expand All @@ -236,13 +249,15 @@ mod tests {
match self {
HttpBin::Get => HTTPMethod::GET,
HttpBin::Post => HTTPMethod::POST,
HttpBin::Bearer => HTTPMethod::GET,
}
}

fn path(&self) -> &'static str {
match self {
HttpBin::Get => "/get",
HttpBin::Post => "/post",
HttpBin::Bearer => "/bearer",
}
}

Expand All @@ -254,9 +269,16 @@ mod tests {
HashMap::default()
}

fn authentication(&self) -> Option<AuthMethod> {
match self {
HttpBin::Bearer => Some(AuthMethod::Bearer("token")),
_ => None,
}
}

fn body(&self) -> HTTPBody {
match self {
HttpBin::Get => HTTPBody::default(),
HttpBin::Get | HttpBin::Bearer => HTTPBody::default(),
HttpBin::Post => HTTPBody::from(&Person {
name: "test".to_string(),
age: 20,
Expand All @@ -277,4 +299,17 @@ mod tests {
let provider = Provider::<HttpBin>::new(|_: &HttpBin| "http://httpbin.org".to_string());
assert_eq!(provider.request_url(&HttpBin::Post), "http://httpbin.org");
}

#[test]
fn test_authentication() {
let provider = Provider::<HttpBin>::default();
block_on(async {
let response: serde_json::Value = provider
.request_json(HttpBin::Bearer)
.await
.expect("request error");

assert!(response["authenticated"].as_bool().unwrap());
});
}
}
9 changes: 8 additions & 1 deletion reqwest-enum/src/target.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,17 @@
use crate::http::{HTTPBody, HTTPMethod};
use crate::http::{AuthMethod, HTTPBody, HTTPMethod};
use std::collections::HashMap;
pub trait Target {
fn base_url(&self) -> &'static str;
fn method(&self) -> HTTPMethod;
fn path(&self) -> &'static str;
fn query(&self) -> HashMap<&'static str, &'static str>;
fn headers(&self) -> HashMap<&'static str, &'static str>;
fn authentication(&self) -> Option<AuthMethod>;
fn body(&self) -> HTTPBody;
}

#[cfg(feature = "jsonrpc")]
pub trait JsonRpcTarget: Target {
fn method_name(&self) -> &'static str;
fn params(&self) -> Vec<serde_json::Value>;
}

0 comments on commit f079464

Please sign in to comment.