Class: Morpheus::Cli::Credentials

Inherits:
Object
  • Object
show all
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

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_percent, #format_rate, #format_results_pagination, #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_to_file, #quote_csv_value, #records_as_csv, #required_blue_prompt, #sleep_with_dots, terminal_width, terminal_width=, #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



354
355
356
357
358
359
360
361
362
# File 'lib/morpheus/cli/credentials.rb', line 354

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_pathObject



387
388
389
# File 'lib/morpheus/cli/credentials.rb', line 387

def credentials_file_path
  File.join(Morpheus::Cli.home_directory, "credentials")
end

#load_credentials_fileObject



377
378
379
380
381
382
383
384
385
# File 'lib/morpheus/cli/credentials.rb', line 377

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



364
365
366
367
368
369
370
371
372
373
374
375
# File 'lib/morpheus/cli/credentials.rb', line 364

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



240
241
242
# File 'lib/morpheus/cli/credentials.rb', line 240

def (options = {}, do_save=true)
  request_credentials(options, do_save)
end

#logoutObject



244
245
246
247
248
249
250
251
252
253
254
255
256
# File 'lib/morpheus/cli/credentials.rb', line 244

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



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
455
456
457
458
459
460
461
# File 'lib/morpheus/cli/credentials.rb', line 426

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.exists?(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.

Parameters:

  • options (defaults to: {})
    • Hash of optional settings.

    :username - Username for prompt. :password - Password for prompt. :remote_url - Use this url instead of the one from the current appliance. Credentials will not be saved. :remote_token - Use this access_token, skip prompting and API request. :remote_username - Username for authentication with –remote, skips saving credentials :remote_password - Password for authentication with –remote, skips saving credentials :test_only - Test only. Saved credentials will not be updated.

Returns:

  • Hash wallet like “refresh_token”:“ec68be138765…”



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
# File 'lib/morpheus/cli/credentials.rb', line 37

def request_credentials(options = {}, do_save=true)
  #puts "request_credentials(#{options})"
  username = nil
  password = nil
  wallet = nil

  # should not need this logic in here
  if options[: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 options[: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
      # @setup_interface = Morpheus::SetupInterface.new({url:@appliance_url,access_token:@access_token})
      whoami_interface = Morpheus::WhoamiInterface.new({url: @appliance_url, access_token: options[:remote_token]})
      whoami_interface.setopts(options)
      if options[:dry_run]
        print_dry_run whoami_interface.dry.get()
        return nil
      end
      whoami_response = whoami_interface.get()
      if options[:json]
        puts as_json(whoami_response, options)
        print reset, "\n"
      end
      # store mock /oauth/token  auth_interface.login() result
      json_response = {'access_token' => options[:remote_token], 'token_type' => 'bearer'}
      username = whoami_response['user']['username']
       = Time.now
      expire_date = nil
      if json_response['expires_in']
        expire_date = .to_i + json_response['expires_in'].to_i
      end
      wallet = {
        'username' => username, 
        '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 options[:debug]
        print_rest_exception(e, options)
      end
      wallet = nil
    end
  else
    # ok prompt for creds..
    username = options['username'] || options[:username] || nil
    password = options['password'] || options[:password] || nil
    
    # what are these for? just use :username and :password
    if options[:remote_username]
      username = options[:remote_username]
      password = options[:remote_password]
    end
    if wallet.nil?
      unless options[:quiet] || options[:no_prompt]
        # if username.empty? || password.empty?
          if options[:test_only]
            print "Test Morpheus Credentials for #{display_appliance(@appliance_name, @appliance_url)}", "\n", reset
          else
            print "Enter Morpheus Credentials for #{display_appliance(@appliance_name, @appliance_url)}", "\n", reset
          end
        # end
        if options[:client_id].empty?
          # print "Client ID: #{required_blue_prompt} #{options[:client_id]}", "\n", reset
        else
          if options[:client_id] != Morpheus::APIClient::CLIENT_ID
            print "Client ID: #{required_blue_prompt} #{options[:client_id]}", "\n", reset
          end
        end
        if username.empty?
          print "Username: #{required_blue_prompt} "
          username = $stdin.gets.chomp!
        else
          print "Username: #{required_blue_prompt} #{username}\n"
        end
        if password.empty?
          print "Password: #{required_blue_prompt} "
          # this should be my_terminal.stdin instead of STDIN and $stdin
          password = STDIN.noecho(&:gets).chomp!
          print "\n"
        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: options[:client_id]})
        auth_interface.setopts(options)
        if options[:dry_run]
          print_dry_run auth_interface.dry.(username, password)
          return nil
        end
        json_response = auth_interface.(username, password)
        if options[:json]
          print JSON.pretty_generate(json_response)
          print reset, "\n"
        end
        #wallet = json_response
         = Time.now
        expire_date = nil
        if json_response['expires_in']
          expire_date = .to_i + json_response['expires_in'].to_i
        end
        wallet = {
          'username' => username, 
          '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 options[:json]
            json_response = JSON.parse(e.response.to_s)
            print JSON.pretty_generate(json_response)
            print reset, "\n"
          end
        else
          print_rest_exception(e, options)
        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.message}"
    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…’



392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
# File 'lib/morpheus/cli/credentials.rb', line 392

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.exists?(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



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
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
# File 'lib/morpheus/cli/credentials.rb', line 258

def use_refresh_token(refresh_token_value, options = {})
  
  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})
    auth_interface.setopts(options)
    if options[: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
     = Time.now
    expire_date = nil
    if json_response['expires_in']
      expire_date = .to_i + json_response['expires_in'].to_i
    end
    wallet = {
      'username' => username, 
      '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 options[:json]
        json_response = JSON.parse(e.response.to_s)
        print JSON.pretty_generate(json_response)
        print reset, "\n"
      end
    else
      print_rest_exception(e, options)
    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.message}"
  end
  
  
  return wallet
end