auth headers

This commit is contained in:
Martin Algesten
2018-06-11 22:44:32 +02:00
parent ea6c4b1f3b
commit 9852960bd7
4 changed files with 35 additions and 19 deletions

View File

@@ -1,7 +1,7 @@
use std::str::FromStr;
use std::sync::Mutex;
use header::Header;
use header::{Header, add_header};
use util::*;
// to get to share private fields
@@ -12,7 +12,6 @@ include!("conn.rs");
#[derive(Debug, Default, Clone)]
pub struct Agent {
pub headers: Vec<Header>,
pub auth: Option<(String, String)>,
pub pool: Arc<Mutex<Option<ConnectionPool>>>,
}
@@ -27,7 +26,6 @@ impl Agent {
pub fn build(&self) -> Self {
Agent {
headers: self.headers.clone(),
auth: self.auth.clone(),
pool: Arc::new(Mutex::new(Some(ConnectionPool::new()))),
}
}
@@ -134,7 +132,9 @@ impl Agent {
S: Into<String>,
T: Into<String>,
{
self.auth = Some((kind.into(), pass.into()));
let s = format!("Authorization: {} {}", kind.into(), pass.into());
let header = s.parse::<Header>().expect("Failed to parse header");
add_header(header, &mut self.headers);
self
}
@@ -212,12 +212,6 @@ impl Agent {
}
}
fn add_agent_header(agent: &mut Agent, k: String, v: String) {
if let Ok(h) = Header::from_str(&format!("{}: {}", k, v)) {
agent.headers.push(h);
}
}
#[cfg(test)]
mod tests {
use super::*;

View File

@@ -16,7 +16,6 @@ pub struct Request {
// from request itself
headers: Vec<Header>,
auth: Option<(String, String)>,
query: QString,
timeout: u32,
timeout_read: u32,
@@ -62,7 +61,6 @@ impl Request {
method,
path,
headers: agent.headers.clone(),
auth: agent.auth.clone(),
redirects: 5,
..Default::default()
}
@@ -454,7 +452,9 @@ impl Request {
S: Into<String>,
T: Into<String>,
{
self.auth = Some((kind.into(), pass.into()));
let s = format!("Authorization: {} {}", kind.into(), pass.into());
let header = s.parse::<Header>().expect("Failed to parse header");
add_header(header, &mut self.headers);
self
}
@@ -505,9 +505,3 @@ impl Request {
.map_err(|e| Error::BadUrl(format!("{}", e)))
}
}
fn add_request_header(request: &mut Request, k: String, v: String) {
if let Ok(h) = Header::from_str(&format!("{}: {}", k, v)) {
request.headers.push(h)
}
}

27
src/test/auth.rs Normal file
View File

@@ -0,0 +1,27 @@
use test;
use super::super::*;
#[test]
fn basic_auth() {
test::set_handler("/basic_auth", |req, _url| {
assert_eq!(req.get("Authorization").unwrap(), "Basic bWFydGluOnJ1YmJlcm1hc2hndW0=");
test::make_stream(200, "OK", vec![], vec![])
});
let resp = get("test://host/basic_auth")
.auth("martin", "rubbermashgum")
.call();
assert_eq!(*resp.status(), 200);
}
#[test]
fn kind_auth() {
test::set_handler("/kind_auth", |req, _url| {
assert_eq!(req.get("Authorization").unwrap(), "Digest abcdefgh123");
test::make_stream(200, "OK", vec![], vec![])
});
let resp = get("test://host/kind_auth")
.auth_kind("Digest", "abcdefgh123")
.call();
assert_eq!(*resp.status(), 200);
}

View File

@@ -8,6 +8,7 @@ use stream::Stream;
use url::Url;
use util::vecread::VecRead;
mod auth;
mod simple;
mod body_read;