Class: Authentic::CLI

Inherits:
Thor
  • Object
show all
Defined in:
lib/authentic.rb

Constant Summary collapse

CLOCKS =
{
  0 => "🌕",
  7 => "🌖",
  14 => "🌗",
  21 => "🌘",
  28 => "🌑",
}

Instance Method Summary collapse

Instance Method Details

#add(name, secret_key, label = nil) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/authentic.rb', line 15

def add(name, secret_key, label = nil)
  params = {
    service:  "authentic gem",
    password: secret_key,
    account:  name,
  }
  params[:comment] = label if label

  begin
    item = Keychain.generic_passwords.create(params)
  rescue => e
    message = e.message
  end

  unless item.nil?
    say "\u2713".colorize(:green) + " Service #{name.colorize(:green)} added to keychain"
  else
    say "\u2717".colorize(:red) + " Couldn't add service #{name.colorize(:red)}..."
    say "Error: #{message}" unless message.nil?
  end
end

#delete(name) ⇒ Object



39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/authentic.rb', line 39

def delete(name)
  item = Keychain.generic_passwords.where(service: "authentic gem", account: name).first
  unless item
    return say "\u2717".colorize(:red) + " Couldn't find service #{name.colorize(:red)}..."
  end
  if options[:force] || yes?("Do you want to permanently delete #{name.colorize(:green)}?")
    item.delete
    say "\u2713".colorize(:green) + " Service #{name.colorize(:green)} deleted from keychain"
  else
    say "Leaving service #{name.colorize(:green)} in keychain"
  end
end

#generateObject



62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
# File 'lib/authentic.rb', line 62

def generate
  now  = Time.now
  keys = Keychain
          .generic_passwords
          .where(service: "authentic gem")
          .all.map do |key|
            totp = ROTP::TOTP.new(key.password.gsub(/=*$/, ''))
            OpenStruct.new(
              code:   totp.at(now),
              name:   key.attributes[:account],
              label:  key.attributes[:comment],
              remain: now.utc.to_i % totp.interval
            )
          end

  table = keys.each_with_index.map do |key, idx|
    number = (idx + 1).to_s.rjust(keys.size.to_s.size, ' ')
    [
      number.colorize(:red),
      key.code.colorize(:green),
      "#{key.name} #{(" (#{key.label})" if key.label)}",
      CLOCKS[7 * (key.remain / 7)].colorize(:blue)
    ]
  end

  print_table(table.to_a)

  unless options['skip-copy']
    if keys.size > 1
      prompt = "\nWhich key should I copy?"
      prompt += " [1-#{keys.size}, leave empty to exit]"
      response = ask prompt
      return if response.empty?
      idx = response.to_i - 1
      key = keys[idx]
    else
      key = keys.first
    end
    Clipboard.pbcopy key.code
    say "\nKey for account #{key.name.colorize(:green)} copied to clipboard"
  end
end