use super::funejson::Value; use super::auth_email_token_hash_email_token::{check_email_token_purpose, hash_email_token}; use super::encoding_base64_base64_url_encode::base64_url_encode; /// A new single-use token from the caller's random bytes. The token goes in /// the email's link only; store the rest. /// /// # Panics /// Panics on a byte outside 0-255, fewer than 16 bytes, a malformed purpose, /// an empty subject or a ttl outside 1-2592000. pub fn generate_email_token( random_bytes: &[i64], purpose: &str, subject: &str, now: i64, ttl_seconds: i64, ) -> IssuedEmailToken { if random_bytes.iter().any(|b| !(0..=255).contains(b)) { panic!("randomBytes must be a list of integers from 0 to 255"); } if random_bytes.len() < 16 { panic!("randomBytes must hold at least 16 bytes"); } check_email_token_purpose(purpose); if subject.is_empty() { panic!("subject must be a non-empty string"); } if !(1..=2_592_000).contains(&ttl_seconds) { panic!("ttlSeconds must be a whole number from 1 to 2592000"); } let token = base64_url_encode(random_bytes); let token_hash = hash_email_token(&token, purpose); IssuedEmailToken { token, token_hash, purpose: purpose.to_string(), subject: subject.to_string(), expires_at: now + ttl_seconds, } } pub fn fune_vector(args: &[Value]) -> Value { let bytes: Vec = match &args[0] { Value::Arr(items) => items .iter() .map(|item| match item { Value::Int(i) => *i, _ => panic!("randomBytes must be a list of integers from 0 to 255"), }) .collect(), _ => panic!("randomBytes must be a list of integers from 0 to 255"), }; let text = |i: usize, message: &str| -> String { match &args[i] { Value::Str(s) => s.clone(), _ => panic!("{}", message), } }; let now = match &args[3] { Value::Int(i) => *i, _ => panic!("now must be a whole number of Unix seconds"), }; let ttl = match &args[4] { Value::Int(i) => *i, _ => panic!("ttlSeconds must be a whole number from 1 to 2592000"), }; let issued = generate_email_token( &bytes, &text(1, "purpose must be 1 to 40 characters of a-z, 0-9 and -"), &text(2, "subject must be a non-empty string"), now, ttl, ); Value::obj(vec![ ("token", Value::str(&issued.token)), ("tokenHash", Value::str(&issued.token_hash)), ("purpose", Value::str(&issued.purpose)), ("subject", Value::str(&issued.subject)), ("expiresAt", Value::Int(issued.expires_at)), ]) }