1
0
Fork 0
mirror of https://github.com/nishiki/manage-password.git synced 2024-10-27 02:33:19 +00:00

indent class

This commit is contained in:
Adrien Waksberg 2017-03-30 20:04:20 +02:00
parent 0f7510b6e6
commit 01745cac2d
4 changed files with 937 additions and 937 deletions

View file

@ -27,507 +27,507 @@ require 'mpw/item'
require 'mpw/mpw'
module MPW
class Cli
# Constructor
# @args: config -> the config
def initialize(config)
@config = config
end
# Change a parameter int the config after init
# @args: options -> param to change
def set_config(options)
@config.setup(options)
puts I18n.t('form.set_config.valid').to_s.green
rescue => e
puts "#{I18n.t('display.error')} #15: #{e}".red
exit 2
end
# Create a new config file
# @args: options -> set param
def setup(options)
options[:lang] = options[:lang] || Locale::Tag.parse(ENV['LANG']).to_simple.to_s[0..1]
I18n.locale = options[:lang].to_sym
@config.setup(options)
load_config
puts I18n.t('form.setup_config.valid').to_s.green
rescue => e
puts "#{I18n.t('display.error')} #8: #{e}".red
exit 2
end
# Setup a new GPG key
# @args: gpg_key -> the key name
def setup_gpg_key(gpg_key)
return if @config.check_gpg_key?
password = ask(I18n.t('form.setup_gpg_key.password')) { |q| q.echo = false }
confirm = ask(I18n.t('form.setup_gpg_key.confirm_password')) { |q| q.echo = false }
raise I18n.t('form.setup_gpg_key.error_password') if password != confirm
@password = password.to_s
puts I18n.t('form.setup_gpg_key.wait')
@config.setup_gpg_key(@password, gpg_key)
puts I18n.t('form.setup_gpg_key.valid').to_s.green
rescue => e
puts "#{I18n.t('display.error')} #8: #{e}".red
exit 2
end
# List gpg keys in wallet
def list_keys
table_list('keys', @mpw.list_keys)
end
# Load config
def load_config
@config.load_config
rescue => e
puts "#{I18n.t('display.error')} #10: #{e}".red
exit 2
end
# Request the GPG password and decrypt the file
def decrypt
unless defined?(@mpw)
@password = ask(I18n.t('display.gpg_password')) { |q| q.echo = false }
@mpw = MPW.new(@config.gpg_key, @wallet_file, @password, @config.gpg_exe)
class Cli
# Constructor
# @args: config -> the config
def initialize(config)
@config = config
end
@mpw.read_data
rescue => e
puts "#{I18n.t('display.error')} #11: #{e}".red
exit 2
end
# Change a parameter int the config after init
# @args: options -> param to change
def set_config(options)
@config.setup(options)
# Format list on a table
def table_list(title, list)
i = 1
length = 0
list.each do |item|
length = item.length if length < item.length
end
length += 7
puts "\n#{I18n.t("display.#{title}")}".red
print ' '
length.times { print '=' }
print "\n"
list.each do |item|
print " #{i}".cyan
(3 - i.to_s.length).times { print ' ' }
puts "| #{item}"
i += 1
puts I18n.t('form.set_config.valid').to_s.green
rescue => e
puts "#{I18n.t('display.error')} #15: #{e}".red
exit 2
end
print "\n"
end
# Create a new config file
# @args: options -> set param
def setup(options)
options[:lang] = options[:lang] || Locale::Tag.parse(ENV['LANG']).to_simple.to_s[0..1]
# Format items on a table
def table_items(items = [])
group = '.'
i = 1
length_total = 10
data = { id: { length: 3, color: 'cyan' },
host: { length: 9, color: 'yellow' },
user: { length: 7, color: 'green' },
protocol: { length: 9, color: 'white' },
port: { length: 5, color: 'white' },
otp: { length: 4, color: 'white' },
comment: { length: 14, color: 'magenta' } }
I18n.locale = options[:lang].to_sym
items.each do |item|
data.each do |k, v|
next if k == :id || k == :otp
@config.setup(options)
v[:length] = item.send(k.to_s).to_s.length + 3 if item.send(k.to_s).to_s.length >= v[:length]
end
load_config
puts I18n.t('form.setup_config.valid').to_s.green
rescue => e
puts "#{I18n.t('display.error')} #8: #{e}".red
exit 2
end
data[:id][:length] = items.length.to_s.length + 2 if items.length.to_s.length > data[:id][:length]
data.each_value { |v| length_total += v[:length] }
items.sort! { |a, b| a.group.to_s.downcase <=> b.group.to_s.downcase }
# Setup a new GPG key
# @args: gpg_key -> the key name
def setup_gpg_key(gpg_key)
return if @config.check_gpg_key?
items.each do |item|
if group != item.group
group = item.group
password = ask(I18n.t('form.setup_gpg_key.password')) { |q| q.echo = false }
confirm = ask(I18n.t('form.setup_gpg_key.confirm_password')) { |q| q.echo = false }
if group.to_s.empty?
puts "\n#{I18n.t('display.no_group')}".red
else
puts "\n#{group}".red
end
raise I18n.t('form.setup_gpg_key.error_password') if password != confirm
print ' '
length_total.times { print '=' }
print "\n "
data.each do |k, v|
case k
when :id
print ' ID'
when :otp
print '| OTP'
else
print "| #{k.to_s.capitalize}"
end
@password = password.to_s
(v[:length] - k.to_s.length).times { print ' ' }
end
print "\n "
length_total.times { print '=' }
print "\n"
puts I18n.t('form.setup_gpg_key.wait')
@config.setup_gpg_key(@password, gpg_key)
puts I18n.t('form.setup_gpg_key.valid').to_s.green
rescue => e
puts "#{I18n.t('display.error')} #8: #{e}".red
exit 2
end
# List gpg keys in wallet
def list_keys
table_list('keys', @mpw.list_keys)
end
# Load config
def load_config
@config.load_config
rescue => e
puts "#{I18n.t('display.error')} #10: #{e}".red
exit 2
end
# Request the GPG password and decrypt the file
def decrypt
unless defined?(@mpw)
@password = ask(I18n.t('display.gpg_password')) { |q| q.echo = false }
@mpw = MPW.new(@config.gpg_key, @wallet_file, @password, @config.gpg_exe)
end
print " #{i}".send(data[:id][:color])
(data[:id][:length] - i.to_s.length).times { print ' ' }
data.each do |k, v|
next if k == :id
@mpw.read_data
rescue => e
puts "#{I18n.t('display.error')} #11: #{e}".red
exit 2
end
if k == :otp
print '| '
item.otp ? (print ' X ') : 4.times { print ' ' }
# Format list on a table
def table_list(title, list)
i = 1
length = 0
next
end
print '| '
print item.send(k.to_s).to_s.send(v[:color])
(v[:length] - item.send(k.to_s).to_s.length).times { print ' ' }
list.each do |item|
length = item.length if length < item.length
end
length += 7
puts "\n#{I18n.t("display.#{title}")}".red
print ' '
length.times { print '=' }
print "\n"
i += 1
list.each do |item|
print " #{i}".cyan
(3 - i.to_s.length).times { print ' ' }
puts "| #{item}"
i += 1
end
print "\n"
end
print "\n"
end
# Format items on a table
def table_items(items = [])
group = '.'
i = 1
length_total = 10
data = { id: { length: 3, color: 'cyan' },
host: { length: 9, color: 'yellow' },
user: { length: 7, color: 'green' },
protocol: { length: 9, color: 'white' },
port: { length: 5, color: 'white' },
otp: { length: 4, color: 'white' },
comment: { length: 14, color: 'magenta' } }
# Display the query's result
# @args: options -> the option to search
def list(**options)
result = @mpw.list(options)
items.each do |item|
data.each do |k, v|
next if k == :id || k == :otp
if result.empty?
puts I18n.t('display.nothing')
else
table_items(result)
end
end
v[:length] = item.send(k.to_s).to_s.length + 3 if item.send(k.to_s).to_s.length >= v[:length]
end
end
data[:id][:length] = items.length.to_s.length + 2 if items.length.to_s.length > data[:id][:length]
# Get an item when multiple choice
# @args: items -> array of items
# @rtrn: item
def get_item(items)
return items[0] if items.length == 1
data.each_value { |v| length_total += v[:length] }
items.sort! { |a, b| a.group.to_s.downcase <=> b.group.to_s.downcase }
items.sort! { |a, b| a.group.to_s.downcase <=> b.group.to_s.downcase }
choice = ask(I18n.t('form.select')).to_i
items.each do |item|
if group != item.group
group = item.group
choice >= 1 && choice <= items.length ? items[choice - 1] : nil
end
if group.to_s.empty?
puts "\n#{I18n.t('display.no_group')}".red
else
puts "\n#{group}".red
end
# Copy in clipboard the login and password
# @args: item -> the item
# clipboard -> enable clipboard
def clipboard(item, clipboard = true)
# Security: force quit after 90s
Thread.new do
sleep 90
exit
end
print ' '
length_total.times { print '=' }
print "\n "
data.each do |k, v|
case k
when :id
print ' ID'
when :otp
print '| OTP'
else
print "| #{k.to_s.capitalize}"
end
Kernel.loop do
choice = ask(I18n.t('form.clipboard.choice')).to_s
case choice
when 'q', 'quit'
break
when 'l', 'login'
if clipboard
Clipboard.copy(item.user)
puts I18n.t('form.clipboard.login').green
else
puts item.user
(v[:length] - k.to_s.length).times { print ' ' }
end
print "\n "
length_total.times { print '=' }
print "\n"
end
when 'p', 'password'
if clipboard
Clipboard.copy(@mpw.get_password(item.id))
puts I18n.t('form.clipboard.password').yellow
print " #{i}".send(data[:id][:color])
(data[:id][:length] - i.to_s.length).times { print ' ' }
data.each do |k, v|
next if k == :id
Thread.new do
sleep 30
if k == :otp
print '| '
item.otp ? (print ' X ') : 4.times { print ' ' }
Clipboard.clear
next
end
print '| '
print item.send(k.to_s).to_s.send(v[:color])
(v[:length] - item.send(k.to_s).to_s.length).times { print ' ' }
end
print "\n"
i += 1
end
print "\n"
end
# Display the query's result
# @args: options -> the option to search
def list(**options)
result = @mpw.list(options)
if result.empty?
puts I18n.t('display.nothing')
else
table_items(result)
end
end
# Get an item when multiple choice
# @args: items -> array of items
# @rtrn: item
def get_item(items)
return items[0] if items.length == 1
items.sort! { |a, b| a.group.to_s.downcase <=> b.group.to_s.downcase }
choice = ask(I18n.t('form.select')).to_i
choice >= 1 && choice <= items.length ? items[choice - 1] : nil
end
# Copy in clipboard the login and password
# @args: item -> the item
# clipboard -> enable clipboard
def clipboard(item, clipboard = true)
# Security: force quit after 90s
Thread.new do
sleep 90
exit
end
Kernel.loop do
choice = ask(I18n.t('form.clipboard.choice')).to_s
case choice
when 'q', 'quit'
break
when 'l', 'login'
if clipboard
Clipboard.copy(item.user)
puts I18n.t('form.clipboard.login').green
else
puts item.user
end
when 'p', 'password'
if clipboard
Clipboard.copy(@mpw.get_password(item.id))
puts I18n.t('form.clipboard.password').yellow
Thread.new do
sleep 30
Clipboard.clear
end
else
puts @mpw.get_password(item.id)
end
when 'o', 'otp'
if clipboard
Clipboard.copy(@mpw.get_otp_code(item.id))
else
puts @mpw.get_otp_code(item.id)
end
puts I18n.t('form.clipboard.otp', time: @mpw.get_otp_remaining_time).yellow
else
puts "----- #{I18n.t('form.clipboard.help.name')} -----".cyan
puts I18n.t('form.clipboard.help.login')
puts I18n.t('form.clipboard.help.password')
puts I18n.t('form.clipboard.help.otp_code')
puts I18n.t('form.clipboard.help.quit')
next
end
end
Clipboard.clear
rescue SystemExit, Interrupt
Clipboard.clear
end
# List all wallets
def list_wallet
wallets = []
Dir.glob("#{@config.wallet_dir}/*.mpw").each do |f|
wallet = File.basename(f, '.mpw')
wallet += ' *'.green if wallet == @config.default_wallet
wallets << wallet
end
table_list('wallets', wallets)
end
# Display the wallet
# @args: wallet -> the wallet name
def get_wallet(wallet = nil)
@wallet_file =
if wallet.to_s.empty?
wallets = Dir.glob("#{@config.wallet_dir}/*.mpw")
if wallets.length == 1
wallets[0]
elsif !@config.default_wallet.to_s.empty?
"#{@config.wallet_dir}/#{@config.default_wallet}.mpw"
else
"#{@config.wallet_dir}/default.mpw"
end
else
puts @mpw.get_password(item.id)
"#{@config.wallet_dir}/#{wallet}.mpw"
end
end
# Add a new public key
# args: key -> the key name or key file to add
def add_key(key)
@mpw.add_key(key)
@mpw.write_data
puts I18n.t('form.add_key.valid').to_s.green
rescue => e
puts "#{I18n.t('display.error')} #13: #{e}".red
end
# Add new public key
# args: key -> the key name to delete
def delete_key(key)
@mpw.delete_key(key)
@mpw.write_data
puts I18n.t('form.delete_key.valid').to_s.green
rescue => e
puts "#{I18n.t('display.error')} #15: #{e}".red
end
# Text editor interface
# @args: template -> template name
# item -> the item to edit
# password -> disable field password
def text_editor(template_name, item = nil, password = false)
editor = ENV['EDITOR'] || 'nano'
options = {}
opts = {}
template_file = "#{File.expand_path('../../../templates', __FILE__)}/#{template_name}.erb"
template = ERB.new(IO.read(template_file))
Dir.mktmpdir do |dir|
tmp_file = "#{dir}/#{template_name}.yml"
File.open(tmp_file, 'w') do |f|
f << template.result(binding)
end
when 'o', 'otp'
if clipboard
Clipboard.copy(@mpw.get_otp_code(item.id))
else
puts @mpw.get_otp_code(item.id)
end
puts I18n.t('form.clipboard.otp', time: @mpw.get_otp_remaining_time).yellow
system("#{editor} #{tmp_file}")
else
puts "----- #{I18n.t('form.clipboard.help.name')} -----".cyan
puts I18n.t('form.clipboard.help.login')
puts I18n.t('form.clipboard.help.password')
puts I18n.t('form.clipboard.help.otp_code')
puts I18n.t('form.clipboard.help.quit')
next
end
end
Clipboard.clear
rescue SystemExit, Interrupt
Clipboard.clear
end
# List all wallets
def list_wallet
wallets = []
Dir.glob("#{@config.wallet_dir}/*.mpw").each do |f|
wallet = File.basename(f, '.mpw')
wallet += ' *'.green if wallet == @config.default_wallet
wallets << wallet
end
table_list('wallets', wallets)
end
# Display the wallet
# @args: wallet -> the wallet name
def get_wallet(wallet = nil)
@wallet_file =
if wallet.to_s.empty?
wallets = Dir.glob("#{@config.wallet_dir}/*.mpw")
if wallets.length == 1
wallets[0]
elsif !@config.default_wallet.to_s.empty?
"#{@config.wallet_dir}/#{@config.default_wallet}.mpw"
else
"#{@config.wallet_dir}/default.mpw"
end
else
"#{@config.wallet_dir}/#{wallet}.mpw"
end
end
# Add a new public key
# args: key -> the key name or key file to add
def add_key(key)
@mpw.add_key(key)
@mpw.write_data
puts I18n.t('form.add_key.valid').to_s.green
rescue => e
puts "#{I18n.t('display.error')} #13: #{e}".red
end
# Add new public key
# args: key -> the key name to delete
def delete_key(key)
@mpw.delete_key(key)
@mpw.write_data
puts I18n.t('form.delete_key.valid').to_s.green
rescue => e
puts "#{I18n.t('display.error')} #15: #{e}".red
end
# Text editor interface
# @args: template -> template name
# item -> the item to edit
# password -> disable field password
def text_editor(template_name, item = nil, password = false)
editor = ENV['EDITOR'] || 'nano'
options = {}
opts = {}
template_file = "#{File.expand_path('../../../templates', __FILE__)}/#{template_name}.erb"
template = ERB.new(IO.read(template_file))
Dir.mktmpdir do |dir|
tmp_file = "#{dir}/#{template_name}.yml"
File.open(tmp_file, 'w') do |f|
f << template.result(binding)
opts = YAML.load_file(tmp_file)
end
system("#{editor} #{tmp_file}")
opts.delete_if { |_, v| v.to_s.empty? }
opts = YAML.load_file(tmp_file)
opts.each do |k, v|
options[k.to_sym] = v
end
options
end
opts.delete_if { |_, v| v.to_s.empty? }
opts.each do |k, v|
options[k.to_sym] = v
end
options
end
# Form to add a new item
# @args: password -> generate a random password
def add(password = false)
options = text_editor('add_form', nil, password)
item = Item.new(options)
options[:password] = MPW.password(@config.password) if password
@mpw.add(item)
@mpw.set_password(item.id, options[:password]) if options.key?(:password)
@mpw.set_otp_key(item.id, options[:otp_key]) if options.key?(:otp_key)
@mpw.write_data
puts I18n.t('form.add_item.valid').to_s.green
rescue => e
puts "#{I18n.t('display.error')} #13: #{e}".red
end
# Update an item
# @args: password -> generate a random password
# options -> the option to search
def update(password = false, **options)
items = @mpw.list(options)
if items.empty?
puts "#{I18n.t('display.warning')}: #{I18n.t('warning.select')}".yellow
else
table_items(items) if items.length > 1
item = get_item(items)
options = text_editor('update_form', item, password)
# Form to add a new item
# @args: password -> generate a random password
def add(password = false)
options = text_editor('add_form', nil, password)
item = Item.new(options)
options[:password] = MPW.password(@config.password) if password
item.update(options)
@mpw.add(item)
@mpw.set_password(item.id, options[:password]) if options.key?(:password)
@mpw.set_otp_key(item.id, options[:otp_key]) if options.key?(:otp_key)
@mpw.write_data
puts I18n.t('form.update_item.valid').to_s.green
puts I18n.t('form.add_item.valid').to_s.green
rescue => e
puts "#{I18n.t('display.error')} #13: #{e}".red
end
rescue => e
puts "#{I18n.t('display.error')} #14: #{e}".red
end
# Remove an item
# @args: options -> the option to search
def delete(**options)
items = @mpw.list(options)
# Update an item
# @args: password -> generate a random password
# options -> the option to search
def update(password = false, **options)
items = @mpw.list(options)
if items.empty?
puts "#{I18n.t('display.warning')}: #{I18n.t('warning.select')}".yellow
else
table_items(items)
if items.empty?
puts "#{I18n.t('display.warning')}: #{I18n.t('warning.select')}".yellow
else
table_items(items) if items.length > 1
item = get_item(items)
confirm = ask("#{I18n.t('form.delete_item.ask')} (y/N) ").to_s
item = get_item(items)
options = text_editor('update_form', item, password)
options[:password] = MPW.password(@config.password) if password
return unless confirm =~ /^(y|yes|YES|Yes|Y)$/
item.update(options)
@mpw.set_password(item.id, options[:password]) if options.key?(:password)
@mpw.set_otp_key(item.id, options[:otp_key]) if options.key?(:otp_key)
@mpw.write_data
puts I18n.t('form.update_item.valid').to_s.green
end
rescue => e
puts "#{I18n.t('display.error')} #14: #{e}".red
end
# Remove an item
# @args: options -> the option to search
def delete(**options)
items = @mpw.list(options)
if items.empty?
puts "#{I18n.t('display.warning')}: #{I18n.t('warning.select')}".yellow
else
table_items(items)
item = get_item(items)
confirm = ask("#{I18n.t('form.delete_item.ask')} (y/N) ").to_s
return unless confirm =~ /^(y|yes|YES|Yes|Y)$/
item.delete
@mpw.write_data
puts I18n.t('form.delete_item.valid').to_s.green
end
rescue => e
puts "#{I18n.t('display.error')} #16: #{e}".red
end
# Copy a password, otp, login
# @args: clipboard -> enable clipboard
# options -> the option to search
def copy(clipboard = true, **options)
items = @mpw.list(options)
if items.empty?
puts I18n.t('display.nothing')
else
table_items(items)
item = get_item(items)
clipboard(item, clipboard)
end
rescue => e
puts "#{I18n.t('display.error')} #14: #{e}".red
end
# Export the items in a CSV file
# @args: file -> the destination file
# options -> option to search
def export(file, options)
file = 'export-mpw.yml' if file.to_s.empty?
items = @mpw.list(options)
data = {}
items.each do |item|
data.merge!(
item.id => {
'host' => item.host,
'user' => item.user,
'group' => item.group,
'password' => @mpw.get_password(item.id),
'protocol' => item.protocol,
'port' => item.port,
'otp_key' => @mpw.get_otp_key(item.id),
'comment' => item.comment,
'last_edit' => item.last_edit,
'created' => item.created,
}
)
end
File.open(file, 'w') { |f| f << data.to_yaml }
puts I18n.t('form.export.valid', file: file).to_s.green
rescue => e
puts "#{I18n.t('display.error')} #17: #{e}".red
end
# Import items from a YAML file
# @args: file -> the import file
def import(file)
raise I18n.t('form.import.file_empty') if file.to_s.empty?
raise I18n.t('form.import.file_not_exist') unless File.exist?(file)
YAML.load_file(file).each_value do |row|
item = Item.new(group: row['group'],
host: row['host'],
protocol: row['protocol'],
user: row['user'],
port: row['port'],
comment: row['comment'])
next if item.empty?
@mpw.add(item)
@mpw.set_password(item.id, row['password']) unless row['password'].to_s.empty?
@mpw.set_otp_key(item.id, row['otp_key']) unless row['otp_key'].to_s.empty?
end
item.delete
@mpw.write_data
puts I18n.t('form.delete_item.valid').to_s.green
puts I18n.t('form.import.valid').to_s.green
rescue => e
puts "#{I18n.t('display.error')} #18: #{e}".red
end
rescue => e
puts "#{I18n.t('display.error')} #16: #{e}".red
end
# Copy a password, otp, login
# @args: clipboard -> enable clipboard
# options -> the option to search
def copy(clipboard = true, **options)
items = @mpw.list(options)
if items.empty?
puts I18n.t('display.nothing')
else
table_items(items)
item = get_item(items)
clipboard(item, clipboard)
end
rescue => e
puts "#{I18n.t('display.error')} #14: #{e}".red
end
# Export the items in a CSV file
# @args: file -> the destination file
# options -> option to search
def export(file, options)
file = 'export-mpw.yml' if file.to_s.empty?
items = @mpw.list(options)
data = {}
items.each do |item|
data.merge!(
item.id => {
'host' => item.host,
'user' => item.user,
'group' => item.group,
'password' => @mpw.get_password(item.id),
'protocol' => item.protocol,
'port' => item.port,
'otp_key' => @mpw.get_otp_key(item.id),
'comment' => item.comment,
'last_edit' => item.last_edit,
'created' => item.created,
}
)
end
File.open(file, 'w') { |f| f << data.to_yaml }
puts I18n.t('form.export.valid', file: file).to_s.green
rescue => e
puts "#{I18n.t('display.error')} #17: #{e}".red
end
# Import items from a YAML file
# @args: file -> the import file
def import(file)
raise I18n.t('form.import.file_empty') if file.to_s.empty?
raise I18n.t('form.import.file_not_exist') unless File.exist?(file)
YAML.load_file(file).each_value do |row|
item = Item.new(group: row['group'],
host: row['host'],
protocol: row['protocol'],
user: row['user'],
port: row['port'],
comment: row['comment'])
next if item.empty?
@mpw.add(item)
@mpw.set_password(item.id, row['password']) unless row['password'].to_s.empty?
@mpw.set_otp_key(item.id, row['otp_key']) unless row['otp_key'].to_s.empty?
end
@mpw.write_data
puts I18n.t('form.import.valid').to_s.green
rescue => e
puts "#{I18n.t('display.error')} #18: #{e}".red
end
end
end

