Class: Keybox::Application::PasswordSafe
- Includes:
- TermIO
- 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")
- ACTION_LIST =
%w(add delete edit show list master-password)
Constants included from TermIO
TermIO::BOLD_ON, TermIO::COLORS, TermIO::EOL_CHARS, TermIO::ESCAPE, TermIO::FG_BLACK, TermIO::FG_BLUE, TermIO::FG_CYAN, TermIO::FG_GREEN, TermIO::FG_MAGENTA, TermIO::FG_RED, TermIO::FG_WHITE, TermIO::FG_YELLOW, TermIO::RESET, TermIO::STTY, TermIO::STTY_RAW_CMD, TermIO::STTY_SAVE_CMD, TermIO::VALID_COLORS
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, #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_database ⇒ Object
-
#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 TermIO
#color_print, #color_puts, #colorize, #colorize_if_io_isatty, #get_one_char, #has_stty?, #prompt, #prompt_and_return, #prompt_y_n
Methods inherited from Base
#error_version_help, #merge_options
Constructor Details
#initialize(argv = []) ⇒ PasswordSafe
Returns a new instance of PasswordSafe.
25 26 27 28 29 30 31 32 33 34 35 |
# File 'lib/keybox/application/password_safe.rb', line 25 def initialize(argv = []) @actions = Array.new super(argv) # only one of the actions is allowed if actions.size > 1 then = [ "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
159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 |
# File 'lib/keybox/application/password_safe.rb', line 159 def add(account) entry = Keybox::HostAccountEntry.new(account, account) if .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) color_puts "Adding #{new_entry.title} to database", :green @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
128 129 130 131 132 133 134 135 136 137 138 139 140 141 |
# File 'lib/keybox/application/password_safe.rb', line 128 def file_path = .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
111 112 113 114 115 116 117 118 119 120 |
# File 'lib/keybox/application/password_safe.rb', line 111 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 return end |
#delete(account) ⇒ Object
delete an entry from the database
205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 |
# File 'lib/keybox/application/password_safe.rb', line 205 def delete(account) matches = @db.find(account) count = 0 matches.each do |match| color_puts "-" * 40, :blue @stdout.puts match color_puts "-" * 40, :blue if prompt_y_n("Delete this entry (y/n) [N] ?") then @db.delete(match) count += 1 end end color_puts "#{count} records matching '#{account}' deleted.", :green end |
#edit(account) ⇒ Object
edit an entry in the database
224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 |
# File 'lib/keybox/application/password_safe.rb', line 224 def edit(account) matches = @db.find(account) count = 0 matches.each do |match| color_puts "-" * 40, :blue @stdout.puts match color_puts "-" * 40, :blue if prompt_y_n("Edit this entry (y/n) [N] ?") then entry = gather_info(match) @db.delete(match) @db << entry count += 1 color_puts "Entry '#{entry.title}' updated.", :green end end color_puts "#{count} records matching '#{account}' edited.", :green end |
#export_to_csv(file) ⇒ Object
Export data from the database into a CSV file
342 343 344 345 |
# File 'lib/keybox/application/password_safe.rb', line 342 def export_to_csv(file) Keybox::Convert::CSV.to_file(@db.records, file) color_puts "Exported #{@db.records.size} records to #{file}.", :green end |
#fill_entry(entry) ⇒ Object
347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 |
# File 'lib/keybox/application/password_safe.rb', line 347 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 = false validate = true p = "#{field}" end value = prompt(p,echo,validate,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
181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 |
# File 'lib/keybox/application/password_safe.rb', line 181 def gather_info(entry) gathered = false while not gathered do color_puts "Gathering information for entry '#{entry.title}'", :yellow entry = fill_entry(entry) # dump the info we have gathered and make sure that # it is the input that the user wants to store. color_puts "-" * 40, :blue @stdout.puts entry color_puts "-" * 40, :blue if prompt_y_n("Is this information correct (y/n) [N] ?") then gathered = true end end entry end |
#import_from_csv(file) ⇒ Object
Import data into the database from a CSV file
332 333 334 335 336 337 338 |
# File 'lib/keybox/application/password_safe.rb', line 332 def import_from_csv(file) entries = Keybox::Convert::CSV.from_file(file) entries.each do |entry| @db << entry end color_puts "Imported #{entries.size} records from #{file}.", :green 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
249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 |
# File 'lib/keybox/application/password_safe.rb', line 249 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}" color_puts header, :yellow # 3 spaces for number column + 1 space after and 4 spaces between # each other column color_puts "-" * (header.length), :blue, false matches.each_with_index do |match,i| color_print sprintf("%3d ", i + 1), :white # toggle colors color = [:cyan, :magenta][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 color_puts columns.join(" " * 4), color end else color_puts "No matching records were found.", :green end end |
#load_database ⇒ Object
143 144 145 146 147 148 149 150 151 152 |
# File 'lib/keybox/application/password_safe.rb', line 143 def load_database password = nil if not File.exists?(.db_file) then color_puts "Creating initial database.", :yellow password = prompt("Initial Password for (#{@options.db_file})", false, true) else password = prompt("Password for (#{@options.db_file})", false) end @db = Keybox::Storage::Container.new(password,.db_file) end |
#master_password(ignore_this) ⇒ Object
Change the master password on the database
323 324 325 326 327 |
# File 'lib/keybox/application/password_safe.rb', line 323 def master_password(ignore_this) new_password = prompt("Enter new master password", false, true, 30) @db.passphrase = new_password color_puts "New master password set.", :green end |
#option_parser ⇒ Object
37 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 |
# File 'lib/keybox/application/password_safe.rb', line 37 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| .db_file = db_file end op.on("-c", "--config CONFIG_FILE", "The Configuration file to use") do |cfile| .config_file = cfile end op.on("-D", "--debug", "Ouput debug information to STDERR") do .debug = true end op.on("--[no-]use-hash-for-url", "Use the password hash algorithm ", " for URL accounts") do |r| .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 .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 .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
378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 |
# File 'lib/keybox/application/password_safe.rb', line 378 def run begin error_version_help load_database if @actions.size == 0 then @actions << [:list, ".*"] end action, param = *@actions.shift self.send(action, param) if @db.modified? then color_puts "Database modified, saving.", :green @db.save else color_puts "Database not modified.", :green end rescue SignalException => se @stdout.puts color_puts "Interrupted", :red color_puts "There may be private information on your screen.", :red color_puts "Please close this terminal.", :red exit 1 rescue StandardError => e @stdout.puts color_puts "Error: #{e.message}", :red exit 1 end end |
#show(account) ⇒ Object
output all the information for the accounts matching
288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 |
# File 'lib/keybox/application/password_safe.rb', line 288 def show(account) matches = @db.find(account) if matches.size > 0 then matches.each_with_index do |match,i| color_puts "#{sprintf("%3d",i + 1)}. #{match.title}", :yellow 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) color_print name_out, :blue color_print " : ", :white if match.private_field?(name) then color_print value, :red color_print " (press any key).", :white junk = get_one_char color_print "\r#{name_out}", :blue color_print " : ", :white color_puts "#{"*" * 20}\e[K", :red else color_puts value, :cyan end end @stdout.puts end else color_puts "No matching records were found.", :green end end |