summaryrefslogtreecommitdiff
path: root/lib/tfa/totp_command.rb
blob: 57f0cc4d9ce410819638ae9820643676d6fbbc02 (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
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