View file

@ -22,133 +22,133 @@ require 'i18n'
require 'fileutils'
module MPW
class Config
attr_accessor :error_msg
class Config
attr_accessor :error_msg
attr_accessor :gpg_key
attr_accessor :lang
attr_accessor :config_dir
attr_accessor :default_wallet
attr_accessor :wallet_dir
attr_accessor :gpg_exe
attr_accessor :password
attr_accessor :gpg_key
attr_accessor :lang
attr_accessor :config_dir
attr_accessor :default_wallet
attr_accessor :wallet_dir
attr_accessor :gpg_exe
attr_accessor :password
# Constructor
# @args: config_file -> the specify config file
def initialize(config_file = nil)
@config_file = config_file
# Constructor
# @args: config_file -> the specify config file
def initialize(config_file = nil)
@config_file = config_file
@config_dir =
if /darwin/ =~ RUBY_PLATFORM
"#{Dir.home}/Library/Preferences/mpw"
elsif /cygwin|mswin|mingw|bccwin|wince|emx/ =~ RUBY_PLATFORM
"#{Dir.home}/AppData/Local/mpw"
else
"#{Dir.home}/.config/mpw"
@config_dir =
if /darwin/ =~ RUBY_PLATFORM
"#{Dir.home}/Library/Preferences/mpw"
elsif /cygwin|mswin|mingw|bccwin|wince|emx/ =~ RUBY_PLATFORM
"#{Dir.home}/AppData/Local/mpw"
else
"#{Dir.home}/.config/mpw"
end
@config_file = "#{@config_dir}/mpw.cfg" if @config_file.nil? || @config_file.empty?
end
# Create a new config file
# @args: options -> hash with values
# @rtrn: true if le config file is create
def setup(options)
gpg_key = options[:gpg_key] || @gpg_key
lang = options[:lang] || @lang
wallet_dir = options[:wallet_dir] || @wallet_dir
default_wallet = options[:default_wallet] || @default_wallet
gpg_exe = options[:gpg_exe] || @gpg_exe
password = { numeric: true,
alpha: true,
special: false,
length: 16 }
%w(numeric special alpha length).each do |k|
if options.key?("pwd_#{k}".to_sym)
password[k.to_sym] = options["pwd_#{k}".to_sym]
elsif !@password.nil? && @password.key?(k.to_sym)
password[k.to_sym] = @password[k.to_sym]
end
end
@config_file = "#{@config_dir}/mpw.cfg" if @config_file.nil? || @config_file.empty?
end
# Create a new config file
# @args: options -> hash with values
# @rtrn: true if le config file is create
def setup(options)
gpg_key = options[:gpg_key] || @gpg_key
lang = options[:lang] || @lang
wallet_dir = options[:wallet_dir] || @wallet_dir
default_wallet = options[:default_wallet] || @default_wallet
gpg_exe = options[:gpg_exe] || @gpg_exe
password = { numeric: true,
alpha: true,
special: false,
length: 16 }
%w(numeric special alpha length).each do |k|
if options.key?("pwd_#{k}".to_sym)
password[k.to_sym] = options["pwd_#{k}".to_sym]
elsif !@password.nil? && @password.key?(k.to_sym)
password[k.to_sym] = @password[k.to_sym]
unless gpg_key =~ /[a-zA-Z0-9.-_]+\@[a-zA-Z0-9]+\.[a-zA-Z]+/
raise I18n.t('error.config.key_bad_format')
end
wallet_dir = "#{@config_dir}/wallets" if wallet_dir.to_s.empty?
config = { 'gpg_key' => gpg_key,
'lang' => lang,
'wallet_dir' => wallet_dir,
'default_wallet' => default_wallet,
'gpg_exe' => gpg_exe,
'password' => password }
FileUtils.mkdir_p(@config_dir, mode: 0700)
FileUtils.mkdir_p(wallet_dir, mode: 0700)
File.open(@config_file, 'w') do |file|
file << config.to_yaml
end
rescue => e
raise "#{I18n.t('error.config.write')}\n#{e}"
end
unless gpg_key =~ /[a-zA-Z0-9.-_]+\@[a-zA-Z0-9]+\.[a-zA-Z]+/
raise I18n.t('error.config.key_bad_format')
# Setup a new gpg key
# @args: password -> the GPG key password
# name -> the name of user
# length -> length of the GPG key
# expire -> the time of expire to GPG key
# @rtrn: true if the GPG key is create, else false
def setup_gpg_key(password, name, length = 4096, expire = 0)
raise I18n.t('error.config.genkey_gpg.name') if name.to_s.empty?
raise I18n.t('error.config.genkey_gpg.password') if password.to_s.empty?
param = ''
param << '<GnupgKeyParms format="internal">' + "\n"
param << "Key-Type: RSA\n"
param << "Key-Length: #{length}\n"
param << "Subkey-Type: ELG-E\n"
param << "Subkey-Length: #{length}\n"
param << "Name-Real: #{name}\n"
param << "Name-Comment: #{name}\n"
param << "Name-Email: #{@gpg_key}\n"
param << "Expire-Date: #{expire}\n"
param << "Passphrase: #{password}\n"
param << "</GnupgKeyParms>\n"
ctx = GPGME::Ctx.new
ctx.genkey(param, nil, nil)
rescue => e
raise "#{I18n.t('error.config.genkey_gpg.exception')}\n#{e}"
end
wallet_dir = "#{@config_dir}/wallets" if wallet_dir.to_s.empty?
config = { 'gpg_key' => gpg_key,
'lang' => lang,
'wallet_dir' => wallet_dir,
'default_wallet' => default_wallet,
'gpg_exe' => gpg_exe,
'password' => password }
# Load the config file
def load_config
config = YAML.load_file(@config_file)
@gpg_key = config['gpg_key']
@lang = config['lang']
@wallet_dir = config['wallet_dir']
@default_wallet = config['default_wallet']
@gpg_exe = config['gpg_exe']
@password = config['password'] || {}
FileUtils.mkdir_p(@config_dir, mode: 0700)
FileUtils.mkdir_p(wallet_dir, mode: 0700)
raise if @gpg_key.empty? || @wallet_dir.empty?
File.open(@config_file, 'w') do |file|
file << config.to_yaml
end
rescue => e
raise "#{I18n.t('error.config.write')}\n#{e}"
end
# Setup a new gpg key
# @args: password -> the GPG key password
# name -> the name of user
# length -> length of the GPG key
# expire -> the time of expire to GPG key
# @rtrn: true if the GPG key is create, else false
def setup_gpg_key(password, name, length = 4096, expire = 0)
raise I18n.t('error.config.genkey_gpg.name') if name.to_s.empty?
raise I18n.t('error.config.genkey_gpg.password') if password.to_s.empty?
param = ''
param << '<GnupgKeyParms format="internal">' + "\n"
param << "Key-Type: RSA\n"
param << "Key-Length: #{length}\n"
param << "Subkey-Type: ELG-E\n"
param << "Subkey-Length: #{length}\n"
param << "Name-Real: #{name}\n"
param << "Name-Comment: #{name}\n"
param << "Name-Email: #{@gpg_key}\n"
param << "Expire-Date: #{expire}\n"
param << "Passphrase: #{password}\n"
param << "</GnupgKeyParms>\n"
ctx = GPGME::Ctx.new
ctx.genkey(param, nil, nil)
rescue => e
raise "#{I18n.t('error.config.genkey_gpg.exception')}\n#{e}"
end
# Load the config file
def load_config
config = YAML.load_file(@config_file)
@gpg_key = config['gpg_key']
@lang = config['lang']
@wallet_dir = config['wallet_dir']
@default_wallet = config['default_wallet']
@gpg_exe = config['gpg_exe']
@password = config['password'] || {}
raise if @gpg_key.empty? || @wallet_dir.empty?
I18n.locale = @lang.to_sym
rescue => e
raise "#{I18n.t('error.config.load')}\n#{e}"
end
# Check if private key exist
# @rtrn: true if the key exist, else false
def check_gpg_key?
ctx = GPGME::Ctx.new
ctx.each_key(@gpg_key, true) do
return true
I18n.locale = @lang.to_sym
rescue => e
raise "#{I18n.t('error.config.load')}\n#{e}"
end
false
# Check if private key exist
# @rtrn: true if the key exist, else false
def check_gpg_key?
ctx = GPGME::Ctx.new
ctx.each_key(@gpg_key, true) do
return true
end
false
end
end
end
end

