about summary refs log tree commit diff
path: root/src/lib.rs
diff options
context:
space:
mode:
authorVincent Ambo <mail@tazj.in>2019-02-26T15·44+0100
committerVincent Ambo <mail@tazj.in>2019-02-26T16·30+0100
commitde16d9698db4ea851464d3f3c49f51c97dcbdf03 (patch)
tree2d128ab13cafbcb275842e5101b0aa5b329b1985 /src/lib.rs
parentbd726c7d4c0b32af26d338e6c33f9fb8a7d80171 (diff)
feat: Add optional `Request::basic_auth` utility function
This function adds a dependency on `base64` and is thus gated behind
the (enabled by default) `basic_auth` feature.
Diffstat (limited to 'src/lib.rs')
-rw-r--r--src/lib.rs10
1 files changed, 10 insertions, 0 deletions
diff --git a/src/lib.rs b/src/lib.rs
index 9caedff31914..9374460d2428 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -42,6 +42,7 @@ extern crate curl;
 
 #[cfg(feature = "json")] extern crate serde;
 #[cfg(feature = "json")] extern crate serde_json;
+#[cfg(feature = "basic_auth")] extern crate base64;
 
 use curl::easy::{Easy, Form, List, ReadError};
 use std::collections::HashMap;
@@ -136,6 +137,15 @@ impl <'a> Request<'a> {
         Ok(self)
     }
 
+    #[cfg(feature = "basic_auth")]
+    /// Set the `Authorization` header to a basic authentication value
+    /// from the supplied username and password.
+    pub fn basic_auth(mut self, username: &str, password: &str) -> Result<Self, curl::Error> {
+        let auth = base64::encode(format!("{}:{}", username, password).as_bytes());
+        self.headers.append(&format!("Authorization: Basic {}", auth))?;
+        Ok(self)
+    }
+
     /// Add a byte-array body to a request using the specified
     /// `Content-Type`.
     pub fn body(mut self, content_type: &'a str, data: &'a [u8]) -> Self {