1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
|
module ROTP
class OTP
# https://github.com/google/google-authenticator/wiki/Key-Uri-Format
class URI
def initialize(otp, account_name: nil, counter: nil)
@otp = otp
@account_name = account_name || ''
@counter = counter
end
def to_s
"otpauth://#{type}/#{label}?#{parameters}"
end
private
def algorithm
return unless %w[sha256 sha512].include?(@otp.digest)
@otp.digest.upcase
end
def counter
return if @otp.is_a?(TOTP)
fail if @counter.nil?
@counter
end
def digits
return if @otp.digits == DEFAULT_DIGITS
@otp.digits
end
def issuer
@otp.issuer&.strip&.tr(':', '_')
end
def label
[issuer, @account_name.rstrip]
.compact
.map { |s| s.tr(':', '_') }
.map { |s| ERB::Util.url_encode(s) }
.join(':')
end
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
def period
return if @otp.is_a?(HOTP)
return if @otp.interval == DEFAULT_INTERVAL
@otp.interval
end
def type
case @otp
when TOTP then 'totp'
when HOTP then 'hotp'
end
end
end
end
end
|