Class: Morpheus::Cli::Credentials
- Inherits:
-
Object
- Object
- Morpheus::Cli::Credentials
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
#as_csv, #as_description_list, #as_details, #as_json, #as_pretty_details, #as_pretty_table, #as_yaml, #build_column_definitions, #current_terminal_width, #format_abbreviated_value, #format_api_request, #format_available_options, #format_boolean, #format_curl_command, #format_detail_value, #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_details, #print_dry_run, #print_green_success, #print_h1, #print_h2, #print_pretty_details, #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)
File.open(credentials_file_path, 'w') {|f| f.write @@appliance_credentials_map.to_yaml } ::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
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
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(options = {}, do_save=true)
request_credentials(options, do_save)
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)
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]
puts "Cannot rename credentials to a name that already exists: #{new_appliance_name}"
return nil
end
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
File.open(fn, 'w') {|f| f.write credential_map.to_yaml } FileUtils.chmod(0600, fn)
@@appliance_credentials_map = credential_map
rescue => e
puts "failed to save #{fn}. #{e}" if Morpheus::Logging.debug?
ensure
Morpheus::Cli::Echo.recalculate_variable_map()
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(options = {}, do_save=true)
username = nil
password = nil
wallet = nil
if options[:remote_url]
do_save = false
end
if options[:remote_token]
begin
whoami_interface = Morpheus::WhoamiInterface.new({url: @appliance_url, access_token: options[:remote_token], verify_ssl: !options[:insecure]})
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
json_response = {'access_token' => options[: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
print_red_alert "Token not valid."
if options[:debug]
print_rest_exception(e, options)
end
wallet = nil
end
else
username = options['username'] || options[:username] || nil
password = options['password'] || options[:password] || nil
if options[:remote_username]
username = options[:remote_username]
password = options[:remote_password]
end
if wallet.nil?
unless options[:quiet] || options[:no_prompt]
print "Enter Morpheus Credentials for #{display_appliance(@appliance_name, @appliance_url)}", "\n", reset
if options[:client_id].empty?
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?
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?
if Morpheus::Cli.windows? || !Morpheus::Cli.testing?
print "Password: #{required_blue_prompt} "
password = $stdin.noecho(&:gets).chomp!
print "\n"
else
Readline.completion_append_character = ""
Readline.basic_word_break_characters = ''
Readline.completion_proc = nil
Readline.pre_input_hook = lambda {
Readline.output = File.open('/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 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: options[:client_id], verify_ssl: !options[:insecure]})
auth_interface.setopts(options)
if options[:dry_run]
print_dry_run auth_interface.dry.login(username, password)
return nil
end
json_response = auth_interface.login(username, password)
if options[:json]
print JSON.pretty_generate(json_response)
print reset, "\n"
end
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
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_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_credentials(@appliance_name, wallet)
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
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.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
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)
credential_map = load_credentials_file || {}
if wallet
credential_map[appliance_name.to_s] = wallet
else
credential_map.delete(appliance_name.to_s)
end
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
File.open(fn, 'w') {|f| f.write credential_map.to_yaml } FileUtils.chmod(0600, fn)
@@appliance_credentials_map = credential_map
rescue => e
puts "failed to save #{fn}. #{e}" if Morpheus::Logging.debug?
ensure
Morpheus::Cli::Echo.recalculate_variable_map()
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, 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, client_id: options[:client_id], verify_ssl: !options[:insecure]})
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)
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
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 nil
end
save_credentials(@appliance_name, wallet)
begin
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
::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
|