samael-mdext 0.1.1

samael with unreleased fixes for SAML metadata extensions and XML escaping
use crate::traits::ToXml;
use quick_xml::events::BytesText;
use quick_xml::Writer;
use serde::Deserialize;
use std::io::{self, Write};

const NAME: &str = "md:ContactPerson";

pub enum ContactType {
    Technical,
    Support,
    Administrative,
    Billing,
    Other,
}

impl ContactType {
    pub fn value(&self) -> &'static str {
        match self {
            ContactType::Technical => "technical",
            ContactType::Support => "support",
            ContactType::Administrative => "administrative",
            ContactType::Billing => "billing",
            ContactType::Other => "other",
        }
    }
}

#[derive(Clone, Debug, Default, Hash, Eq, PartialEq, Ord, PartialOrd)]
pub struct ContactPerson {
    pub contact_type: Option<String>,
    pub company: Option<String>,
    pub given_name: Option<String>,
    pub sur_name: Option<String>,
    pub email_addresses: Option<Vec<String>>,
    pub telephone_numbers: Option<Vec<String>>,
}

impl<'de> serde::Deserialize<'de> for ContactPerson {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        use serde::de::{self, MapAccess, Visitor};
        use std::fmt;

        struct ContactPersonVisitor;

        impl<'de> Visitor<'de> for ContactPersonVisitor {
            type Value = ContactPerson;

            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                formatter.write_str("ContactPerson element")
            }

            fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
            where
                A: MapAccess<'de>,
            {
                let mut contact_type = None;
                let mut company = None;
                let mut given_name = None;
                let mut sur_name = None;
                let mut email_addresses: Option<Vec<String>> = None;
                let mut telephone_numbers: Option<Vec<String>> = None;

                while let Some(key) = map.next_key::<String>()? {
                    match key.as_str() {
                        "@contactType" => {
                            if contact_type.is_none() {
                                contact_type = Some(map.next_value()?);
                            } else {
                                // Skip duplicate (e.g. from namespaced remd:contactType)
                                map.next_value::<de::IgnoredAny>()?;
                            }
                        }
                        "Company" => {
                            company = Some(map.next_value()?);
                        }
                        "GivenName" => {
                            given_name = Some(map.next_value()?);
                        }
                        "SurName" => {
                            sur_name = Some(map.next_value()?);
                        }
                        "EmailAddress" => {
                            let val: String = map.next_value()?;
                            email_addresses.get_or_insert_with(Vec::new).push(val);
                        }
                        "TelephoneNumber" => {
                            let val: String = map.next_value()?;
                            telephone_numbers.get_or_insert_with(Vec::new).push(val);
                        }
                        _ => {
                            map.next_value::<de::IgnoredAny>()?;
                        }
                    }
                }

                Ok(ContactPerson {
                    contact_type,
                    company,
                    given_name,
                    sur_name,
                    email_addresses,
                    telephone_numbers,
                })
            }
        }

        deserializer.deserialize_map(ContactPersonVisitor)
    }
}

impl ToXml for ContactPerson {
    fn write_xml<W: Write>(&self, writer: &mut Writer<W>) -> io::Result<()> {
        writer
            .create_element(NAME)
            .with_attributes(self.contact_type.as_deref().map(|v| ("contactType", v)))
            .write_inner_content(|writer| {
                if let Some(company) = &self.company {
                    writer
                        .create_element("md:Company")
                        .write_text_content(BytesText::new(company))?;
                }
                if let Some(sur_name) = &self.sur_name {
                    writer
                        .create_element("md:SurName")
                        .write_text_content(BytesText::new(sur_name))?;
                }
                if let Some(given_name) = &self.given_name {
                    writer
                        .create_element("md:GivenName")
                        .write_text_content(BytesText::new(given_name))?;
                }

                if let Some(email_addresses) = &self.email_addresses {
                    for email in email_addresses {
                        writer
                            .create_element("md:EmailAddress")
                            .write_text_content(BytesText::new(email))?;
                    }
                }

                if let Some(telephone_numbers) = &self.telephone_numbers {
                    for number in telephone_numbers {
                        writer
                            .create_element("md:TelephoneNumber")
                            .write_text_content(BytesText::new(number))?;
                    }
                }
                Ok(())
            })?;
        Ok(())
    }
}