From cf06e86e2cb9122baad7a40a4dd0972c9b6ac35e Mon Sep 17 00:00:00 2001 From: Brandon Dyer Date: Sun, 29 Oct 2023 10:04:32 -0500 Subject: [PATCH 1/2] Do what chrono does --- Cargo.toml | 3 ++- src/validation.rs | 14 +++++++++++--- 2 files changed, 13 insertions(+), 4 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 47e724f4..ffec841b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -15,11 +15,12 @@ rust-version = "1.67.0" [dependencies] serde_json = "1.0" serde = {version = "1.0", features = ["derive"] } -ring = { version = "0.17.4", features = ["std"] } +ring = { version = "0.17.4", features = ["std", "wasm32_unknown_unknown_js"] } base64 = "0.21.0" # For PEM decoding pem = {version = "3", optional = true} simple_asn1 = {version = "0.6", optional = true} +js-sys = "0.3" [dev-dependencies] # For the custom time example diff --git a/src/validation.rs b/src/validation.rs index af05d11c..3fd8c725 100644 --- a/src/validation.rs +++ b/src/validation.rs @@ -2,7 +2,6 @@ use std::borrow::Cow; use std::collections::HashSet; use std::fmt; use std::marker::PhantomData; -use std::time::{SystemTime, UNIX_EPOCH}; use serde::de::{self, Visitor}; use serde::{Deserialize, Deserializer}; @@ -137,9 +136,18 @@ impl Default for Validation { } /// Gets the current timestamp in the format expected by JWTs. +#[cfg(not(all(target_arch = "wasm32", not(any(target_os = "emscripten", target_os = "wasi")))))] +#[must_use] pub fn get_current_timestamp() -> u64 { - let start = SystemTime::now(); - start.duration_since(UNIX_EPOCH).expect("Time went backwards").as_secs() + let start = std::time::SystemTime::now(); + start.duration_since(std::time::UNIX_EPOCH).expect("Time went backwards").as_secs() +} + +/// Gets the current timestamp in the format expected by JWTs. +#[cfg(all(target_arch = "wasm32", not(any(target_os = "emscripten", target_os = "wasi"))))] +#[must_use] +pub fn get_current_timestamp() -> u64 { + js_sys::Date::new_0().get_time() as u64 / 1000 } #[derive(Deserialize)] From 185f208f3676f23ad8a57cde1eb4d2812929814e Mon Sep 17 00:00:00 2001 From: Brandon Dyer Date: Sun, 29 Oct 2023 11:26:37 -0500 Subject: [PATCH 2/2] Target specific dependencies --- Cargo.toml | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/Cargo.toml b/Cargo.toml index ffec841b..13e45a51 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -15,12 +15,18 @@ rust-version = "1.67.0" [dependencies] serde_json = "1.0" serde = {version = "1.0", features = ["derive"] } -ring = { version = "0.17.4", features = ["std", "wasm32_unknown_unknown_js"] } base64 = "0.21.0" # For PEM decoding pem = {version = "3", optional = true} simple_asn1 = {version = "0.6", optional = true} + +[target.'cfg(not(target_arch = "wasm32"))'.dependencies] +ring = { version = "0.17.4", features = ["std"] } + + +[target.'cfg(target_arch = "wasm32")'.dependencies] js-sys = "0.3" +ring = { version = "0.17.4", features = ["std", "wasm32_unknown_unknown_js"] } [dev-dependencies] # For the custom time example