Implement Chainable directly for BasicAuthCredentials

This commit is contained in:
Thomas Zahner 2024-03-13 08:35:19 +01:00
parent 8da4592e2a
commit db1dc19c0a
3 changed files with 20 additions and 26 deletions

View file

@ -1,7 +1,5 @@
use crate::{BasicAuthCredentials, Response};
use crate::Response;
use core::fmt::Debug;
use headers::authorization::Credentials;
use http::header::AUTHORIZATION;
use reqwest::Request;
#[derive(Debug, PartialEq)]
@ -43,27 +41,6 @@ pub(crate) trait Chainable<T, R>: Debug {
fn handle(&mut self, input: T) -> ChainResult<T, R>;
}
#[derive(Debug)]
pub(crate) struct BasicAuth {
credentials: BasicAuthCredentials,
}
impl BasicAuth {
pub(crate) fn new(credentials: BasicAuthCredentials) -> Self {
Self { credentials }
}
}
impl Chainable<Request, Response> for BasicAuth {
fn handle(&mut self, mut request: Request) -> ChainResult<Request, Response> {
request.headers_mut().append(
AUTHORIZATION,
self.credentials.to_authorization().0.encode(),
);
ChainResult::Chained(request)
}
}
mod test {
use super::{ChainResult, ChainResult::*, Chainable};

View file

@ -31,7 +31,7 @@ use typed_builder::TypedBuilder;
use crate::{
chain::ChainResult::*,
chain::{BasicAuth, Chain, RequestChain},
chain::{Chain, RequestChain},
filter::{Excludes, Filter, Includes},
quirks::Quirks,
remap::Remaps,
@ -482,7 +482,7 @@ impl Client {
let mut request_chain: RequestChain = Chain::new(vec![Box::new(quirks)]);
if let Some(c) = credentials {
request_chain.push(Box::new(BasicAuth::new(c.clone())));
request_chain.push(Box::new(c.clone()));
}
let status = match uri.scheme() {

View file

@ -1,9 +1,17 @@
use std::str::FromStr;
use headers::authorization::Credentials;
use headers::{authorization::Basic, Authorization};
use http::header::AUTHORIZATION;
use reqwest::Request;
use serde::Deserialize;
use thiserror::Error;
use crate::{
chain::{ChainResult, Chainable},
Response,
};
#[derive(Copy, Clone, Debug, Error, PartialEq)]
pub enum BasicAuthCredentialsParseError {
#[error("Invalid basic auth credentials syntax")]
@ -66,3 +74,12 @@ impl BasicAuthCredentials {
Authorization::basic(&self.username, &self.password)
}
}
impl Chainable<Request, Response> for BasicAuthCredentials {
fn handle(&mut self, mut request: Request) -> ChainResult<Request, Response> {
request
.headers_mut()
.append(AUTHORIZATION, self.to_authorization().0.encode());
ChainResult::Chained(request)
}
}