duritong / trocla

A password store for password creation and retrieval
Other
75 stars 18 forks source link

Add key options on formats and search key option ? #49

Closed fe80 closed 3 years ago

fe80 commented 6 years ago

Hi,

We have lot of key and we doesn't know all available format for a key. I think is a good idea to list all availbe format for a key.

Example code for moneta (to review ?)

# bin/trocla

def formats(options)
  key = (options.delete(:trocla_key) || '' )
  if key.empty?
    "Available formats: #{Trocla::Formats.all.join(', ')}"
  else
    res = Trocla.new(options.delete(:config_file)).available_format(
      key,
      options.merge(YAML.load(options.delete(:other_options).shift.to_s)||{})
    )   
    [ res, res.nil? ? 1 : 0 ]  # never nil review
  end 
end

if (action=ARGV.shift) && actions.include?(action)
    options[:trocla_key] = ARGV.shift
    options[:trocla_format] = ARGV.shift
    options[:other_options] = ARGV
    check_format(options[:trocla_format]) unless ['delete','formats','search'].include?(action)
    begin
      result, excode = send(action,options)
      if result
        puts result.is_a?(String) ? result : result.inspect
      end
    rescue Exception => e
      unless e.message == 'exit'
        STDERR.puts "Action failed with the following message: #{e.message}"
        STDERR.puts '(See full trace by running task with --trace)'
      end
      raise e if options[:trace]
      exit 1
    end
    exit excode.nil? ? 0 : excode
else
    STDERR.puts "Please supply one of the following actions: #{actions.join(', ')}"
    STDERR.puts "Use #{$0} --help to get a list of options for these actions"
    exit 1
end

# lib/trocla.rb
  def available_format(key, options={})
    decrypt(store.format(key)).join(', ') # Use render ?
  end

# lib/trocla/stores/moneta.rb
  def format(key)
    moneta.fetch(key, {}).keys # Never nil
  end

We have also a monkey patch for search avaible key:

# Monkey patch
class Trocla::Store
  def search(key)
    raise 'not implemented'
  end
end

class Trocla::Stores::Moneta < Trocla::Store
  def search(key)
    search_keys(key)
  end

  private
  def search_keys(key)
    _moneta = Moneta.new(store_config['adapter'], (store_config['adapter_options']||{}).merge({ :expires => false }))
    a = []
    if store_config['adapter'] == :Sequel
      keys = _moneta.adapter.backend[:trocla].select_order_map {from_base64(:k)}
    elsif store_config['adapter'] == :YAML
      keys = _moneta.adapter.backend.transaction(true) { _moneta.adapter.backend.roots }
    end
    regexp = Regexp.new("^#{key}")
    keys.each do |k|
      a << k if regexp.match(k)
    end
    a
  end
end

class Trocla
  def search_key(key)
    store.search(key)
  end
end
duritong commented 6 years ago

I woul definitely merge something like that. Can you provide a PR? Also include the monkeypatch

duritong commented 3 years ago

50 got merged