112 lines
2.5 KiB
Rust
112 lines
2.5 KiB
Rust
use digest_auth::AuthorizationHeader;
|
|
use digest_auth::HttpMethod;
|
|
use reqwest::Method;
|
|
use reqwest::header::HeaderMap;
|
|
use url::Position;
|
|
use url::Url;
|
|
|
|
use crate::AuthContext;
|
|
use crate::Error::AuthHeaderMissing;
|
|
use crate::Error::RequestBuilderNotCloneable;
|
|
use crate::error::Error;
|
|
use crate::error::Result;
|
|
|
|
pub(crate) const WWW_AUTHENTICATE: &str = "www-authenticate";
|
|
|
|
pub(crate) trait TryClone {
|
|
fn try_clone(&self) -> Option<Self>
|
|
where
|
|
Self: Sized;
|
|
}
|
|
|
|
pub(crate) trait Build<R> {
|
|
fn build(self) -> Result<R>;
|
|
}
|
|
|
|
pub(crate) trait WithRequest<B>
|
|
where
|
|
B: AsBytes,
|
|
{
|
|
fn url(&self) -> &Url;
|
|
fn method(&self) -> &Method;
|
|
fn body(&self) -> Option<&B>;
|
|
}
|
|
|
|
#[allow(dead_code)]
|
|
pub(crate) trait WithHeaders {
|
|
fn headers(&self) -> &HeaderMap;
|
|
}
|
|
|
|
pub(crate) trait AsBytes {
|
|
fn as_bytes(&self) -> Option<&[u8]>;
|
|
}
|
|
|
|
pub(crate) trait CloneRequestBuilder<T>
|
|
where
|
|
T: TryClone,
|
|
{
|
|
fn refresh(&self) -> Result<T>;
|
|
}
|
|
|
|
impl<T> CloneRequestBuilder<T> for T
|
|
where
|
|
T: TryClone,
|
|
{
|
|
fn refresh(&self) -> Result<T> {
|
|
self.try_clone().ok_or(RequestBuilderNotCloneable)
|
|
}
|
|
}
|
|
|
|
pub(crate) fn parse_digest_auth_header(
|
|
header: &HeaderMap,
|
|
path: &str,
|
|
method: HttpMethod,
|
|
body: Option<&[u8]>,
|
|
username: &str,
|
|
password: &str,
|
|
) -> Result<AuthorizationHeader> {
|
|
let www_auth = header.get(WWW_AUTHENTICATE).ok_or(Error::AuthHeaderMissing)?.to_str()?;
|
|
let context = AuthContext::new_with_method(username, password, path, body, method);
|
|
let mut prompt = digest_auth::parse(www_auth)?;
|
|
|
|
Ok(prompt.respond(&context)?)
|
|
}
|
|
|
|
fn calculate_answer<Bod, Req, Bui>(
|
|
request_builder: &Bui,
|
|
headers: &HeaderMap,
|
|
username: &str,
|
|
password: &str,
|
|
) -> Result<AuthorizationHeader>
|
|
where
|
|
Bod: AsBytes,
|
|
Req: WithRequest<Bod>,
|
|
Bui: Build<Req> + TryClone,
|
|
{
|
|
let request = request_builder.refresh()?.build()?;
|
|
let path = &request.url()[Position::AfterPort..];
|
|
let method = HttpMethod::from(request.method().as_str());
|
|
let body = request.body().and_then(|b| b.as_bytes());
|
|
|
|
parse_digest_auth_header(headers, path, method, body, username, password)
|
|
}
|
|
|
|
pub(crate) fn get_answer<Bod, Req, Bui>(
|
|
request_builder: &Bui,
|
|
first_response: &HeaderMap,
|
|
username: &str,
|
|
password: &str,
|
|
) -> Result<Option<AuthorizationHeader>>
|
|
where
|
|
Bod: AsBytes,
|
|
Req: WithRequest<Bod>,
|
|
Bui: Build<Req> + TryClone,
|
|
{
|
|
let answer = calculate_answer(request_builder, first_response, username, password);
|
|
match answer {
|
|
Ok(answer) => Ok(Some(answer)),
|
|
Err(AuthHeaderMissing) => Ok(None),
|
|
Err(error) => Err(error),
|
|
}
|
|
}
|