Class: Morpheus::Cli::Credentials
- Inherits:
-
Object
- Object
- Morpheus::Cli::Credentials
- Includes:
- PrintHelper
- Defined in:
- lib/morpheus/cli/credentials.rb
Constant Summary collapse
- @@appliance_credentials_map =
nil
Constants included from PrintHelper
PrintHelper::ALL_LABELS_UPCASE
Instance Method Summary collapse
- #clear_saved_credentials(appliance_name) ⇒ Object
- #credentials_file_path ⇒ Object
-
#initialize(appliance_name, appliance_url) ⇒ Credentials
constructor
A new instance of Credentials.
- #load_credentials_file ⇒ Object
- #load_saved_credentials(reload = false) ⇒ Object
- #login(options = {}, do_save = true) ⇒ Object
- #logout ⇒ Object
- #rename_credentials(appliance_name, new_appliance_name) ⇒ Object
-
#request_credentials(options = {}, do_save = true) ⇒ Object
request_credentials will fetch a credentials wallet (access_token, refresh_token, etc) By default this uses the saved credentials for the current appliance.
-
#save_credentials(appliance_name, wallet) ⇒ Object
credentials wallet is ‘…’, ‘refresh_token’: ‘…’ ‘expiration’: ‘2019-01-01…’.
- #use_refresh_token(refresh_token_value, options = {}) ⇒ Object
Methods included from PrintHelper
#as_csv, #as_description_list, #as_json, #as_pretty_table, #as_yaml, #build_column_definitions, #current_terminal_width, #format_api_request, #format_available_options, #format_boolean, #format_curl_command, #format_dt_dd, #format_option_types_table, #format_percent, #format_rate, #format_results_pagination, #format_simple_option_types_table, #format_table_cell, #generate_usage_bar, included, #justify_string, #parse_json_or_yaml, #parse_rest_exception, #parse_yaml_or_json, #print_description_list, #print_dry_run, #print_green_success, #print_h1, #print_h2, #print_red_alert, #print_rest_errors, #print_rest_exception, #print_results_pagination, #print_stats_usage, #print_system_command_dry_run, #print_to_file, #quote_csv_value, #records_as_csv, #required_blue_prompt, #sleep_with_dots, terminal_width, terminal_width=, #transform_data_for_field_options, #truncate_string, #truncate_string_right, #with_stdout_to_file, #wrap
Constructor Details
#initialize(appliance_name, appliance_url) ⇒ Credentials
Returns a new instance of Credentials.
16 17 18 19 |
# File 'lib/morpheus/cli/credentials.rb', line 16 def initialize(appliance_name, appliance_url) @appliance_name = appliance_name ? appliance_name.to_sym : nil @appliance_url = appliance_url end |
Instance Method Details
#clear_saved_credentials(appliance_name) ⇒ Object
370 371 372 373 374 375 376 377 378 |
# File 'lib/morpheus/cli/credentials.rb', line 370 def clear_saved_credentials(appliance_name) @@appliance_credentials_map = load_credentials_file || {} @@appliance_credentials_map.delete(appliance_name.to_s) @@appliance_credentials_map.delete(appliance_name.to_sym) #Morpheus::Logging::DarkPrinter.puts "clearing credentials for #{appliance_name} from file #{credentials_file_path}" if Morpheus::Logging.debug? File.open(credentials_file_path, 'w') {|f| f.write @@appliance_credentials_map.to_yaml } #Store ::Morpheus::Cli::Remote.recalculate_variable_map() true end |
#credentials_file_path ⇒ Object
403 404 405 |
# File 'lib/morpheus/cli/credentials.rb', line 403 def credentials_file_path File.join(Morpheus::Cli.home_directory, "credentials") end |
#load_credentials_file ⇒ Object
393 394 395 396 397 398 399 400 401 |
# File 'lib/morpheus/cli/credentials.rb', line 393 def load_credentials_file fn = credentials_file_path if File.exist? fn #Morpheus::Logging::DarkPrinter.puts "loading credentials file #{fn}" if Morpheus::Logging.debug? return YAML.load_file(fn) else return nil end end |
#load_saved_credentials(reload = false) ⇒ Object
380 381 382 383 384 385 386 387 388 389 390 391 |
# File 'lib/morpheus/cli/credentials.rb', line 380 def load_saved_credentials(reload=false) if reload || !defined?(@@appliance_credentials_map) || @@appliance_credentials_map.nil? @@appliance_credentials_map = load_credentials_file || {} end # ok, we switched symbols to strings, because symbols suck in yaml! need to support both # also we switched from just a token (symbol) to a whole object of strings wallet = @@appliance_credentials_map[@appliance_name.to_s] || @@appliance_credentials_map[@appliance_name.to_sym] if wallet.is_a?(String) wallet = {'access_token' => wallet} end return wallet end |
#login(options = {}, do_save = true) ⇒ Object
256 257 258 |
# File 'lib/morpheus/cli/credentials.rb', line 256 def login( = {}, do_save=true) request_credentials(, do_save) end |
#logout ⇒ Object
260 261 262 263 264 265 266 267 268 269 270 271 272 |
# File 'lib/morpheus/cli/credentials.rb', line 260 def logout() clear_saved_credentials(@appliance_name) # save pertinent session info to the appliance appliance = ::Morpheus::Cli::Remote.load_remote(@appliance_name) if appliance appliance.delete(:username) # could leave this... appliance[:authenticated] = false appliance[:last_logout_at] = Time.now.to_i ::Morpheus::Cli::Remote.save_remote(@appliance_name, appliance) end ::Morpheus::Cli::Remote.recalculate_variable_map() true end |
#rename_credentials(appliance_name, new_appliance_name) ⇒ Object
442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 |
# File 'lib/morpheus/cli/credentials.rb', line 442 def rename_credentials(appliance_name, new_appliance_name) # reloading file is better for now, otherwise you can lose credentials with multiple shells. credential_map = load_credentials_file || {} if new_appliance_name.to_s.empty? puts "Cannot rename credentials without specifying a new name" return nil elsif credential_map[new_appliance_name.to_s] || credential_map[new_appliance_name.to_sym] # yes you can, maybe require --force? puts "Cannot rename credentials to a name that already exists: #{new_appliance_name}" return nil end # always remove symbol, which was used pre 3.6.9 credential_map.delete(appliance_name.to_sym) begin fn = credentials_file_path if !Dir.exist?(File.dirname(fn)) FileUtils.mkdir_p(File.dirname(fn)) end #Morpheus::Logging::DarkPrinter.puts "renaming credentials from #{appliance_name} to #{new_appliance_name}" if Morpheus::Logging.debug? File.open(fn, 'w') {|f| f.write credential_map.to_yaml } #Store FileUtils.chmod(0600, fn) @@appliance_credentials_map = credential_map rescue => e puts "failed to save #{fn}. #{e}" if Morpheus::Logging.debug? ensure # recalcuate echo vars #puts "Recalculating variable maps for username change" Morpheus::Cli::Echo.recalculate_variable_map() # recalculate shell prompt after this change if Morpheus::Cli::Shell.has_instance? Morpheus::Cli::Shell.instance.reinitialize() end end end |
#request_credentials(options = {}, do_save = true) ⇒ Object
request_credentials will fetch a credentials wallet (access_token, refresh_token, etc) By default this uses the saved credentials for the current appliance. If not logged in, it will prompt for username and password to authenticate with the /oauth/token API to receive an access_token. If :username and :password are passed, then Pass :remote_token to skip prompting and the auth api request. or nil if unable to find credentials.
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 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 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 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 |
# File 'lib/morpheus/cli/credentials.rb', line 37 def request_credentials( = {}, do_save=true) #puts "request_credentials(#{options})" username = nil password = nil wallet = nil # should not need this logic in here if [:remote_url] # @appliance_name = options[:remote_url] # name should change too though or printing may be misleading. # @appliance_name = "remote-url" # @appliance_url = options[:remote_url] # do not save when using --remote-url do_save = false end if [:remote_token] # user passed in a token to login with. # this should get token info from /oauth/token # OR whoami should return other wallet info like access token or maybe just the expiration date # for now, it just stores the access token without other wallet info begin whoami_interface = Morpheus::WhoamiInterface.new({url: @appliance_url, access_token: [:remote_token], verify_ssl: ![:insecure]}) whoami_interface.setopts() if [:dry_run] print_dry_run whoami_interface.dry.get() return nil end whoami_response = whoami_interface.get() if [:json] puts as_json(whoami_response, ) print reset, "\n" end # store mock /oauth/token auth_interface.login() result json_response = {'access_token' => [:remote_token], 'token_type' => 'bearer'} username = whoami_response['user']['username'] login_date = Time.now expire_date = nil if json_response['expires_in'] expire_date = login_date.to_i + json_response['expires_in'].to_i end wallet = { 'username' => username, 'login_date' => login_date.to_i, 'expire_date' => expire_date ? expire_date.to_i : nil, 'access_token' => json_response['access_token'], 'refresh_token' => json_response['refresh_token'], 'token_type' => json_response['token_type'] } rescue ::RestClient::Exception => e #raise e print_red_alert "Token not valid." if [:debug] print_rest_exception(e, ) end wallet = nil end else # ok prompt for creds.. username = ['username'] || [:username] || nil password = ['password'] || [:password] || nil # what are these for? just use :username and :password if [:remote_username] username = [:remote_username] password = [:remote_password] end if wallet.nil? unless [:quiet] || [:no_prompt] print "Enter Morpheus Credentials for #{display_appliance(@appliance_name, @appliance_url)}", "\n", reset if [:client_id].empty? # print "Client ID: #{required_blue_prompt} #{options[:client_id]}", "\n", reset else if [:client_id] != Morpheus::APIClient::CLIENT_ID print "Client ID: #{required_blue_prompt} #{[:client_id]}", "\n", reset end end if username.empty? # print "Username: #{required_blue_prompt} " # username = $stdin.gets.chomp! Readline.completion_append_character = "" Readline.basic_word_break_characters = '' Readline.completion_proc = nil username = Readline.readline("Username: #{required_blue_prompt} ", false).to_s.chomp else print "Username: #{required_blue_prompt} #{username}\n" end if password.empty? # readline is still echoing secret with 'NUL:'' so just use $stdin on windows for now # and some other environments? just use noecho unless running unit tests if Morpheus::Cli.windows? || !Morpheus::Cli.testing? print "Password: #{required_blue_prompt} " # this should be my_terminal.stdin instead of STDIN and $stdin password = $stdin.noecho(&:gets).chomp! print "\n" else Readline.completion_append_character = "" Readline.basic_word_break_characters = '' Readline.completion_proc = nil # needs to work like $stdin.noecho Readline.pre_input_hook = lambda { Readline.output = File.open('/dev/null', 'w') #Readline.output = File.open(Morpheus::Cli.windows? ? 'NUL:' : '/dev/null', 'w') #$stdout = File.open(Morpheus::Cli.windows? ? 'NUL:' : '/dev/null', 'w') } password = Readline.readline("Password: #{required_blue_prompt} ", false).to_s.chomp Readline.pre_input_hook = nil Readline.output = Morpheus::Terminal.instance.stdout #my_terminal.stdout print "\n" end else print "Password: #{required_blue_prompt} \n" end end if username.empty? || password.empty? print_red_alert "Username and password are required to login." return nil end begin auth_interface = Morpheus::AuthInterface.new({url:@appliance_url, client_id: [:client_id], verify_ssl: ![:insecure]}) auth_interface.setopts() if [:dry_run] print_dry_run auth_interface.dry.login(username, password) return nil end json_response = auth_interface.login(username, password) if [:json] print JSON.pretty_generate(json_response) print reset, "\n" end #wallet = json_response login_date = Time.now expire_date = nil if json_response['expires_in'] expire_date = login_date.to_i + json_response['expires_in'].to_i end wallet = { 'username' => username, 'login_date' => login_date.to_i, 'expire_date' => expire_date ? expire_date.to_i : nil, 'access_token' => json_response['access_token'], 'refresh_token' => json_response['refresh_token'], 'token_type' => json_response['token_type'] } rescue ::RestClient::Exception => e #raise e if (e.response && e.response.code == 400) json_response = JSON.parse(e.response.to_s) error_msg = json_response['error_description'] || "Credentials not verified." print_red_alert error_msg if [:json] json_response = JSON.parse(e.response.to_s) print JSON.pretty_generate(json_response) print reset, "\n" end else print_rest_exception(e, ) end wallet = nil end end end if do_save && @appliance_name begin # save pertinent session info to the appliance save_credentials(@appliance_name, wallet) now = Time.now.to_i appliance = ::Morpheus::Cli::Remote.load_remote(@appliance_name) if wallet && wallet['access_token'] save_credentials(@appliance_name, wallet) else clear_saved_credentials(@appliance_name) end if appliance if wallet && wallet['access_token'] # save wallet to credentials file save_credentials(@appliance_name, wallet) # save appliances file appliance = ::Morpheus::Cli::Remote.load_remote(@appliance_name) appliance[:authenticated] = true appliance[:username] = username appliance[:status] = "ready" appliance[:last_login_at] = now appliance[:last_success_at] = now ::Morpheus::Cli::Remote.save_remote(@appliance_name, appliance) else # could be nice and not do this #logout() #save wallet to credentials file clear_saved_credentials(@appliance_name) now = Time.now.to_i appliance = ::Morpheus::Cli::Remote.load_remote(@appliance_name) appliance[:authenticated] = false old_username = appliance.delete(:username) appliance[:last_logout_at] = Time.now.to_i #appliance[:last_login_at] = now #appliance[:error] = "Credentials not verified" appliance.delete(:username) ::Morpheus::Cli::Remote.save_remote(@appliance_name, appliance) if old_username print reset,"You have been automatically logged out. Goodbye #{old_username}!", reset, "\n" end end end rescue => e Morpheus::Logging::DarkPrinter.puts "failed to update remote appliance config: (#{e.class}) #{e.}" ensure #::Morpheus::Cli::Remote.recalculate_variable_map() end end return wallet end |
#save_credentials(appliance_name, wallet) ⇒ Object
credentials wallet is ‘…’, ‘refresh_token’: ‘…’ ‘expiration’: ‘2019-01-01…’
408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 |
# File 'lib/morpheus/cli/credentials.rb', line 408 def save_credentials(appliance_name, wallet) # reloading file is better for now, otherwise you can lose credentials with multiple shells. credential_map = load_credentials_file || {} if wallet credential_map[appliance_name.to_s] = wallet else # nil mean remove the damn thing credential_map.delete(appliance_name.to_s) end # always remove symbol, which was used pre 3.6.9 credential_map.delete(appliance_name.to_sym) begin fn = credentials_file_path if !Dir.exist?(File.dirname(fn)) FileUtils.mkdir_p(File.dirname(fn)) end #Morpheus::Logging::DarkPrinter.puts "adding credentials for #{appliance_name} to #{fn}" if Morpheus::Logging.debug? File.open(fn, 'w') {|f| f.write credential_map.to_yaml } #Store FileUtils.chmod(0600, fn) @@appliance_credentials_map = credential_map rescue => e puts "failed to save #{fn}. #{e}" if Morpheus::Logging.debug? ensure # recalcuate echo vars #puts "Recalculating variable maps for username change" Morpheus::Cli::Echo.recalculate_variable_map() # recalculate shell prompt after this change if Morpheus::Cli::Shell.has_instance? Morpheus::Cli::Shell.instance.reinitialize() end end end |
#use_refresh_token(refresh_token_value, options = {}) ⇒ Object
274 275 276 277 278 279 280 281 282 283 284 285 286 287 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 319 320 321 322 323 324 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 361 362 363 364 365 366 367 368 |
# File 'lib/morpheus/cli/credentials.rb', line 274 def use_refresh_token(refresh_token_value, = {}) wallet = load_saved_credentials if wallet.nil? print_red_alert yellow,"You are not currently logged in to #{display_appliance(@appliance_name, @appliance_url)}",reset,"\n" return nil end if refresh_token_value.nil? if wallet['refresh_token'] refresh_token_value = wallet['refresh_token'] else print_red_alert yellow,"No refresh token found for #{display_appliance(@appliance_name, @appliance_url)}",reset,"\n" return nil end end username = wallet['username'] begin auth_interface = Morpheus::AuthInterface.new({url:@appliance_url, client_id: [:client_id], verify_ssl: ![:insecure]}) auth_interface.setopts() if [:dry_run] print_dry_run auth_interface.dry.use_refresh_token(refresh_token_value) return nil end json_response = auth_interface.use_refresh_token(refresh_token_value) #wallet = json_response login_date = Time.now expire_date = nil if json_response['expires_in'] expire_date = login_date.to_i + json_response['expires_in'].to_i end wallet = { 'username' => username, 'login_date' => login_date.to_i, 'expire_date' => expire_date ? expire_date.to_i : nil, 'access_token' => json_response['access_token'], 'refresh_token' => json_response['refresh_token'], 'token_type' => json_response['token_type'] } rescue ::RestClient::Exception => e #raise e if (e.response && e.response.code == 400) json_response = JSON.parse(e.response.to_s) error_msg = json_response['error_description'] || "Refresh token not valid." print_red_alert error_msg if [:json] json_response = JSON.parse(e.response.to_s) print JSON.pretty_generate(json_response) print reset, "\n" end else print_rest_exception(e, ) end wallet = nil # return now or else it will log them out return nil end # save wallet to credentials file save_credentials(@appliance_name, wallet) begin # save pertinent session info to the appliance now = Time.now.to_i appliance = ::Morpheus::Cli::Remote.load_remote(@appliance_name) if appliance if wallet && wallet['access_token'] appliance = ::Morpheus::Cli::Remote.load_remote(@appliance_name) appliance[:authenticated] = true appliance[:username] = username appliance[:status] = "ready" appliance[:last_login_at] = now appliance[:last_success_at] = now ::Morpheus::Cli::Remote.save_remote(@appliance_name, appliance) else now = Time.now.to_i appliance = ::Morpheus::Cli::Remote.load_remote(@appliance_name) appliance[:authenticated] = false #appliance[:username] = username #appliance[:last_login_at] = now #appliance[:error] = "Credentials not verified" ::Morpheus::Cli::Remote.save_remote(@appliance_name, appliance) end end rescue => e Morpheus::Logging::DarkPrinter.puts "failed to update remote appliance config: (#{e.class}) #{e.}" end return wallet end |