View file

@ -19,84 +19,84 @@
require 'i18n'
module MPW
class Item
attr_accessor :id
attr_accessor :group
attr_accessor :host
attr_accessor :protocol
attr_accessor :user
attr_accessor :port
attr_accessor :otp
attr_accessor :comment
attr_accessor :last_edit
attr_accessor :created
class Item
attr_accessor :id
attr_accessor :group
attr_accessor :host
attr_accessor :protocol
attr_accessor :user
attr_accessor :port
attr_accessor :otp
attr_accessor :comment
attr_accessor :last_edit
attr_accessor :created
# Constructor
# Create a new item
# @args: options -> a hash of parameter
# raise an error if the hash hasn't the key name
def initialize(**options)
if !options.key?(:host) || options[:host].to_s.empty?
raise I18n.t('error.update.host_empty')
# Constructor
# Create a new item
# @args: options -> a hash of parameter
# raise an error if the hash hasn't the key name
def initialize(**options)
if !options.key?(:host) || options[:host].to_s.empty?
raise I18n.t('error.update.host_empty')
end
if !options.key?(:id) || options[:id].to_s.empty? || !options.key?(:created) || options[:created].to_s.empty?
@id = generate_id
@created = Time.now.to_i
else
@id = options[:id]
@created = options[:created]
@last_edit = options[:last_edit]
options[:no_update_last_edit] = true
end
update(options)
end
if !options.key?(:id) || options[:id].to_s.empty? || !options.key?(:created) || options[:created].to_s.empty?
@id = generate_id
@created = Time.now.to_i
else
@id = options[:id]
@created = options[:created]
@last_edit = options[:last_edit]
options[:no_update_last_edit] = true
# Update the item
# @args: options -> a hash of parameter
def update(**options)
if options.key?(:host) && options[:host].to_s.empty?
raise I18n.t('error.update.host_empty')
end
@group = options[:group] if options.key?(:group)
@host = options[:host] if options.key?(:host)
@protocol = options[:protocol] if options.key?(:protocol)
@user = options[:user] if options.key?(:user)
@port = options[:port].to_i if options.key?(:port) && !options[:port].to_s.empty?
@otp = options[:otp] if options.key?(:otp)
@comment = options[:comment] if options.key?(:comment)
@last_edit = Time.now.to_i unless options.key?(:no_update_last_edit)
end
update(options)
end
# Update the item
# @args: options -> a hash of parameter
def update(**options)
if options.key?(:host) && options[:host].to_s.empty?
raise I18n.t('error.update.host_empty')
# Delete all data
def delete
@id = nil
@group = nil
@host = nil
@protocol = nil
@user = nil
@port = nil
@otp = nil
@comment = nil
@created = nil
@last_edit = nil
end
@group = options[:group] if options.key?(:group)
@host = options[:host] if options.key?(:host)
@protocol = options[:protocol] if options.key?(:protocol)
@user = options[:user] if options.key?(:user)
@port = options[:port].to_i if options.key?(:port) && !options[:port].to_s.empty?
@otp = options[:otp] if options.key?(:otp)
@comment = options[:comment] if options.key?(:comment)
@last_edit = Time.now.to_i unless options.key?(:no_update_last_edit)
end
def empty?
@id.to_s.empty?
end
# Delete all data
def delete
@id = nil
@group = nil
@host = nil
@protocol = nil
@user = nil
@port = nil
@otp = nil
@comment = nil
@created = nil
@last_edit = nil
end
def nil?
false
end
def empty?
@id.to_s.empty?
end
private
def nil?
false
end
private
# Generate an random id
def generate_id
[*('A'..'Z'), *('a'..'z'), *('0'..'9')].sample(16).join
# Generate an random id
def generate_id
[*('A'..'Z'), *('a'..'z'), *('0'..'9')].sample(16).join
end
end
end
end

