File: arguments.rb

package info (click to toggle)
ruby-rotp 6.2.0-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 388 kB
  • sloc: ruby: 960; javascript: 325; makefile: 16
file content (90 lines) | stat: -rw-r--r-- 2,362 bytes parent folder | download
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
79
80
81
82
83
84
85
86
87
88
89
90
require 'optparse'
require 'ostruct'

module ROTP
  class Arguments
    def initialize(filename, arguments)
      @filename = filename
      @arguments = Array(arguments)
    end

    def options
      parse
      options!
    end

    def to_s
      parser.help + "\n"
    end

    private

    attr_reader :arguments, :filename

    def options!
      @options ||= default_options
    end

    def default_options
      OpenStruct.new time: true, counter: 0, mode: :time
    end

    def parse
      return options!.mode = :help if arguments.empty?

      parser.parse arguments
    rescue OptionParser::InvalidOption => exception
      options!.mode = :help
      options!.warnings = red(exception.message + '. Try --help for help.')
    end

    def parser
      OptionParser.new do |parser|
        parser.banner = ''
        parser.separator green('  Usage: ') + bold("#{filename} [options]")
        parser.separator ''
        parser.separator green '  Examples:   '
        parser.separator '    ' + bold("#{filename} --secret p4ssword") + '                       # Generates a time-based one-time password'
        parser.separator '    ' + bold("#{filename} --hmac --secret p4ssword --counter 42") + '   # Generates a counter-based one-time password'
        parser.separator ''
        parser.separator green '  Options:'

        parser.on('-s', '--secret [SECRET]', 'The shared secret') do |secret|
          options!.secret = secret
        end

        parser.on('-c', '--counter [COUNTER]', 'The counter for counter-based hmac OTP') do |counter|
          options!.counter = counter.to_i
        end

        parser.on('-t', '--time', 'Use time-based OTP according to RFC 6238 (default)') do
          options!.mode = :time
        end

        parser.on('-m', '--hmac', 'Use counter-based OTP according to RFC 4226') do
          options!.mode = :hmac
        end

        parser.on_tail('-h', '--help', 'Show this message') do
          options!.mode = :help
        end

        parser.on('-d', '--digest [ALGORITHM]', 'Use algorithm for the digest (default sha1)') do |digest|
          options!.digest = digest
        end
      end
    end

    def bold(string)
      "\033[1m#{string}\033[22m"
    end

    def green(string)
      "\033[32m#{string}\033[0m"
    end

    def red(string)
      "\033[31m#{string}\033[0m"
    end
  end
end