Skip to content

Commit

Permalink
Add option for skipping secret generation (#56)
Browse files Browse the repository at this point in the history
* Add option for skipping secret generation

* Use #nil?

* Send options to callbacks
  • Loading branch information
matheusazzi authored and robertomiranda committed Jun 18, 2019
1 parent 18107db commit 3280ecd
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 1 deletion.
2 changes: 1 addition & 1 deletion lib/active_model/one_time_password.rb
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ def has_one_time_password(options = {})

include InstanceMethodsOnActivation

before_create do
before_create(options.slice(:if, :unless)) do
self.otp_regenerate_secret if !otp_column
self.otp_regenerate_counter if otp_counter_based && !otp_counter
end
Expand Down
16 changes: 16 additions & 0 deletions test/models/opt_in_two_factor.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
# frozen_string_literal: true

class OptInTwoFactor
extend ActiveModel::Callbacks
include ActiveModel::Validations
include ActiveModel::OneTimePassword

define_model_callbacks :create
attr_accessor :otp_secret_key, :email

has_one_time_password unless: :otp_opt_in?

def otp_opt_in?
true
end
end
12 changes: 12 additions & 0 deletions test/one_time_password_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,10 @@ def setup
@ar_user = ActiverecordUser.new
@ar_user.email = '[email protected]'
@ar_user.run_callbacks :create

@opt_in = OptInTwoFactor.new
@opt_in.email = '[email protected]'
@opt_in.run_callbacks :create
end

def test_authenticate_with_otp
Expand Down Expand Up @@ -49,6 +53,14 @@ def test_counter_based_otp_active_record
assert code != @ar_user.otp_code(auto_increment: true)
end

def test_opt_in_two_factor
assert @opt_in.otp_column.nil?

@opt_in.otp_regenerate_secret
code = @opt_in.otp_code
assert @opt_in.authenticate_otp(code)
end

def test_authenticate_with_otp_when_drift_is_allowed
code = @user.otp_code(Time.now - 30)
assert @user.authenticate_otp(code, drift: 60)
Expand Down

0 comments on commit 3280ecd

Please sign in to comment.