View file

@ -24,341 +24,341 @@ require 'rotp'
require 'mpw/item'
module MPW
class MPW
# Constructor
def initialize(key, wallet_file, gpg_pass = nil, gpg_exe = nil)
@key = key
@gpg_pass = gpg_pass
@gpg_exe = gpg_exe
@wallet_file = wallet_file
class MPW
# Constructor
def initialize(key, wallet_file, gpg_pass = nil, gpg_exe = nil)
@key = key
@gpg_pass = gpg_pass
@gpg_exe = gpg_exe
@wallet_file = wallet_file
GPGME::Engine.set_info(GPGME::PROTOCOL_OpenPGP, @gpg_exe, "#{Dir.home}/.gnupg") unless @gpg_exe.to_s.empty?
end
# Read mpw file
def read_data
@config = {}
@data = []
@keys = {}
@passwords = {}
@otp_keys = {}
data = nil
return unless File.exist?(@wallet_file)
Gem::Package::TarReader.new(File.open(@wallet_file)) do |tar|
tar.each do |f|
case f.full_name
when 'wallet/config.gpg'
@config = YAML.safe_load(decrypt(f.read))
when 'wallet/meta.gpg'
data = decrypt(f.read)
when %r{^wallet/keys/(?<key>.+)\.pub$}
key = Regexp.last_match('key')
if GPGME::Key.find(:public, key).empty?
GPGME::Key.import(f.read, armor: true)
end
@keys[key] = f.read
when %r{^wallet/passwords/(?<id>[a-zA-Z0-9]+)\.gpg$}
@passwords[Regexp.last_match('id')] = f.read
when %r{^wallet/otp_keys/(?<id>[a-zA-Z0-9]+)\.gpg$}
@otp_keys[Regexp.last_match('id')] = f.read
else
next
end
end
GPGME::Engine.set_info(GPGME::PROTOCOL_OpenPGP, @gpg_exe, "#{Dir.home}/.gnupg") unless @gpg_exe.to_s.empty?
end
unless data.to_s.empty?
YAML.safe_load(data).each_value do |d|
@data.push(
Item.new(
id: d['id'],
group: d['group'],
host: d['host'],
protocol: d['protocol'],
user: d['user'],
port: d['port'],
otp: @otp_keys.key?(d['id']),
comment: d['comment'],
last_edit: d['last_edit'],
created: d['created'],
# Read mpw file
def read_data
@config = {}
@data = []
@keys = {}
@passwords = {}
@otp_keys = {}
data = nil
return unless File.exist?(@wallet_file)
Gem::Package::TarReader.new(File.open(@wallet_file)) do |tar|
tar.each do |f|
case f.full_name
when 'wallet/config.gpg'
@config = YAML.safe_load(decrypt(f.read))
when 'wallet/meta.gpg'
data = decrypt(f.read)
when %r{^wallet/keys/(?<key>.+)\.pub$}
key = Regexp.last_match('key')
if GPGME::Key.find(:public, key).empty?
GPGME::Key.import(f.read, armor: true)
end
@keys[key] = f.read
when %r{^wallet/passwords/(?<id>[a-zA-Z0-9]+)\.gpg$}
@passwords[Regexp.last_match('id')] = f.read
when %r{^wallet/otp_keys/(?<id>[a-zA-Z0-9]+)\.gpg$}
@otp_keys[Regexp.last_match('id')] = f.read
else
next
end
end
end
unless data.to_s.empty?
YAML.safe_load(data).each_value do |d|
@data.push(
Item.new(
id: d['id'],
group: d['group'],
host: d['host'],
protocol: d['protocol'],
user: d['user'],
port: d['port'],
otp: @otp_keys.key?(d['id']),
comment: d['comment'],
last_edit: d['last_edit'],
created: d['created'],
)
)
end
end
add_key(@key) if @keys[@key].nil?
rescue => e
raise "#{I18n.t('error.mpw_file.read_data')}\n#{e}"
end
# Encrypt a file
def write_data
data = {}
tmp_file = "#{@wallet_file}.tmp"
@data.each do |item|
next if item.empty?
data.merge!(
item.id => {
'id' => item.id,
'group' => item.group,
'host' => item.host,
'protocol' => item.protocol,
'user' => item.user,
'port' => item.port,
'comment' => item.comment,
'last_edit' => item.last_edit,
'created' => item.created,
}
)
end
end
add_key(@key) if @keys[@key].nil?
rescue => e
raise "#{I18n.t('error.mpw_file.read_data')}\n#{e}"
end
@config['last_update'] = Time.now.to_i
# Encrypt a file
def write_data
data = {}
tmp_file = "#{@wallet_file}.tmp"
Gem::Package::TarWriter.new(File.open(tmp_file, 'w+')) do |tar|
data_encrypt = encrypt(data.to_yaml)
tar.add_file_simple('wallet/meta.gpg', 0400, data_encrypt.length) do |io|
io.write(data_encrypt)
end
@data.each do |item|
next if item.empty?
config = encrypt(@config.to_yaml)
tar.add_file_simple('wallet/config.gpg', 0400, config.length) do |io|
io.write(config)
end
data.merge!(
item.id => {
'id' => item.id,
'group' => item.group,
'host' => item.host,
'protocol' => item.protocol,
'user' => item.user,
'port' => item.port,
'comment' => item.comment,
'last_edit' => item.last_edit,
'created' => item.created,
}
)
end
@passwords.each do |id, password|
tar.add_file_simple("wallet/passwords/#{id}.gpg", 0400, password.length) do |io|
io.write(password)
end
end
@config['last_update'] = Time.now.to_i
@otp_keys.each do |id, key|
tar.add_file_simple("wallet/otp_keys/#{id}.gpg", 0400, key.length) do |io|
io.write(key)
end
end
Gem::Package::TarWriter.new(File.open(tmp_file, 'w+')) do |tar|
data_encrypt = encrypt(data.to_yaml)
tar.add_file_simple('wallet/meta.gpg', 0400, data_encrypt.length) do |io|
io.write(data_encrypt)
end
config = encrypt(@config.to_yaml)
tar.add_file_simple('wallet/config.gpg', 0400, config.length) do |io|
io.write(config)
end
@passwords.each do |id, password|
tar.add_file_simple("wallet/passwords/#{id}.gpg", 0400, password.length) do |io|
io.write(password)
@keys.each do |id, key|
tar.add_file_simple("wallet/keys/#{id}.pub", 0400, key.length) do |io|
io.write(key)
end
end
end
@otp_keys.each do |id, key|
tar.add_file_simple("wallet/otp_keys/#{id}.gpg", 0400, key.length) do |io|
io.write(key)
end
end
File.rename(tmp_file, @wallet_file)
rescue => e
File.unlink(tmp_file) if File.exist?(tmp_file)
@keys.each do |id, key|
tar.add_file_simple("wallet/keys/#{id}.pub", 0400, key.length) do |io|
io.write(key)
end
end
raise "#{I18n.t('error.mpw_file.write_data')}\n#{e}"
end
File.rename(tmp_file, @wallet_file)
rescue => e
File.unlink(tmp_file) if File.exist?(tmp_file)
# Get a password
# args: id -> the item id
def get_password(id)
password = decrypt(@passwords[id])
raise "#{I18n.t('error.mpw_file.write_data')}\n#{e}"
end
# Get a password
# args: id -> the item id
def get_password(id)
password = decrypt(@passwords[id])
if /^\$[a-zA-Z0-9]{4,9}::(?<password>.+)$/ =~ password
Regexp.last_match('password')
else
password
end
end
# Set a password
# args: id -> the item id
# password -> the new password
def set_password(id, password)
salt = MPW.password(length: Random.rand(4..9))
password = "$#{salt}::#{password}"
@passwords[id] = encrypt(password)
end
# Return the list of all gpg keys
# rtrn: an array with the gpg keys name
def list_keys
@keys.keys
end
# Add a public key
# args: key -> new public key file or name
def add_key(key)
if File.exist?(key)
data = File.open(key).read
key_import = GPGME::Key.import(data, armor: true)
key = GPGME::Key.get(key_import.imports[0].fpr).uids[0].email
else
data = GPGME::Key.export(key, armor: true).read
end
raise I18n.t('error.export_key') if data.to_s.empty?
@keys[key] = data
@passwords.each_key { |id| set_password(id, get_password(id)) }
@otp_keys.each_key { |id| set_otp_key(id, get_otp_key(id)) }
end
# Delete a public key
# args: key -> public key to delete
def delete_key(key)
@keys.delete(key)
@passwords.each_key { |id| set_password(id, get_password(id)) }
@otp_keys.each_key { |id| set_otp_key(id, get_otp_key(id)) }
end
# Set config
# args: config -> a hash with config options
def set_config(**options)
@config = {} if @config.nil?
@config['protocol'] = options[:protocol] if options.key?(:protocol)
@config['host'] = options[:host] if options.key?(:host)
@config['port'] = options[:port] if options.key?(:port)
@config['user'] = options[:user] if options.key?(:user)
@config['password'] = options[:password] if options.key?(:password)
@config['path'] = options[:path] if options.key?(:path)
end
# Add a new item
# @args: item -> Object MPW::Item
def add(item)
raise I18n.t('error.bad_class') unless item.instance_of?(Item)
raise I18n.t('error.empty') if item.empty?
@data.push(item)
end
# Search in some csv data
# @args: options -> a hash with paramaters
# @rtrn: a list with the resultat of the search
def list(**options)
result = []
search = options[:pattern].to_s.downcase
group = options[:group].to_s.downcase
@data.each do |item|
next if item.empty?
next unless group.empty? || group.eql?(item.group.to_s.downcase)
host = item.host.to_s.downcase
comment = item.comment.to_s.downcase
next unless host =~ /^.*#{search}.*$/ || comment =~ /^.*#{search}.*$/
result.push(item)
end
result
end
# Search in some csv data
# @args: id -> the id item
# @rtrn: a row with the result of the search
def search_by_id(id)
@data.each do |item|
return item if item.id == id
end
nil
end
# Set an opt key
# args: id -> the item id
# key -> the new key
def set_otp_key(id, key)
@otp_keys[id] = encrypt(key.to_s) unless key.to_s.empty?
end
# Get an opt key
# args: id -> the item id
# key -> the new key
def get_otp_key(id)
@otp_keys.key?(id) ? decrypt(@otp_keys[id]) : nil
end
# Get an otp code
# @args: id -> the item id
# @rtrn: an otp code
def get_otp_code(id)
@otp_keys.key?(id) ? 0 : ROTP::TOTP.new(decrypt(@otp_keys[id])).now
end
# Get remaining time before expire otp code
# @rtrn: return time in seconde
def get_otp_remaining_time
(Time.now.utc.to_i / 30 + 1) * 30 - Time.now.utc.to_i
end
# Generate a random password
# @args: options -> :length, :special, :alpha, :numeric
# @rtrn: a random string
def self.password(**options)
length =
if !options.include?(:length) || options[:length].to_i <= 0
8
elsif options[:length].to_i >= 32_768
32_768
if /^\$[a-zA-Z0-9]{4,9}::(?<password>.+)$/ =~ password
Regexp.last_match('password')
else
options[:length].to_i
password
end
end
# Set a password
# args: id -> the item id
# password -> the new password
def set_password(id, password)
salt = MPW.password(length: Random.rand(4..9))
password = "$#{salt}::#{password}"
@passwords[id] = encrypt(password)
end
# Return the list of all gpg keys
# rtrn: an array with the gpg keys name
def list_keys
@keys.keys
end
# Add a public key
# args: key -> new public key file or name
def add_key(key)
if File.exist?(key)
data = File.open(key).read
key_import = GPGME::Key.import(data, armor: true)
key = GPGME::Key.get(key_import.imports[0].fpr).uids[0].email
else
data = GPGME::Key.export(key, armor: true).read
end
chars = []
chars += [*('!'..'?')] - [*('0'..'9')] if options[:special]
chars += [*('A'..'Z'), *('a'..'z')] if options[:alpha]
chars += [*('0'..'9')] if options[:numeric]
chars = [*('A'..'Z'), *('a'..'z'), *('0'..'9')] if chars.empty?
raise I18n.t('error.export_key') if data.to_s.empty?
result = ''
while length > 62
result << chars.sample(62).join
length -= 62
end
result << chars.sample(length).join
result
end
private
# Decrypt a gpg file
# @args: data -> string to decrypt
def decrypt(data)
return nil if data.to_s.empty?
crypto = GPGME::Crypto.new(armor: true)
crypto.decrypt(data, password: @gpg_pass).read.force_encoding('utf-8')
rescue => e
raise "#{I18n.t('error.gpg_file.decrypt')}\n#{e}"
end
# Encrypt a file
# args: data -> string to encrypt
def encrypt(data)
recipients = []
crypto = GPGME::Crypto.new(armor: true, always_trust: true)
recipients.push(@key)
@keys.each_key do |key|
next if key == @key
recipients.push(key)
@keys[key] = data
@passwords.each_key { |id| set_password(id, get_password(id)) }
@otp_keys.each_key { |id| set_otp_key(id, get_otp_key(id)) }
end
crypto.encrypt(data, recipients: recipients).read
rescue => e
raise "#{I18n.t('error.gpg_file.encrypt')}\n#{e}"
# Delete a public key
# args: key -> public key to delete
def delete_key(key)
@keys.delete(key)
@passwords.each_key { |id| set_password(id, get_password(id)) }
@otp_keys.each_key { |id| set_otp_key(id, get_otp_key(id)) }
end
# Set config
# args: config -> a hash with config options
def set_config(**options)
@config = {} if @config.nil?
@config['protocol'] = options[:protocol] if options.key?(:protocol)
@config['host'] = options[:host] if options.key?(:host)
@config['port'] = options[:port] if options.key?(:port)
@config['user'] = options[:user] if options.key?(:user)
@config['password'] = options[:password] if options.key?(:password)
@config['path'] = options[:path] if options.key?(:path)
end
# Add a new item
# @args: item -> Object MPW::Item
def add(item)
raise I18n.t('error.bad_class') unless item.instance_of?(Item)
raise I18n.t('error.empty') if item.empty?
@data.push(item)
end
# Search in some csv data
# @args: options -> a hash with paramaters
# @rtrn: a list with the resultat of the search
def list(**options)
result = []
search = options[:pattern].to_s.downcase
group = options[:group].to_s.downcase
@data.each do |item|
next if item.empty?
next unless group.empty? || group.eql?(item.group.to_s.downcase)
host = item.host.to_s.downcase
comment = item.comment.to_s.downcase
next unless host =~ /^.*#{search}.*$/ || comment =~ /^.*#{search}.*$/
result.push(item)
end
result
end
# Search in some csv data
# @args: id -> the id item
# @rtrn: a row with the result of the search
def search_by_id(id)
@data.each do |item|
return item if item.id == id
end
nil
end
# Set an opt key
# args: id -> the item id
# key -> the new key
def set_otp_key(id, key)
@otp_keys[id] = encrypt(key.to_s) unless key.to_s.empty?
end
# Get an opt key
# args: id -> the item id
# key -> the new key
def get_otp_key(id)
@otp_keys.key?(id) ? decrypt(@otp_keys[id]) : nil
end
# Get an otp code
# @args: id -> the item id
# @rtrn: an otp code
def get_otp_code(id)
@otp_keys.key?(id) ? 0 : ROTP::TOTP.new(decrypt(@otp_keys[id])).now
end
# Get remaining time before expire otp code
# @rtrn: return time in seconde
def get_otp_remaining_time
(Time.now.utc.to_i / 30 + 1) * 30 - Time.now.utc.to_i
end
# Generate a random password
# @args: options -> :length, :special, :alpha, :numeric
# @rtrn: a random string
def self.password(**options)
length =
if !options.include?(:length) || options[:length].to_i <= 0
8
elsif options[:length].to_i >= 32_768
32_768
else
options[:length].to_i
end
chars = []
chars += [*('!'..'?')] - [*('0'..'9')] if options[:special]
chars += [*('A'..'Z'), *('a'..'z')] if options[:alpha]
chars += [*('0'..'9')] if options[:numeric]
chars = [*('A'..'Z'), *('a'..'z'), *('0'..'9')] if chars.empty?
result = ''
while length > 62
result << chars.sample(62).join
length -= 62
end
result << chars.sample(length).join
result
end
private
# Decrypt a gpg file
# @args: data -> string to decrypt
def decrypt(data)
return nil if data.to_s.empty?
crypto = GPGME::Crypto.new(armor: true)
crypto.decrypt(data, password: @gpg_pass).read.force_encoding('utf-8')
rescue => e
raise "#{I18n.t('error.gpg_file.decrypt')}\n#{e}"
end
# Encrypt a file
# args: data -> string to encrypt
def encrypt(data)
recipients = []
crypto = GPGME::Crypto.new(armor: true, always_trust: true)
recipients.push(@key)
@keys.each_key do |key|
next if key == @key
recipients.push(key)
end
crypto.encrypt(data, recipients: recipients).read
rescue => e
raise "#{I18n.t('error.gpg_file.encrypt')}\n#{e}"
end
end
end
end