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



70
71
72
73
# File 'lib/otp/active_record.rb', line 70

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



61
62
# File 'lib/otp/active_record.rb', line 61

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
31
# 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



53
54
# File 'lib/otp/active_record.rb', line 53

def sms_otp
end

#verify_otp(otp) ⇒ Object

Verifies the OTP

Returns:

  • true on success, false on failure



36
37
38
39
40
41
42
43
44
45
46
# File 'lib/otp/active_record.rb', line 36

def verify_otp(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
    otp_status = hotp.verify(otp.to_s, otp_counter)
    increment!(:otp_counter)
    otp_status
  end
end