1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
use ::base64; use ::header; use ::HeaderResult; #[derive(Clone, Debug)] pub struct HttpBasic { pub user: String, pub password: String, } impl From<(String, String)> for HttpBasic { fn from((user, password): (String, String)) -> Self { Self { user, password, } } } impl ::std::fmt::Display for HttpBasic { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { let raw = format!("{}:{}", self.user, self.password); let encoded = base64::encode(raw.as_str()); f.write_str(format!("Basic {}", encoded).as_str()) } } impl header::Header for HttpBasic { fn header_name() -> &'static str { "Authorization" } fn parse_header(raw: &[Vec<u8>]) -> HeaderResult<HttpBasic> { let encoded = &raw[0]; let decoded = String::from_utf8(base64::decode(encoded).unwrap())?; let parts = decoded.split(':').collect::<Vec<_>>(); Ok(Self { user: parts[0].into(), password: parts[1].into() }) } } impl header::HeaderFormat for HttpBasic { fn fmt_header(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { <Self as ::std::fmt::Display>::fmt(self, f) } }