light-openid 2.0.6

Lightweight OpenID primitives & client
Documentation
use crate::utils::crypt_utils::sha256_str;
use std::fmt::Display;

/// A Nonce used for authentication requests
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, PartialEq, Eq)]
#[serde(tag = "t")]
pub enum Nonce {
    Hashed { id: uuid::Uuid },
    Plain { val: String },
}

impl Default for Nonce {
    fn default() -> Self {
        Self::new()
    }
}

impl Nonce {
    /// Generate a new random nonce
    pub fn new() -> Self {
        Self::Hashed {
            id: uuid::Uuid::new_v4(),
        }
    }

    /// Generate a new plain text nonce. Will be used as-is in authorization and token requests
    /// (no hashing performed)
    pub fn new_plain(d: impl Display) -> Self {
        Self::Plain { val: d.to_string() }
    }

    /// Get a hash of the nonce
    pub fn hash(&self) -> String {
        match self {
            Nonce::Hashed { id } => {
                let hash = sha256_str(id.as_bytes());
                hash[0..hash.len() / 2].to_string()
            }
            Nonce::Plain { val } => val.to_string(),
        }
    }
}

#[cfg(test)]
mod tests {
    use crate::nonce::Nonce;

    #[test]
    fn serialize_nonce() {
        let nonce = Nonce::new();
        let serialized = serde_json::to_string(&nonce).unwrap();
        let deserialized: Nonce = serde_json::from_str(&serialized).unwrap();
        assert_eq!(deserialized, nonce);
    }
}