[pbs-devel] [PATCH proxmox-ldap 3/6] add helpers for constructing LDAP filters
Lukas Wagner
l.wagner at proxmox.com
Tue Jan 17 15:20:34 CET 2023
Signed-off-by: Lukas Wagner <l.wagner at proxmox.com>
---
src/lib.rs | 70 ++++++++++++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 70 insertions(+)
diff --git a/src/lib.rs b/src/lib.rs
index 48eb863..40c4f6d 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -226,3 +226,73 @@ impl LdapConnection {
bail!("user not found")
}
}
+
+#[allow(dead_code)]
+enum FilterElement {
+ And(Vec<FilterElement>),
+ Or(Vec<FilterElement>),
+ Condition(String, String),
+ Not(Box<FilterElement>),
+ Verbatim(String),
+}
+
+impl ToString for FilterElement {
+ fn to_string(&self) -> String {
+ fn children_to_string(children: &[FilterElement]) -> String {
+ children.iter().fold(String::new(), |mut acc, v| {
+ acc.push_str(&v.to_string());
+ acc
+ })
+ }
+
+ match self {
+ FilterElement::And(children) => {
+ format!("(&{})", children_to_string(children))
+ }
+ FilterElement::Or(children) => {
+ format!("(|{})", children_to_string(children))
+ }
+ FilterElement::Not(element) => {
+ format!("(!{})", element.to_string())
+ }
+ FilterElement::Condition(attr, value) => {
+ format!("({attr}={value})")
+ }
+ FilterElement::Verbatim(verbatim) => verbatim.clone(),
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::FilterElement::*;
+
+ #[test]
+ fn test_filter_elements_to_string() {
+ assert_eq!(
+ "(uid=john)",
+ Condition("uid".into(), "john".into()).to_string()
+ );
+ assert_eq!(
+ "(!(uid=john))",
+ Not(Box::new(Condition("uid".into(), "john".into()))).to_string()
+ );
+
+ assert_eq!("(foo=bar)", Verbatim("(foo=bar)".into()).to_string());
+
+ let filter_string = And(vec![
+ Condition("givenname".into(), "john".into()),
+ Condition("sn".into(), "doe".into()),
+ Or(vec![
+ Condition("email".into(), "john at foo".into()),
+ Condition("email".into(), "john at bar".into()),
+ ]),
+ ])
+ .to_string();
+
+ assert_eq!(
+ "(&(givenname=john)(sn=doe)(|(email=john at foo)(email=john at bar)))".to_owned(),
+ filter_string
+ );
+ }
+}
--
2.30.2
More information about the pbs-devel
mailing list