light-openid 2.0.5

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(uuid::Uuid),
    Plain(String),
}

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

impl Nonce {
    /// Generate a new random nonce
    pub fn new() -> Self {
        Self::Hashed(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(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(p) => p.to_string(),
        }
    }
}