Module: Devise::Models::TwoFactorAuthenticatable

Extended by:
ActiveSupport::Concern
Includes:
DatabaseAuthenticatable
Defined in:
lib/devise_two_factor/models/two_factor_authenticatable.rb

Defined Under Namespace

Modules: ClassMethods

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.required_fields(klass) ⇒ Object



27
28
29
# File 'lib/devise_two_factor/models/two_factor_authenticatable.rb', line 27

def self.required_fields(klass)
  [:encrypted_otp_secret, :encrypted_otp_secret_iv, :encrypted_otp_secret_salt, :consumed_timestep]
end

Instance Method Details

#clean_up_passwordsObject



63
64
65
66
# File 'lib/devise_two_factor/models/two_factor_authenticatable.rb', line 63

def clean_up_passwords
  super
  self.otp_attempt = nil
end

#current_otpObject



49
50
51
# File 'lib/devise_two_factor/models/two_factor_authenticatable.rb', line 49

def current_otp
  otp.at(Time.now)
end

#current_otp_timestepObject

ROTP’s TOTP#timecode is private, so we duplicate it here



54
55
56
# File 'lib/devise_two_factor/models/two_factor_authenticatable.rb', line 54

def current_otp_timestep
   Time.now.utc.to_i / otp.interval
end

#otp(otp_secret = self.otp_secret) ⇒ Object



45
46
47
# File 'lib/devise_two_factor/models/two_factor_authenticatable.rb', line 45

def otp(otp_secret = self.otp_secret)
  ROTP::TOTP.new(otp_secret)
end

#otp_provisioning_uri(account, options = {}) ⇒ Object



58
59
60
61
# File 'lib/devise_two_factor/models/two_factor_authenticatable.rb', line 58

def otp_provisioning_uri(, options = {})
  otp_secret = options[:otp_secret] || self.otp_secret
  ROTP::TOTP.new(otp_secret, options).provisioning_uri()
end

#validate_and_consume_otp!(code, options = {}) ⇒ Object

This defaults to the model’s otp_secret If this hasn’t been generated yet, pass a secret as an option



33
34
35
36
37
38
39
40
41
42
43
# File 'lib/devise_two_factor/models/two_factor_authenticatable.rb', line 33

def validate_and_consume_otp!(code, options = {})
  otp_secret = options[:otp_secret] || self.otp_secret
  return false unless code.present? && otp_secret.present?

  totp = otp(otp_secret)
  if totp.verify(code.gsub(/\s+/, ""), drift_behind: self.class.otp_allowed_drift, drift_ahead: self.class.otp_allowed_drift)
    return consume_otp!
  end

  false
end