writium_auth/
header.rs

1use std::fmt::Write;
2use std::fmt::{Display, Formatter, Result as FormatResult};
3use writium::hyper::header::{Header, Formatter as HyperFormatter, Raw};
4use writium::hyper::{Error as HyperError, Result as HyperResult};
5
6#[derive(Clone)]
7pub struct Challenge {
8    scheme: &'static str,
9    params: Vec<(String, String)>,
10}
11impl Challenge {
12    pub fn new(scheme: &'static str) -> Challenge {
13        Challenge {
14            scheme: scheme,
15            params: Vec::new(),
16        }
17    }
18    pub fn with_param(mut self, key: &str, val: &str) -> Challenge {
19        self.params.push((key.to_string(), val.to_string()));
20        self
21    }
22}
23impl Display for Challenge {
24    fn fmt(&self, f: &mut Formatter) -> FormatResult {
25        f.write_str(&self.scheme)?;
26        let mut it = self.params.iter();
27        if let Some(&(ref key, ref val)) = it.next() {
28            f.write_char(' ')?;
29            f.write_str(&format!("{}=\"{}\"", key, val))?;
30            for &(ref key, ref val) in it {
31                f.write_str(&format!(",{}=\"{}\"", key, val))?;
32            }
33        }
34        Ok(())
35    }
36}
37
38#[derive(Clone)]
39pub struct WwwAuthenticate {
40    challenges: Vec<Challenge>,
41}
42impl WwwAuthenticate {
43    pub fn new() -> WwwAuthenticate {
44        WwwAuthenticate {
45            challenges: Vec::new(),
46        }
47    }
48    pub fn with_challenge(mut self, challenge: Challenge) -> WwwAuthenticate {
49        self.challenges.push(challenge);
50        self
51    }
52    pub fn with_challenges(mut self, challenges: Vec<Challenge>) -> WwwAuthenticate {
53        self.challenges = challenges;
54        self
55    }
56}
57impl Header for WwwAuthenticate {
58    fn header_name() -> &'static str {
59        "WWW-Authenticate"
60    }
61    /// This header should never present in a request.
62    fn parse_header(_raw: &Raw) -> HyperResult<Self> {
63        Err(HyperError::Header)
64    }
65    #[inline]
66    fn fmt_header(&self, f: &mut HyperFormatter) -> FormatResult {
67        f.fmt_line(self)
68    }
69}
70impl Display for WwwAuthenticate {
71    fn fmt(&self, f: &mut Formatter) -> FormatResult {
72        let mut it = self.challenges.iter();
73        if let Some(ch) = it.next() {
74            ch.fmt(f)?;
75            for ch in it {
76                f.write_char(',')?;
77                ch.fmt(f)?;
78            }
79        }
80        Ok(())
81    }
82}