Sha256: 1ce0d9e920c615a8d3b717a9faf6fae0f55d6cb017c3192eca813985309de868

Contents?: true

Size: 1.39 KB

Versions: 8

Compression:

Stored size: 1.39 KB

Contents

class Miam::PasswordManager
  include Miam::Logger::Helper

  LOWERCASES = ('a'..'z').to_a
  UPPERCASES = ('A'..'Z').to_a
  NUMBERS = ('0'..'9').to_a
  SYMBOLS = "!@\#$%^&*()_+-=[]{}|'".split(//)

  def initialize(output, options = {})
    @output = output
    @options = options
  end

  def identify(user, type, policy)
    password = mkpasswd(policy)
    log(:debug, "mkpasswd: #{password}")
    puts_password(user, type, password)
    password
  end

  def puts_password(user, type, password)
    log(:info, "User `#{user}` > `#{type}`: put password to `#{@output}`")

    open_output do |f|
      f.puts("#{user},#{type},#{password}")
    end
  end

  private

  def mkpasswd(policy)
    chars = []
    len = 8

    if policy
      len = policy.minimum_password_length if policy.minimum_password_length > len
      chars << LOWERCASES.shuffle.first if policy.require_lowercase_characters
      chars << UPPERCASES.shuffle.first if policy.require_uppercase_characters
      chars << NUMBERS.shuffle.first if policy.require_numbers
      chars << SYMBOLS.shuffle.first if policy.require_symbols

      len -= chars.length
    end

    (chars + [*1..9, *'A'..'Z', *'a'..'z'].shuffle.slice(0, len)).shuffle.join
  end

  def open_output
    return if @options[:dry_run]

    if @output == '-'
      yield($stdout)
      $stdout.flush
    else
      open(@output, 'a') do |f|
        yield(f)
      end
    end
  end
end

Version data entries

8 entries across 8 versions & 1 rubygems

Version Path
miam-0.2.5.beta1 lib/miam/password_manager.rb
miam-0.2.4 lib/miam/password_manager.rb
miam-0.2.4.beta18 lib/miam/password_manager.rb
miam-0.2.4.beta17 lib/miam/password_manager.rb
miam-0.2.4.beta16 lib/miam/password_manager.rb
miam-0.2.4.beta15 lib/miam/password_manager.rb
miam-0.2.4.beta14 lib/miam/password_manager.rb
miam-0.2.4.beta13 lib/miam/password_manager.rb