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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
use serde::Deserialize;
use serde::Serialize;
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum HttpAuthorization {
None,
Basic(String, String),
Digest(String, String),
Bearer(String),
}
impl Default for HttpAuthorization {
fn default() -> Self {
HttpAuthorization::None
}
}
impl HttpAuthorization {
pub fn from(auth_type: &str, username: Option<String>, password: Option<String>) -> Self {
match auth_type.to_lowercase().as_str() {
"basic" => {
if let Some(username) = username {
if let Some(password) = password {
return HttpAuthorization::Basic(username, password);
}
}
HttpAuthorization::None
}
"digest" => {
if let Some(username) = username {
if let Some(password) = password {
return HttpAuthorization::Digest(username, password);
}
}
HttpAuthorization::None
}
"bearer" => {
if let Some(token) = username {
return HttpAuthorization::Bearer(token);
}
HttpAuthorization::None
}
_ => HttpAuthorization::None,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_from() {
assert_eq!(
HttpAuthorization::from("basic", Some("username".to_string()), Some("password".to_string())),
HttpAuthorization::Basic("username".to_string(), "password".to_string())
);
assert_eq!(
HttpAuthorization::from("digest", Some("username".to_string()), Some("password".to_string())),
HttpAuthorization::Digest("username".to_string(), "password".to_string())
);
assert_eq!(
HttpAuthorization::from("bearer", Some("token".to_string()), None),
HttpAuthorization::Bearer("token".to_string())
);
assert_eq!(
HttpAuthorization::from("unknown", Some("username".to_string()), Some("password".to_string())),
HttpAuthorization::None
);
}
}