summaryrefslogtreecommitdiff
path: root/lib/tfa/totp_command.rb
blob: 14bc064961db3e303f42e9c5ef8e3edaf5b1f5a5 (plain)
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
module TFA
  class TotpCommand
    def initialize(storage)
      @storage = storage
    end

    def run(name)
      secret = secret_for(name)
      secret ? password_for(secret) : all_passwords
    end

    private

    def password_for(secret)
      ::ROTP::TOTP.new(secret).now
    rescue ROTP::Base32::Base32Error
      "INVALID SECRET"
    end

    def all_passwords
      @storage.each do |hash|
        hash[hash.keys.first] = password_for(hash[hash.keys.first])
      end
    end

    def secret_for(key)
      @storage.secret_for(key)
    end
  end
end