Class: Keybox::Application::PasswordSafe
- Includes:
- HighLineUtil
- Defined in:
- lib/keybox/application/password_safe.rb
Constant Summary collapse
- DEFAULT_DIRECTORY =
File.join(ENV["HOME"],".keybox")
- DEFAULT_DB =
File.join(DEFAULT_DIRECTORY,"database.yaml")
- DEFAULT_CONFIG =
File.join(DEFAULT_DIRECTORY,"config.yaml")
- DEFAULT_COLOR_SCHEME =
:dark_bg
- ACTION_LIST =
%w(add delete edit show list master-password)
Constants included from HighLineUtil
Instance Attribute Summary collapse
-
#actions ⇒ Object
Returns the value of attribute actions.
-
#db ⇒ Object
readonly
Returns the value of attribute db.
Attributes inherited from Base
#error_message, #highline, #options, #parsed_options, #stderr, #stdin, #stdout
Instance Method Summary collapse
-
#add(account) ⇒ Object
add an account to the database If the account is a URL and use_password_hash_for_url is true then don’t us the URLAccountEntry instead of the usual HostAccountEntry.
-
#configuration_file_options ⇒ Object
load options from the configuration file, if the file doesn’t exist, create it and dump the default options to it.
- #default_options ⇒ Object
-
#delete(account) ⇒ Object
delete an entry from the database.
-
#edit(account) ⇒ Object
edit an entry in the database.
-
#export_to_csv(file) ⇒ Object
Export data from the database into a CSV file.
- #fill_entry(entry) ⇒ Object
-
#gather_info(entry) ⇒ Object
Gather all the information for the.
-
#import_from_csv(file) ⇒ Object
Import data into the database from a CSV file.
-
#initialize(argv = []) ⇒ PasswordSafe
constructor
A new instance of PasswordSafe.
-
#list(account) ⇒ Object
list all the entries in the database.
-
#load_color_scheme ⇒ Object
load the given color scheme.
-
#load_database ⇒ Object
load the database from its super secret location.
-
#master_password(ignore_this) ⇒ Object
Change the master password on the database.
- #option_parser ⇒ Object
- #run ⇒ Object
-
#show(account) ⇒ Object
output all the information for the accounts matching.
Methods included from HighLineUtil
Methods inherited from Base
#error_version_help, #merge_options, #set_io
Constructor Details
#initialize(argv = []) ⇒ PasswordSafe
Returns a new instance of PasswordSafe.
26 27 28 29 30 31 32 33 34 35 36 |
# File 'lib/keybox/application/password_safe.rb', line 26 def initialize(argv = []) @actions = Array.new super(argv) # only one of the actions is allowed if actions.size > 1 then @error_message = [ "ERROR: Only one of #{ACTION_LIST.join(",")} is allowed at a time", "Try `#{@parser.program_name} --help` for more information"].join("\n") end end |
Instance Attribute Details
#actions ⇒ Object
Returns the value of attribute actions.
16 17 18 |
# File 'lib/keybox/application/password_safe.rb', line 16 def actions @actions end |
#db ⇒ Object (readonly)
Returns the value of attribute db.
17 18 19 |
# File 'lib/keybox/application/password_safe.rb', line 17 def db @db end |
Instance Method Details
#add(account) ⇒ Object
add an account to the database If the account is a URL and use_password_hash_for_url is true then don’t us the URLAccountEntry instead of the usual HostAccountEntry
235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 |
# File 'lib/keybox/application/password_safe.rb', line 235 def add(account) entry = Keybox::HostAccountEntry.new(account, account) if @options.use_password_hash_for_url then begin account_uri = URI.parse(account) if not account_uri.scheme.nil? then entry = Keybox::URLAccountEntry.new(account,account) end rescue ::URI::InvalidURIError => e # just ignore it, we're fine with the Host # Account Entry end end new_entry = gather_info(entry) hsay "Adding #{new_entry.title} to database.", :information @db << new_entry end |
#configuration_file_options ⇒ Object
load options from the configuration file, if the file doesn’t exist, create it and dump the default options to it.
we use the default unless the parsed_options contain a configuration file then we use that one
133 134 135 136 137 138 139 140 141 142 143 144 145 |
# File 'lib/keybox/application/password_safe.rb', line 133 def file_path = @parsed_options.config_file || DEFAULT_CONFIG # if the file is 0 bytes, then this is illegal and needs # to be overwritten. if not File.exists?(file_path) or File.size(file_path) == 0 then FileUtils.mkdir_p(File.dirname(file_path)) File.open(file_path,"w") do |f| YAML.dump(.marshal_dump,f) end end = YAML.load_file(file_path) || Hash.new end |
#default_options ⇒ Object
115 116 117 118 119 120 121 122 123 124 125 |
# File 'lib/keybox/application/password_safe.rb', line 115 def = OpenStruct.new .debug = 0 .show_help = false .show_version = false .config_file = Keybox::Application::PasswordSafe::DEFAULT_CONFIG .db_file = Keybox::Application::PasswordSafe::DEFAULT_DB .use_password_hash_for_url = false .color_scheme = Keybox::Application::PasswordSafe::DEFAULT_COLOR_SCHEME return end |
#delete(account) ⇒ Object
delete an entry from the database
281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 |
# File 'lib/keybox/application/password_safe.rb', line 281 def delete(account) matches = @db.find(account) count = 0 matches.each do |match| hsay "-" * 40, :separator_bar hsay match, :normal hsay "-" * 40, :separator_bar if hagree "Delete this entry (y/n) ?" then @db.delete(match) count += 1 end end hsay "#{count} records matching '#{account}' deleted.", :information end |
#edit(account) ⇒ Object
edit an entry in the database
300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 |
# File 'lib/keybox/application/password_safe.rb', line 300 def edit(account) matches = @db.find(account) count = 0 matches.each do |match| hsay "-" * 40, :separator_bar hsay match, :normal hsay "-" * 40, :separator_bar if hagree "Edit this entry (y/n) ?" then entry = gather_info(match) @db.delete(match) @db << entry count += 1 hsay "Entry '#{entry.title}' updated.", :information end end hsay "#{count} records matching '#{account}' edited.", :information end |
#export_to_csv(file) ⇒ Object
Export data from the database into a CSV file
420 421 422 423 |
# File 'lib/keybox/application/password_safe.rb', line 420 def export_to_csv(file) Keybox::Convert::CSV.to_file(@db.records, file) hsay "Exported #{@db.records.size} records to #{file}.", :information end |
#fill_entry(entry) ⇒ Object
425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 |
# File 'lib/keybox/application/password_safe.rb', line 425 def fill_entry(entry) # calculate maximum prompt width for pretty output max_length = entry.fields.collect { |f| f.length }.max max_length += entry.values.collect { |v| v.length }.max # now prompt for the entry items entry.fields.each do |field| echo = true validate = false default = entry.send(field) p = "#{field} [#{default}]" # we don't echo private field prompts and we validate # them if entry.private_field?(field) then echo = '*' validate = true p = "#{field}" end value = prompt("#{p}",:echo => echo ,:validate => validate,:width => max_length) if value.nil? or value.size == 0 then value = default end entry.send("#{field}=",value) end return entry end |
#gather_info(entry) ⇒ Object
Gather all the information for the
257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 |
# File 'lib/keybox/application/password_safe.rb', line 257 def gather_info(entry) gathered = false while not gathered do hsay "Gathering information for entry '#{entry.title}'", :information entry = fill_entry(entry) # dump the info we have gathered and make sure that # it is the input that the user wants to store. hsay "-" * 40, :separator_bar hsay entry, :normal hsay "-" * 40, :separator_bar gathered = hagree "Is this information correct? (y/n)" end entry end |
#import_from_csv(file) ⇒ Object
Import data into the database from a CSV file
410 411 412 413 414 415 416 |
# File 'lib/keybox/application/password_safe.rb', line 410 def import_from_csv(file) entries = Keybox::Convert::CSV.from_file(file) entries.each do |entry| @db << entry end hsay "Imported #{entries.size} records from #{file}.", :information end |
#list(account) ⇒ Object
list all the entries in the database. This doesn’t show the password for any of them, just lists the key information about each entry so the user can see what is in the database
325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 |
# File 'lib/keybox/application/password_safe.rb', line 325 def list(account) matches = @db.find(account) title = "Title" username = "Username" add_info = "Additional Information" if matches.size > 0 then lengths = { :title => (matches.collect { |f| f.title.length } << title.length).max, :username => (matches.collect { |f| f.username.length } << username.length).max, :additional_info => add_info.length } full_length = lengths.values.inject(0) { |sum,n| sum + n} header = " # #{"Title".ljust(lengths[:title])} #{"Username".ljust(lengths[:username])} #{add_info}" hsay header, :header # 3 spaces for number column + 1 space after and 4 spaces between # each other column hsay"-" * (header.length), :header_bar matches.each_with_index do |match,i| line_number = sprintf("%3d", i + 1) # toggle colors color = [:even_row, :odd_row][i % 2] columns = [] [:title, :username, :additional_info].each do |f| t = match.send(f) t = "-" if t.nil? or t.length == 0 columns << t.ljust(lengths[f]) end cdata = columns.join(" " * 4) @highline.say("<%= color('#{line_number}',:line_number) %> <%= color('#{cdata}','#{color}') %>") end else hsay "No matching records were found.", :information end end |
#load_color_scheme ⇒ Object
load the given color scheme. If the scheme cannot be found it will default to the :none
scheme which has no color
The color_scheme file exists either in the application data directory, or in the same directory as the configuration file.
The file name convention for the scheme file is schemename.color_scheme.yaml
. So for instance the default :dark_bg
color scheme file is named:
dark_bg.color_scheme.yaml
161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 |
# File 'lib/keybox/application/password_safe.rb', line 161 def load_color_scheme if @options.color_scheme != :none then search_directories = [ Keybox::APP_DATA_DIR, File.dirname(@options.config_file) ] scheme_basename = "#{@options.color_scheme.to_s}.color_scheme.yaml" scheme_path = nil # get the path to the file search_directories.each do |sd| if File.exists?(File.join(sd,scheme_basename)) then scheme_path = File.join(sd,scheme_basename) break end end # if we have a file then load it and make sure we have # all the valid labels. if scheme_path then initial_color_scheme = YAML::load(File.read(scheme_path)) # make sure that everything is a Symbol and in the # process make sure that all of the required labels # are there. color_scheme = {} initial_color_scheme.each_pair do |label,ansi_seq| color_scheme[label.to_sym] = ansi_seq.collect { |a| a.to_sym } end # validate that all the required color labels exist if (NONE_SCHEME.keys - color_scheme.keys).size == 0 then ::HighLine.color_scheme = ::HighLine::ColorScheme.new(color_scheme) else @options.color_scheme = :none ::HighLine.color_scheme = ::HighLine::ColorScheme.new(NONE_SCHEME) @stdout.puts "The color scheme in file '#{scheme_path}' is Invalid" @stdout.puts "It is missing the following items:" (NONE_SCHEME.keys - color_scheme.keys).each do |missing_label| @stdout.puts "\t :#{missing_label}" end @stdout.puts "Not using any color scheme." end else # if we don't have a file then set the color # scheme to nil and we're done @options.color_scheme = :none ::HighLine.color_scheme = ::HighLine::ColorScheme.new(NONE_SCHEME) end else ::HighLine.color_scheme = ::HighLine::ColorScheme.new(NONE_SCHEME) end end |
#load_database ⇒ Object
load the database from its super secret location
219 220 221 222 223 224 225 226 227 228 |
# File 'lib/keybox/application/password_safe.rb', line 219 def load_database password = nil if not File.exists?(@options.db_file) then hsay 'Creating initial database.', :information password = prompt("Initial Password for (#{@options.db_file})", :echo => "*", :validate => true) else password = prompt("Password for (#{@options.db_file})", :echo => "*") end @db = Keybox::Storage::Container.new(password,@options.db_file) end |
#master_password(ignore_this) ⇒ Object
Change the master password on the database
402 403 404 405 |
# File 'lib/keybox/application/password_safe.rb', line 402 def master_password(ignore_this) @db.passphrase = prompt("Enter new master password", :echo => '*', :validate => true, :width => 45) hsay "New master password set.", :information end |
#option_parser ⇒ Object
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 |
# File 'lib/keybox/application/password_safe.rb', line 38 def option_parser OptionParser.new do |op| op.separator "" op.separator "General Options:" op.on("-f", "--file DATABASE_FILE", "The Database File to use") do |db_file| @parsed_options.db_file = db_file end op.on("-c", "--config CONFIG_FILE", "The Configuration file to use") do |cfile| @parsed_options.config_file = cfile end op.on("--color SCHEME","The color scheme to use", "none,dark_bg,light_bg,<other>") do |scheme| @parsed_options.color_scheme = scheme.to_sym end op.on("-D", "--debug", "Ouput debug information to STDERR") do @parsed_options.debug = true end op.on("--[no-]use-hash-for-url", "Use the password hash algorithm ", " for URL accounts") do |r| @parsed_options.use_password_hash_for_url = r end op.separator "" op.separator "Commands, one and only one of these is required:" op.on("-h", "--help") do @parsed_options.show_help = true end op.on("-a", "--add ACCOUNT", "Create a new account in keybox") do |account| @actions << [:add, account] end op.on("-d", "--delete ACCOUNT", "Delete the account from keybox") do |account| @actions << [:delete, account] end op.on("-e", "--edit ACCOUNT", "Edit the account in keybox") do |account| @actions << [:edit, account] end op.on("-l", "--list [REGEX]", "List the matching accounts", " (no argument will list all)") do |regex| regex = regex || ".*" @actions << [:list, regex] end op.on("-m", "--master-password", "Change the master password") do @actions << [:master_password, nil] end op.on("-s", "--show [REGEX]", "Show the given account(s)") do |regex| regex = regex || ".*" @actions << [:show, regex] end op.on("-v", "--version", "Show version information") do @parsed_options.show_version = true end op.separator "" op.separator "Import / Export from other data formats:" op.on("-i", "--import-from-csv FILE", "Import from a CSV file") do |file| @actions << [:import_from_csv, file] end op.on("-x", "--export-to-csv FILE", "Export contents to a CSV file") do |file| @actions << [:export_to_csv, file] end end end |
#run ⇒ Object
456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 |
# File 'lib/keybox/application/password_safe.rb', line 456 def run begin error_version_help load_color_scheme load_database if @actions.size == 0 then @actions << [:list, ".*"] end action, param = *@actions.shift self.send(action, param) if @db.modified? then hsay "Database modified, saving.", :information @db.save else hsay "Database not modified.", :information end rescue SignalException => se @stdout.puts hsay "Interrupted", :error hsay "There may be private information on your screen.", :error hsay "Please close this terminal.", :error exit 1 rescue StandardError => e hsay "Error: #{e.}", :error exit 1 end end |
#show(account) ⇒ Object
output all the information for the accounts matching
365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 |
# File 'lib/keybox/application/password_safe.rb', line 365 def show(account) matches = @db.find(account) if matches.size > 0 then matches.each_with_index do |match,i| hsay "#{sprintf("%3d",i + 1)}. #{match.title}", :header max_name_length = match.max_field_length + 1 match.each do |name,value| next if name == "title" next if value.length == 0 name_out = name.rjust(max_name_length) @highline.say("<%= color('#{name_out}', :name) %> <%= color(':',:separator) %> ") if match.private_field?(name) then @highline.ask( "<%= color('#{value}',:private) %> <%= color('(press any key).', :prompt) %> " ) do |q| q.overwrite = true q.echo = false q.character = true end @highline.say("<%= color('#{name_out}', :name) %> <%= color(':',:separator) %> <%= color('#{'*' * 20}', :private) %>") else hsay value, :value end end @stdout.puts end else hsay "No matching records were found.", :information end end |