Skip to content

Commit 2a817f3

Browse files
authored
Merge pull request #6 from tmthecoder/add-totp-time-until
Add in the `time_until_refresh` method to the TOTP struct
2 parents 44852e5 + 2707164 commit 2a817f3

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-0
lines changed

src/totp.rs

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -149,6 +149,29 @@ impl TOTP {
149149
}
150150
}
151151

152+
/// All helper methods for totp generation
153+
impl TOTP {
154+
155+
/// Returns the time in seconds until an OTP refresh is needed.
156+
///
157+
/// Just like the corresponding [`TOTP::get_otp`] method, this method
158+
/// takes the current system time in seconds.
159+
pub fn time_until_refresh(&self, time: u64) -> u64 {
160+
self.time_until_refresh_with_start(time, 0)
161+
}
162+
163+
/// Returns the time in seconds until an OTP refresh is needed.
164+
///
165+
/// Just like the corresponding [`TOTP::get_otp_with_custom_time_start`]
166+
/// method, this method takes the current time in seconds along with a
167+
/// specified start time in case an offset is desired. Both values must be
168+
/// in seconds.
169+
pub fn time_until_refresh_with_start(&self, time: u64, time_start: u64) -> u64 {
170+
let time_until = (time - time_start) % self.period;
171+
if time_until == 0 { self.period } else { time_until }
172+
}
173+
}
174+
152175
/// All otp generation methods for the [`TOTP`] struct.
153176
impl TOTP {
154177
/// Generates and returns the TOTP value for the specified time.

tests/totp.rs

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -215,3 +215,28 @@ fn rfc_test_6_sha512() {
215215
47863826
216216
)
217217
}
218+
219+
// Tests to check the time_until_refresh methods.
220+
#[test]
221+
fn test_time_until() {
222+
let totp = TOTP::default_from_base32("SecretKey");
223+
assert_eq!(totp.time_until_refresh(15), 15);
224+
}
225+
226+
#[test]
227+
fn test_time_until_at_edge() {
228+
let totp = TOTP::default_from_base32("SecretKey");
229+
assert_eq!(totp.time_until_refresh(30), 30)
230+
}
231+
232+
#[test]
233+
fn test_time_until_with_start() {
234+
let totp = TOTP::default_from_base32("SecretKey");
235+
assert_eq!(totp.time_until_refresh_with_start(30, 15), 15)
236+
}
237+
238+
#[test]
239+
fn test_time_until_with_start_at_edge() {
240+
let totp = TOTP::default_from_base32("SecretKey");
241+
assert_eq!(totp.time_until_refresh_with_start(45, 15), 30)
242+
}

0 commit comments

Comments
 (0)