module Rubyists::Opr::Utils

Utility methods

Constants

Doofus
MAX_PASS_SIZE
SAFE_CHARS
SAMPLES

Public Class Methods

chunk_size(size) click to toggle source
# 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) click to toggle source

Decode a Base64 string

# File lib/rubyists::opr/utils.rb, line 19
def self.decode(str) # {{{
  Base64.decode64(str)
end
doofus!(message, code: 1) click to toggle source
# 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) click to toggle source

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

# 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) click to toggle source

Generate a password

# 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) click to toggle source
# 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