Module: OTP::ActiveRecord

Extended by:
ActiveSupport::Concern
Includes:
ActiveSupport::Configurable
Defined in:
lib/otp/active_record.rb

Overview

ActiveRecord

concern.

Constant Summary collapse

OTP_DIGITS =

Length of the generated OTP, defaults to 4.

4

Instance Method Summary collapse

Instance Method Details

#deliver_otpActiveJob::Base

Helper to deliver the OTP

Will use the SMS job if the phone number is available. Will default to the email delivery.

Returns:

  • (ActiveJob::Base)

    instance of the job



66
67
68
69
# File 'lib/otp/active_record.rb', line 66

def deliver_otp
  return unless persisted?
  sms_otp || email_otp || raise(NotImplementedError, self)
end

#email_otpOTP::API::Mailer

Helper to email the OTP using a job

Does nothing. Implement your own handler.

Returns:

  • (OTP::API::Mailer)

    instance of the job



57
58
# File 'lib/otp/active_record.rb', line 57

def email_otp
end

#otpString

Generates the OTP

Returns:

  • (String)

    or nil if no OTP is set



21
22
23
24
25
26
27
28
29
30
# File 'lib/otp/active_record.rb', line 21

def otp
  return nil if !valid? || !persisted? || otp_secret.blank?
  otp_digits = self.class.const_get(:OTP_DIGITS)
  hotp = ROTP::HOTP.new(otp_secret, digits: otp_digits)

  transaction do
    increment!(:otp_counter)
    hotp.at(otp_counter)
  end
end

#sms_otpOTP::API::SMSOTPJob

Helper to send the OTP using the SMS job

Does nothing. Implement your own handler.

Returns:

  • (OTP::API::SMSOTPJob)

    instance of the job



49
50
# File 'lib/otp/active_record.rb', line 49

def sms_otp
end

#verify_otp(otp) ⇒ Object

Verifies the OTP

Returns:

  • true on success, false on failure



35
36
37
38
39
40
41
42
# File 'lib/otp/active_record.rb', line 35

def verify_otp(otp)
  hotp = ROTP::HOTP.new(otp_secret, digits: OTP_DIGITS)
  transaction do
    otp_status = hotp.verify(otp.to_s, otp_counter)
    increment!(:otp_counter)
    otp_status
  end
end