Skip to content

Commit e52e8e8

Browse files
committed
simplify totp verification code
1 parent 9a48b39 commit e52e8e8

File tree

1 file changed

+7
-14
lines changed

1 file changed

+7
-14
lines changed

lib/rotp/totp.rb

+7-14
Original file line numberDiff line numberDiff line change
@@ -37,15 +37,16 @@ def now
3737
# @return [Integer, nil] the last successful timestamp
3838
# interval
3939
def verify(otp, drift_ahead: 0, drift_behind: 0, after: nil, at: Time.now)
40-
timecodes = get_timecodes(at, drift_behind, drift_ahead)
40+
now = timeint(at)
4141

42-
timecodes = timecodes.select { |t| t > timecode(after) } if after
42+
timecode_start = timecode([now - drift_behind, after].compact.max)
43+
timecode_end = timecode(now + drift_ahead)
4344

44-
result = nil
45-
timecodes.each do |t|
46-
result = t * interval if super(otp, generate_otp(t))
45+
timecode_start.upto(timecode_end) do |t|
46+
return t * interval if super(otp, generate_otp(t))
4747
end
48-
result
48+
49+
nil
4950
end
5051

5152
# Returns the provisioning URI for the OTP
@@ -59,14 +60,6 @@ def provisioning_uri(name)
5960

6061
private
6162

62-
# Get back an array of timecodes for a period
63-
def get_timecodes(at, drift_behind, drift_ahead)
64-
now = timeint(at)
65-
timecode_start = timecode(now - drift_behind)
66-
timecode_end = timecode(now + drift_ahead)
67-
(timecode_start..timecode_end).step(1).to_a
68-
end
69-
7063
# Ensure UTC int
7164
def timeint(time)
7265
return time.to_i unless time.class == Time

0 commit comments

Comments
 (0)