Skip to main content

light_openid/
nonce.rs

1use crate::utils::crypt_utils::sha256_str;
2use std::fmt::Display;
3
4/// A Nonce used for authentication requests
5#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, PartialEq, Eq)]
6#[serde(tag = "t")]
7pub enum Nonce {
8    Hashed(uuid::Uuid),
9    Plain(String),
10}
11
12impl Default for Nonce {
13    fn default() -> Self {
14        Self::new()
15    }
16}
17
18impl Nonce {
19    /// Generate a new random nonce
20    pub fn new() -> Self {
21        Self::Hashed(uuid::Uuid::new_v4())
22    }
23
24    /// Generate a new plain text nonce. Will be used as-is in authorization and token requests
25    /// (no hashing performed)
26    pub fn new_plain(d: impl Display) -> Self {
27        Self::Plain(d.to_string())
28    }
29
30    /// Get a hash of the nonce
31    pub fn hash(&self) -> String {
32        match self {
33            Nonce::Hashed(id) => {
34                let hash = sha256_str(id.as_bytes());
35                hash[0..hash.len() / 2].to_string()
36            }
37            Nonce::Plain(p) => p.to_string(),
38        }
39    }
40}