Skip to main content

kanidmd_lib/valueset/
totp.rs

1use crate::{
2    be::dbvalue::DbTotpV1,
3    credential::totp::Totp,
4    prelude::*,
5    schema::SchemaAttribute,
6    valueset::{DbValueSetV2, ScimResolveStatus, ValueSet},
7};
8use std::collections::{btree_map::Entry as BTreeEntry, BTreeMap};
9
10#[derive(Debug, Clone)]
11pub struct ValueSetTotpSecret {
12    map: BTreeMap<String, Totp>,
13}
14
15impl ValueSetTotpSecret {
16    pub fn new(l: String, t: Totp) -> Box<Self> {
17        let mut map = BTreeMap::new();
18        map.insert(l, t);
19        Box::new(ValueSetTotpSecret { map })
20    }
21
22    pub fn push(&mut self, l: String, t: Totp) -> bool {
23        self.map.insert(l, t).is_none()
24    }
25
26    pub fn from_dbvs2(data: Vec<(String, DbTotpV1)>) -> Result<ValueSet, OperationError> {
27        let map = data
28            .into_iter()
29            .map(|(l, data)| {
30                Totp::try_from(data)
31                    .map_err(|()| OperationError::InvalidValueState)
32                    .map(|t| (l, t))
33            })
34            .collect::<Result<_, _>>()?;
35        Ok(Box::new(ValueSetTotpSecret { map }))
36    }
37
38    // We need to allow this, because rust doesn't allow us to impl FromIterator on foreign
39    // types, and tuples are always foreign.
40    #[allow(clippy::should_implement_trait)]
41    pub fn from_iter<T>(iter: T) -> Option<Box<Self>>
42    where
43        T: IntoIterator<Item = (String, Totp)>,
44    {
45        let map = iter.into_iter().collect();
46        Some(Box::new(ValueSetTotpSecret { map }))
47    }
48}
49
50impl ValueSetT for ValueSetTotpSecret {
51    fn insert_checked(&mut self, value: Value) -> Result<bool, OperationError> {
52        match value {
53            Value::TotpSecret(l, t) => {
54                if let BTreeEntry::Vacant(e) = self.map.entry(l) {
55                    e.insert(t);
56                    Ok(true)
57                } else {
58                    Ok(false)
59                }
60            }
61            _ => Err(OperationError::InvalidValueState),
62        }
63    }
64
65    fn clear(&mut self) {
66        self.map.clear();
67    }
68
69    fn remove(&mut self, pv: &PartialValue, _cid: &Cid) -> bool {
70        if let PartialValue::Utf8(l) = pv {
71            self.map.remove(l.as_str());
72        };
73        self.map.is_empty()
74    }
75
76    fn contains(&self, pv: &PartialValue) -> bool {
77        match pv {
78            PartialValue::Utf8(l) => self.map.contains_key(l.as_str()),
79            _ => false,
80        }
81    }
82
83    fn substring(&self, _pv: &PartialValue) -> bool {
84        false
85    }
86
87    fn startswith(&self, _pv: &PartialValue) -> bool {
88        false
89    }
90
91    fn endswith(&self, _pv: &PartialValue) -> bool {
92        false
93    }
94
95    fn lessthan(&self, _pv: &PartialValue) -> bool {
96        false
97    }
98
99    fn len(&self) -> usize {
100        self.map.len()
101    }
102
103    fn generate_idx_eq_keys(&self) -> Vec<String> {
104        self.map.keys().cloned().collect()
105    }
106
107    fn syntax(&self) -> SyntaxType {
108        SyntaxType::TotpSecret
109    }
110
111    fn validate(&self, _schema_attr: &SchemaAttribute) -> bool {
112        true
113    }
114
115    fn to_proto_string_clone_iter(&self) -> Box<dyn Iterator<Item = String> + '_> {
116        Box::new(self.map.keys().cloned())
117    }
118
119    fn to_scim_value(&self) -> Option<ScimResolveStatus> {
120        None
121    }
122
123    fn to_db_valueset_v2(&self) -> DbValueSetV2 {
124        DbValueSetV2::TotpSecret(
125            self.map
126                .iter()
127                .map(|(label, totp)| (label.clone(), totp.to_dbtotpv1()))
128                .collect(),
129        )
130    }
131
132    fn to_partialvalue_iter(&self) -> Box<dyn Iterator<Item = PartialValue> + '_> {
133        Box::new(self.map.keys().cloned().map(PartialValue::Utf8))
134    }
135
136    fn to_value_iter(&self) -> Box<dyn Iterator<Item = Value> + '_> {
137        Box::new(
138            self.map
139                .iter()
140                .map(|(l, t)| Value::TotpSecret(l.clone(), t.clone())),
141        )
142    }
143
144    fn equal(&self, _other: &ValueSet) -> bool {
145        // Looks like we may not need this?
146        /*
147        if let Some(other) = other.as_credential_map() {
148            &self.map == other
149        } else {
150            // debug_assert!(false);
151            false
152        }
153        */
154        debug_assert!(false);
155        false
156    }
157
158    fn merge(&mut self, _other: &ValueSet) -> Result<(), OperationError> {
159        /*
160        if let Some(b) = other.as_credential_map() {
161            mergemaps!(self.map, b)
162        } else {
163            debug_assert!(false);
164            Err(OperationError::InvalidValueState)
165        }
166        */
167
168        debug_assert!(false);
169        Err(OperationError::InvalidValueState)
170    }
171
172    fn as_totp_map(&self) -> Option<&BTreeMap<String, Totp>> {
173        Some(&self.map)
174    }
175}