Commit d54f86592caafd4edcce38770dd748e08a35c576

wyhaya 2022-05-06T17:35:49

Support generate token from the current time

diff --git a/src/lib.rs b/src/lib.rs
index ca28739..874f409 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -55,6 +55,7 @@ use core::fmt;
 use {base64, image::Luma, qrcodegen};
 
 use hmac::Mac;
+use std::time::{SystemTime, SystemTimeError, UNIX_EPOCH};
 
 type HmacSha1 = hmac::Hmac<sha1::Sha1>;
 type HmacSha256 = hmac::Hmac<sha2::Sha256>;
@@ -169,6 +170,14 @@ impl<T: AsRef<[u8]>> TOTP<T> {
         )
     }
 
+    /// Generate a token from the current system time
+    pub fn generate_current(&self) -> Result<String, SystemTimeError> {
+        let time = SystemTime::now()
+            .duration_since(UNIX_EPOCH)?
+            .as_secs();
+        Ok(self.generate(time))
+    }
+
     /// Will check if token is valid by current time, accounting [skew](struct.TOTP.html#structfield.skew)
     pub fn check(&self, token: &str, time: u64) -> bool {
         let basestep = time / self.step - (self.skew as u64);