Skip to content

Commit 972e455

Browse files
authored
Merge pull request #156 from PrecisionNutrition/remove-spaces-from-otp-code
Strip Spaces from TOTP Code
2 parents 5cb982a + 8887bab commit 972e455

File tree

2 files changed

+10
-1
lines changed

2 files changed

+10
-1
lines changed

lib/two_factor_authentication/models/two_factor_authenticatable.rb

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ def authenticate_totp(code, options = {})
3939
drift = options[:drift] || self.class.allowed_otp_drift_seconds
4040
raise "authenticate_totp called with no otp_secret_key set" if totp_secret.nil?
4141
totp = ROTP::TOTP.new(totp_secret, digits: digits)
42-
new_timestamp = totp.verify_with_drift_and_prior(code, drift, totp_timestamp)
42+
new_timestamp = totp.verify_with_drift_and_prior(without_spaces(code), drift, totp_timestamp)
4343
return false unless new_timestamp
4444
self.totp_timestamp = new_timestamp
4545
true
@@ -103,6 +103,10 @@ def create_direct_otp(options = {})
103103

104104
private
105105

106+
def without_spaces(code)
107+
code.gsub(/\s/, '')
108+
end
109+
106110
def random_base10(digits)
107111
SecureRandom.random_number(10**digits).to_s.rjust(digits, '0')
108112
end

spec/lib/two_factor_authentication/models/two_factor_authenticatable_spec.rb

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,11 @@ def do_invoke(code, user)
8686
expect(do_invoke(code, instance)).to eq(true)
8787
end
8888

89+
it 'authenticates a code entered with a space' do
90+
code = @totp_helper.totp_code.insert(3, ' ')
91+
expect(do_invoke(code, instance)).to eq(true)
92+
end
93+
8994
it 'does not authenticate an old code' do
9095
code = @totp_helper.totp_code(1.minutes.ago.to_i)
9196
expect(do_invoke(code, instance)).to eq(false)

0 commit comments

Comments
 (0)