Module: Rubyists::Opr::Utils

Defined in:
lib/rubyists::opr/utils.rb

Overview

Utility methods

Constant Summary collapse

Doofus =

{{{

Class.new Opr::Error
MAX_PASS_SIZE =
8192
SAMPLES =
((' '..'@').to_a + ('['..'`').to_a + ('{'..'~').to_a).freeze
SAFE_CHARS =
(('a'..'z').to_a + ('A'..'Z').to_a + ('0'..'9').to_a).freeze

Class Method Summary collapse

Class Method Details

.chunk_size(size) ⇒ Object

}}}



37
38
39
40
41
42
43
44
45
46
47
# File 'lib/rubyists::opr/utils.rb', line 37

def self.chunk_size(size) # {{{
  if size > 20
    4..6
  elsif size >= 12
    3..5
  elsif size >= 8
    2..3
  else
    1..2
  end.to_a
end

.decode(str) ⇒ Object

Decode a Base64 string



19
20
21
# File 'lib/rubyists::opr/utils.rb', line 19

def self.decode(str) # {{{
  Base64.decode64(str)
end

.doofus!(message, code: 1) ⇒ Object

}}}



30
31
32
33
34
35
# File 'lib/rubyists::opr/utils.rb', line 30

def self.doofus!(message, code: 1) # {{{
  raise Doofus, message
rescue Doofus => e
  warn "Doofus Error! <<#{e}>>"
  exit code
end

.encode(obj) ⇒ Object

Encode an object for 1password POST-ing. obj must respond to #to_json



24
25
26
27
28
# File 'lib/rubyists::opr/utils.rb', line 24

def self.encode(obj) # {{{
  doofus! "#{obj} does not respond to #to_json" unless obj.respond_to? :to_json

  Base64.encode64(obj.to_json).tr("\n", '').sub(/=+$/, '')
end

.passgen(minsize, maxsize = nil, chars = SAMPLES) ⇒ Object

Generate a password



60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/rubyists::opr/utils.rb', line 60

def self.passgen(minsize, maxsize = nil, chars = SAMPLES) # {{{
  doofus! "What's the point in a #{minsize} character pass? Minimum is 6" if minsize < 6
  maxsize ||= 16
  doofus! "You're going to break something with a max size of #{maxsize} Max is #{MAX_PASS_SIZE}" if maxsize > MAX_PASS_SIZE # rubocop:disable Metrics/LineLength

  maxsize = minsize if minsize > maxsize
  size = (minsize..maxsize).to_a.sample
  chunks = chunk_size size
  rand = chars ? SecureRandom.base64(size) : SecureRandom.urlsafe_base64(size)
  arr = rand.sub(/=+$/, '').chars.each_slice(chunks.sample).map do |e|
    joined = e.join
    joined << chars.sample if chars
    joined
  end
  shuffle_and_right_size arr, size
end

.shuffle_and_right_size(arr, size) ⇒ Object

}}}



49
50
51
52
53
54
55
56
57
# File 'lib/rubyists::opr/utils.rb', line 49

def self.shuffle_and_right_size(arr, size) # {{{
  flattened = arr.flatten
  if flattened.size < size
    until flattened.size == size # rubocop:disable Style/WhileUntilModifier
      flattened << SAFE_CHARS.sample
    end
  end
  flattened.sort { |_, _| rand(10) >= 5 ? 1 : -1 }.join('')[0, size]
end