use crate::nonce::error::NonceError;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
pub(crate) fn current_timestamp() -> Result<i64, NonceError> {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_secs() as i64)
.map_err(|_| NonceError::CryptoError("System time is before Unix epoch".to_string()))
}
#[allow(dead_code)]
pub(crate) fn is_expired(created_at: i64, ttl_seconds: u64) -> bool {
let now = current_timestamp().unwrap_or(0);
now - created_at > ttl_seconds as i64
}
pub(crate) fn is_outside_window(timestamp: u64, current_time: i64, time_window: Duration) -> bool {
let timestamp_i64 = timestamp as i64;
let window_seconds = time_window.as_secs() as i64;
(current_time - timestamp_i64) > window_seconds
|| (timestamp_i64 - current_time) > window_seconds
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_current_timestamp() {
let ts = current_timestamp().unwrap();
assert!(ts > 1577836800); }
#[test]
fn test_is_expired() {
let now = current_timestamp().unwrap();
assert!(!is_expired(now - 10, 60));
assert!(is_expired(now - 120, 60)); }
#[test]
fn test_is_outside_window() {
let now = current_timestamp().unwrap();
let window = Duration::from_secs(60);
assert!(!is_outside_window((now - 30) as u64, now, window));
assert!(is_outside_window((now - 120) as u64, now, window));
assert!(is_outside_window((now + 120) as u64, now, window));
}
}