class ROTP::OTP::URI

github.com/google/google-authenticator/wiki/Key-Uri-Format

Public Class Methods

new(otp, account_name: nil, counter: nil) click to toggle source
# File lib/rotp/otp/uri.rb, line 5
def initialize(otp, account_name: nil, counter: nil)
  @otp = otp
  @account_name = account_name || ''
  @counter = counter
end

Public Instance Methods

to_s() click to toggle source
# File lib/rotp/otp/uri.rb, line 11
def to_s
  "otpauth://#{type}/#{label}?#{parameters}"
end

Private Instance Methods

algorithm() click to toggle source
# File lib/rotp/otp/uri.rb, line 17
def algorithm
  return unless %w[sha256 sha512].include?(@otp.digest)

  @otp.digest.upcase
end
counter() click to toggle source
# File lib/rotp/otp/uri.rb, line 23
def counter
  return if @otp.is_a?(TOTP)
  fail if @counter.nil?

  @counter
end
digits() click to toggle source
# File lib/rotp/otp/uri.rb, line 30
def digits
  return if @otp.digits == DEFAULT_DIGITS

  @otp.digits
end
issuer() click to toggle source
# File lib/rotp/otp/uri.rb, line 36
def issuer
  @otp.issuer&.strip&.tr(':', '_')
end
label() click to toggle source
# File lib/rotp/otp/uri.rb, line 40
def label
  [issuer, @account_name.rstrip]
    .compact
    .map { |s| s.tr(':', '_') }
    .map { |s| ERB::Util.url_encode(s) }
    .join(':')
end
parameters() click to toggle source
# File lib/rotp/otp/uri.rb, line 48
def parameters
  {
    secret: @otp.secret,
    issuer: issuer,
    algorithm: algorithm,
    digits: digits,
    period: period,
    counter: counter,
  }
    .merge(@otp.provisioning_params)
    .reject { |_, v| v.nil? }
    .map { |k, v| "#{k}=#{ERB::Util.url_encode(v)}" }
    .join('&')
end
period() click to toggle source
# File lib/rotp/otp/uri.rb, line 63
def period
  return if @otp.is_a?(HOTP)
  return if @otp.interval == DEFAULT_INTERVAL

  @otp.interval
end
type() click to toggle source
# File lib/rotp/otp/uri.rb, line 70
def type
  case @otp
  when TOTP then 'totp'
  when HOTP then 'hotp'
  end
end