File tree Expand file tree Collapse file tree 2 files changed +48
-0
lines changed Expand file tree Collapse file tree 2 files changed +48
-0
lines changed Original file line number Diff line number Diff line change @@ -149,6 +149,29 @@ impl TOTP {
149
149
}
150
150
}
151
151
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
+
152
175
/// All otp generation methods for the [`TOTP`] struct.
153
176
impl TOTP {
154
177
/// Generates and returns the TOTP value for the specified time.
Original file line number Diff line number Diff line change @@ -215,3 +215,28 @@ fn rfc_test_6_sha512() {
215
215
47863826
216
216
)
217
217
}
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
+ }
You can’t perform that action at this time.
0 commit comments