1pub use crate::uri::SASLMechanism;
2use crate::{
3 types::{AMQPValue, FieldTable, LongString, generation::gen_field_table},
4 uri::AMQPUserInfo,
5};
6
7#[derive(Clone, Debug, PartialEq, Eq)]
9pub struct Credentials {
10 username: LongString,
11 password: LongString,
12}
13
14impl Credentials {
15 pub fn new(username: LongString, password: LongString) -> Self {
17 Self { username, password }
18 }
19
20 pub fn username(&self) -> &LongString {
22 &self.username
23 }
24
25 pub fn password(&self) -> &LongString {
27 &self.password
28 }
29
30 pub fn sasl_auth_string(&self, mechanism: SASLMechanism) -> LongString {
32 match mechanism {
33 SASLMechanism::AMQPlain => self.amqplain_auth_string(),
34 SASLMechanism::Anonymous | SASLMechanism::External => LongString::default(),
35 SASLMechanism::Plain => format!("\0{}\0{}", self.username, self.password).into(),
36 SASLMechanism::RabbitCrDemo => self.username.clone(),
37 }
38 }
39
40 pub fn rabbit_cr_demo_challenge(&self) -> &'static str {
42 "Please tell me your password"
43 }
44
45 pub fn rabbit_cr_demo_answer(&self) -> LongString {
47 format!("My password is {}", self.password).into()
48 }
49
50 fn amqplain_auth_string(&self) -> LongString {
51 let needed_len = 4 + 15 + 5 + self.username.len() + 5 + self.password.len();
52 let mut buf = vec![0; needed_len];
53 let mut table = FieldTable::default();
54 table.insert("LOGIN".into(), AMQPValue::LongString(self.username.clone()));
55 table.insert(
56 "PASSWORD".into(),
57 AMQPValue::LongString(self.password.clone()),
58 );
59 gen_field_table(&table)((&mut buf[..]).into())
60 .expect("miscalculated AMQPLAIN string length");
61 buf.as_slice()[4..].to_vec().into()
63 }
64}
65
66impl Default for Credentials {
67 fn default() -> Self {
68 Self::new("guest".into(), "guest".into())
69 }
70}
71
72impl From<AMQPUserInfo> for Credentials {
73 fn from(user_info: AMQPUserInfo) -> Self {
74 Self {
75 username: user_info.username.into(),
76 password: user_info.password.into(),
77 }
78 }
79}
80
81#[cfg(test)]
82mod test {
83 use super::*;
84
85 #[test]
86 fn test_amqplain() {
87 assert_eq!(
88 Credentials::default().amqplain_auth_string(),
89 "\u{5}LOGINS\u{0}\u{0}\u{0}\u{5}guest\u{8}PASSWORDS\u{0}\u{0}\u{0}\u{5}guest".into()
90 );
91 }
92}