fkl_parser/mir/implementation/
authorization.rs

1use serde::Deserialize;
2use serde::Serialize;
3
4// Basic, Digest, Bearer
5#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6pub enum HttpAuthorization {
7  None,
8  Basic(String, String),
9  Digest(String, String),
10  Bearer(String),
11}
12
13impl Default for HttpAuthorization {
14  fn default() -> Self {
15    HttpAuthorization::None
16  }
17}
18
19impl HttpAuthorization {
20  pub fn from(auth_type: &str, username: Option<String>, password: Option<String>) -> Self {
21    match auth_type.to_lowercase().as_str() {
22      "basic" => {
23        if let Some(username) = username {
24          if let Some(password) = password {
25            return HttpAuthorization::Basic(username, password);
26          }
27        }
28        HttpAuthorization::None
29      }
30      "digest" => {
31        if let Some(username) = username {
32          if let Some(password) = password {
33            return HttpAuthorization::Digest(username, password);
34          }
35        }
36        HttpAuthorization::None
37      }
38      "bearer" => {
39        if let Some(token) = username {
40          return HttpAuthorization::Bearer(token);
41        }
42        HttpAuthorization::None
43      }
44      _ => HttpAuthorization::None,
45    }
46  }
47}
48
49#[cfg(test)]
50mod tests {
51  use super::*;
52
53  #[test]
54  fn test_from() {
55    assert_eq!(
56      HttpAuthorization::from("basic", Some("username".to_string()), Some("password".to_string())),
57      HttpAuthorization::Basic("username".to_string(), "password".to_string())
58    );
59    assert_eq!(
60      HttpAuthorization::from("digest", Some("username".to_string()), Some("password".to_string())),
61      HttpAuthorization::Digest("username".to_string(), "password".to_string())
62    );
63    assert_eq!(
64      HttpAuthorization::from("bearer", Some("token".to_string()), None),
65      HttpAuthorization::Bearer("token".to_string())
66    );
67    assert_eq!(
68      HttpAuthorization::from("unknown", Some("username".to_string()), Some("password".to_string())),
69      HttpAuthorization::None
70    );
71  }
72}