Class: Morpheus::Cli::UserSourcesCommand

Inherits:
Object
  • Object
show all
Includes:
AccountsHelper, CliCommand
Defined in:
lib/morpheus/cli/user_sources_command.rb

Instance Attribute Summary

Attributes included from CliCommand

#no_prompt

Instance Method Summary collapse

Methods included from AccountsHelper

#account_column_definitions, #accounts_interface, #find_account_by_id, #find_account_by_name, #find_account_by_name_or_id, #find_account_from_options, #find_all_user_ids, #find_role_by_id, #find_role_by_name, #find_role_by_name_or_id, #find_user_by_id, #find_user_by_username, #find_user_by_username_or_id, #find_user_group_by_id, #find_user_group_by_name, #find_user_group_by_name_or_id, #format_access_string, #format_role_type, #format_user_role_names, #format_user_status, #get_access_color, #get_access_string, included, #list_account_column_definitions, #list_user_column_definitions, #list_user_group_column_definitions, #role_column_definitions, #roles_interface, #subtenant_role_column_definitions, #user_column_definitions, #user_group_column_definitions, #user_groups_interface, #users_interface

Methods included from CliCommand

#apply_options, #build_common_options, #build_option_type_options, #build_standard_add_options, #build_standard_delete_options, #build_standard_get_options, #build_standard_list_options, #build_standard_post_options, #build_standard_put_options, #build_standard_remove_options, #build_standard_update_options, #command_description, #command_name, #default_refresh_interval, #default_sigdig, #default_subcommand, #establish_remote_appliance_connection, #full_command_usage, #get_subcommand_description, #handle_subcommand, included, #interactive?, #my_help_command, #my_terminal, #my_terminal=, #parse_bytes_param, #parse_id_list, #parse_list_options, #parse_list_subtitles, #parse_passed_options, #parse_payload, #parse_query_options, #print, #print_error, #println, #prog_name, #puts, #puts_error, #raise_args_error, #raise_command_error, #render_response, #run_command_for_each_arg, #subcommand_aliases, #subcommand_description, #subcommand_usage, #subcommands, #usage, #validate_outfile, #verify_args!, #visible_subcommands

Constructor Details

#initializeUserSourcesCommand

Returns a new instance of UserSourcesCommand.



17
18
19
# File 'lib/morpheus/cli/user_sources_command.rb', line 17

def initialize()
  # @appliance_name, @appliance_url = Morpheus::Cli::Remote.active_appliance
end

Instance Method Details

#_get(user_source_id, params, options) ⇒ Object



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

def _get(user_source_id, params, options)
   = nil
   = nil
  # account_id = args[0]
  # account = find_account_by_name_or_id(account_id)
  # exit 1 if account.nil?
  # account_id = account['id']
  # user_source_id = args[1]
  
  @user_sources_interface.setopts(options)
  if options[:dry_run]
    if user_source_id.to_s =~ /\A\d{1,}\Z/
      print_dry_run @user_sources_interface.dry.get(, user_source_id.to_i)
    else
      print_dry_run @user_sources_interface.dry.list(, {name:user_source_id})
    end
    return
  end
  user_source = find_user_source_by_name_or_id(, user_source_id)
  if user_source.nil?
    return 1
  end
  # fetch by id to get config too
  json_response = nil
  if user_source_id.to_s =~ /\A\d{1,}\Z/
    json_response = {'userSource' => user_source}
  else
    json_response = @user_sources_interface.get(, user_source['id'])
    user_source = json_response['userSource']
  end
    
  #user_source = json_response['userSource']
  render_response(json_response, options, "userSource") do
    print_h1 "Identity Source Details"
    print cyan
    description_cols = {
      "ID" => lambda {|it| it['id'] },
      "Name" => lambda {|it| it['name'] },
      "Description" => lambda {|it| it['description'] },
      "Type" => lambda {|it| it['type'] },
      "Tenant" => lambda {|it| it['account'] ? it['account']['name'] : '' },
      #"Subdomain" => lambda {|it| it['subdomain'] },
      "Login URL" => lambda {|it| it['loginURL'] },
      "Default Role" => lambda {|it| it['defaultAccountRole'] ? it['defaultAccountRole']['authority'] : '' },
      "External Login" => lambda {|it| format_boolean it['externalLogin'] },
      "Allow Custom Mappings" => lambda {|it| format_boolean it['allowCustomMappings'] },
      "Active" => lambda {|it| format_boolean it['active'] },
    }
    print_description_list(description_cols, user_source)

    # show config settings...
    user_source_config = user_source['config']
    print_h2 "Configuration"
    if user_source_config
      columns = user_source_config.keys #.sort
      print_description_list(columns, user_source_config)
      # print reset,"\n"
    else
      print cyan,"No config found.","\n",reset
    end

    role_mappings = user_source['roleMappings']
    print_h2 "Role Mappings"
    if role_mappings && role_mappings.size > 0
      # print_h2 "Role Mappings"
      role_mapping_columns = [
        {"MORPHEUS ROLE" => lambda {|it| 
          it['mappedRole'] ? it['mappedRole']['authority'] : ''
        } },
        {"SOURCE ROLE NAME" => lambda {|it| it['sourceRoleName'] } },
        {"SOURCE ROLE FQN" => lambda {|it| it['sourceRoleFqn'] } },
      ]
      print as_pretty_table(role_mappings, role_mapping_columns)
    else
      print cyan,"No role mappings found for this identity source.","\n",reset
    end
    
    provider_settings = user_source['providerSettings']
    if provider_settings && !provider_settings.empty?
      print_h2 "Provider Settings"
      print_description_list({
        "Entity ID" => lambda {|it| it['entityId'] },
        "ACS URL" => lambda {|it| it['acsUrl'] }
      }, provider_settings)
      print_h2 "SP Metadata"
      print cyan
      print provider_settings['spMetadata']
      print "\n",reset
    else
      # print cyan,"No provider settings found.","\n",reset
    end
    print "\n",reset
  end
  return 0, nil
end

#activate(args) ⇒ Object



496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
# File 'lib/morpheus/cli/user_sources_command.rb', line 496

def activate(args)
  options = {}
  params = {}
   = nil
  role_mappings = nil
  role_mapping_names = nil
  optparse = Morpheus::Cli::OptionParser.new do|opts|
    opts.banner = subcommand_usage("[name]")
    build_common_options(opts, options, [:options, :json, :dry_run, :remote])
    opts.footer = "Activate an identity source." + "\n" +
                  "[name] is required. This is the name or id of an identity source."
  end
  optparse.parse!(args)
  if args.count < 1
    puts optparse
    exit 1
  end
  connect(options)
  begin
    user_source = find_user_source_by_name_or_id(nil, args[0])
    exit 1 if user_source.nil?
    payload = nil
    if options[:payload]
      payload = options[:payload]
    else
      payload = {}
      # support old -O options
      payload.deep_merge!(options[:options].reject {|k,v| k.is_a?(Symbol) }) if options[:options]
    end
    @user_sources_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @user_sources_interface.dry.activate(nil, user_source['id'], payload)
      return
    end
    
    json_response = @user_sources_interface.activate(nil, user_source['id'], payload)
    
    if options[:json]
      puts JSON.pretty_generate(json_response)
      return
    end

    print_green_success "Activated Identity Source #{user_source['name']}"
    get([user_source['id']] + (options[:remote] ? ["-r",options[:remote]] : []))
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#add(args) ⇒ Object



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
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
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
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
# File 'lib/morpheus/cli/user_sources_command.rb', line 213

def add(args)
  options = {}
  params = {}
   = nil
  type_code = nil
  role_mappings = nil
  role_mapping_names = nil
  default_role_id = nil
  optparse = Morpheus::Cli::OptionParser.new do|opts|
    opts.banner = subcommand_usage("[account] [name]")
    opts.on( '--tenant TENANT', String, "Tenant Name or ID the identity source will belong to, default is your own." ) do |val|
       = val
    end
    opts.on( '-a', '--account ACCOUNT', "Tenant Name or ID the identity source will belong to, default is your own." ) do |val|
       = val
    end
    opts.add_hidden_option('-a, --account') if opts.is_a?(Morpheus::Cli::OptionParser)
    opts.on('--type CODE', String, "Identity Source Type") do |val|
      type_code = val
    end
    opts.on('--name VALUE', String, "Name for this identity source") do |val|
      params['name'] = val
    end
    opts.on('--description VALUE', String, "Description") do |val|
      params['description'] = val
    end
    opts.on("--allow-custom-mappings [on|off]", ['on','off'], "Allow Custom Mappings, Enable Role Mapping Permissions") do |val|
      params['allowCustomMappings'] = val.to_s == 'on' || val.to_s == 'true' || val.to_s == '1' || val.to_s == ''
    end
    opts.on("--allowCustomMappings [on|off]", ['on','off'], "Allow Custom Mappings, Enable Role Mapping Permissions") do |val|
      params['allowCustomMappings'] = val.to_s == 'on' || val.to_s == 'true' || val.to_s == '1' || val.to_s == ''
    end
    opts.add_hidden_option('--allowCustomMappings')
    opts.on('--role-mappings MAPPINGS', String, "Role Mappings FQN in the format id1:FQN1,id2:FQN2") do |val|
      role_mappings = {}
      val.split(',').collect {|it| it.strip.split(':') }.each do |pair|
        k, v = pair[0], pair[1]
        if !k.to_s.empty?
          role_mappings[k.to_s] = v
        end
      end
    end
    opts.on('--role-mapping-names MAPPINGS', String, "Role Mapping Names in the format id1:Name1,id2:Name2") do |val|
      role_mapping_names = {}
      val.split(',').collect {|it| it.strip.split(':') }.each do |pair|
        k, v = pair[0], pair[1]
        if !k.to_s.empty?
          role_mapping_names[k.to_s] = v
        end
      end
    end
    
    opts.on('--default-role ID', String, "Default Role ID") do |val|
      default_role_id = val
    end
    #build_option_type_options(opts, options, add_user_source_option_types())
    build_standard_add_options(opts, options)
    opts.footer = "Create a new identity source." + "\n" +
                  "[account] is required. This is the name or id of an account."
  end
  optparse.parse!(args)
  connect(options)
  if args.count > 2
    print_error Morpheus::Terminal.angry_prompt
    puts_error  "wrong number of arguments, expected 0-2 and got (#{args.count}) #{args.inspect}\n#{optparse}"
    return 1
  end
  if args[0]
     = args[0]
  end
  if args[1]
    params['name'] = args[1]
  end
  


    # find the account first, or just prompt for that too please.
    if !
      print_error Morpheus::Terminal.angry_prompt
      puts_error  "missing required argument [account]\n#{optparse}"
      return 1
    end
     = ()
    return 1 if .nil?
     = ['id']

    # construct payload
    payload = {}
    if options[:payload]
      payload = options[:payload]
      payload.deep_merge!({'userSource' => parse_passed_options(options)})
    else
      payload.deep_merge!({'userSource' => parse_passed_options(options)})
      
      # Identity Source Type
      user_source_types = @user_sources_interface.list_types({userSelectable: true})['userSourceTypes']
      if user_source_types.empty?
        print_red_alert "No available Identity Source Types found"
        return 1
      end
      user_source_type = nil
      if !type_code
        user_source_type_dropdown = user_source_types.collect {|it| { 'name' => it['type'], 'value' => it['type']} }
        v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'type', 'type' => 'select', 'selectOptions' => user_source_type_dropdown, 'fieldLabel' => 'Type', 'required' => true}], options[:options])
        type_code = v_prompt['type'] if v_prompt['type']
      end
      user_source_type = user_source_types.find { |it| it['type'] == type_code }

      if user_source_type.nil?
        print_red_alert "Identity Source Type not found for '#{type_code}'"
        return 1
      end

      payload['userSource']['type'] = type_code

      # Name
      if params['name']
        payload['userSource']['name'] = params['name']
      else
        v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'name', 'type' => 'text', 'fieldLabel' => 'Name', 'required' => true}], options[:options])
        payload['userSource']['name'] = v_prompt['name'] if v_prompt['name']
      end
    
      # custom options by type
      my_option_types = load_user_source_type_option_types(user_source_type['type'])
      v_prompt = Morpheus::Cli::OptionTypes.prompt(my_option_types, options[:options])
      payload['userSource'].deep_merge!(v_prompt)

      # Default Account Role
      # todo: a proper select
      if !default_role_id
        v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldContext' => 'defaultAccountRole', 'fieldName' => 'id', 'type' => 'text', 'fieldLabel' => 'Default Account Role ID', 'required' => true}], options[:options])
        if v_prompt['defaultAccountRole'] && v_prompt['defaultAccountRole']['id']
          default_role_id = v_prompt['defaultAccountRole']['id']
        end
      end
      if default_role_id
        payload['userSource']['defaultAccountRole'] = {'id' => default_role_id }
      end

      # Allow Custom Mappings
      if !params['allowCustomMappings'].nil?
        payload['userSource']['allowCustomMappings'] = ["on","true"].include?(params['allowCustomMappings'].to_s)
      else
        v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'allowCustomMappings', 'type' => 'checkbox', 'fieldLabel' => 'Allow Custom Mappings', 'defaultValue' => false}], options[:options])
        payload['userSource']['allowCustomMappings'] = ["on","true"].include?(v_prompt['allowCustomMappings'].to_s)
      end

      if role_mappings
        payload['roleMappings'] = role_mappings
      end

      if role_mapping_names
        payload['roleMappingNames'] = role_mapping_names
      end

      # support old -O options
      payload['userSource'].deep_merge!(options[:options].reject {|k,v| k.is_a?(Symbol) }) if options[:options]
      

    end
    @user_sources_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @user_sources_interface.dry.create(, payload)
      return
    end
    # do it
    json_response = @user_sources_interface.create(, payload)
    # print and return result
    if options[:json]
      puts as_json(json_response, options)
      return 0
    end
    user_source = json_response['userSource']
    print_green_success "Added Identity Source #{user_source['name']}"
    get([user_source['id']] + (options[:remote] ? ["-r",options[:remote]] : []))
    return 0
end

#connect(opts) ⇒ Object



21
22
23
24
25
26
# File 'lib/morpheus/cli/user_sources_command.rb', line 21

def connect(opts)
  @api_client = establish_remote_appliance_connection(opts)
  @user_sources_interface = @api_client.user_sources
  @accounts_interface = @api_client.accounts
  @users_interface = @api_client.users
end

#deactivate(args) ⇒ Object



546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
# File 'lib/morpheus/cli/user_sources_command.rb', line 546

def deactivate(args)
  options = {}
  params = {}
   = nil
  role_mappings = nil
  role_mapping_names = nil
  optparse = Morpheus::Cli::OptionParser.new do|opts|
    opts.banner = subcommand_usage("[name]")
    build_common_options(opts, options, [:options, :json, :dry_run, :remote])
    opts.footer = "Deactivate an identity source." + "\n" +
                  "[name] is required. This is the name or id of an identity source."
  end
  optparse.parse!(args)
  if args.count < 1
    puts optparse
    exit 1
  end
  connect(options)
  begin
    user_source = find_user_source_by_name_or_id(nil, args[0])
    exit 1 if user_source.nil?
    payload = nil
    if options[:payload]
      payload = options[:payload]
    else
      payload = {}
      # support old -O options
      payload.deep_merge!(options[:options].reject {|k,v| k.is_a?(Symbol) }) if options[:options]
    end
    @user_sources_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @user_sources_interface.dry.deactivate(nil, user_source['id'], payload)
      return
    end
    
    json_response = @user_sources_interface.deactivate(nil, user_source['id'], payload)
    
    if options[:json]
      puts JSON.pretty_generate(json_response)
      return
    end

    print_green_success "Activated Identity Source #{user_source['name']}"
    get([user_source['id']] + (options[:remote] ? ["-r",options[:remote]] : []))
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#get(args) ⇒ Object



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

def get(args)
  params = {}
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[name]")
    # opts.on( '-c', '--config', "Display raw config only. Default is YAML. Combine with -j for JSON instead." ) do
    #   options[:show_config] = true
    # end
    # opts.on('--no-config', "Do not display Config YAML." ) do
    #   options[:no_config] = true
    # end
    build_standard_get_options(opts, options)
    opts.footer = <<-EOT
Get details about an identity source.
[name] is required. This is the name or id of an identity source.
EOT
  end
  optparse.parse!(args)
  verify_args!(args:args, optparse:optparse, min:1)
  connect(options)
  id_list = parse_id_list(args)
  return run_command_for_each_arg(id_list) do |arg|
    _get(arg, params, options)
  end
end

#get_type(args) ⇒ Object



746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
# File 'lib/morpheus/cli/user_sources_command.rb', line 746

def get_type(args)
  options = {}
  params = {}
   = nil
   = nil
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage("[type]")
    build_common_options(opts, options, [:json, :yaml, :csv, :fields, :dry_run, :remote])
    opts.footer = "Get details about an identity source type." + "\n" +
                  "[type] is required. This is the type identifier."
  end
  optparse.parse!(args)
  connect(options)
  # instance is required right now.
  # account_id = args[0] if !account_id
  expected_arg_count = 1
  if args.count != expected_arg_count
    print_error Morpheus::Terminal.angry_prompt
    puts_error  "wrong number of arguments, expected #{expected_arg_count} and got (#{args.count}) #{args.inspect}\n#{optparse}"
    return 1
  end
  begin
    user_source_type_id = args[0]
    
    # construct payload
    @user_sources_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @user_sources_interface.dry.list_types(user_source_type_id, params)
      return
    end
    json_response = @user_sources_interface.get_type(user_source_type_id, params)
    user_source_type = json_response["userSourceType"]
    if options[:json]
      puts as_json(json_response, options, "userSourceType")
      return 0
    elsif options[:yaml]
      puts as_yaml(json_response, options, "userSourceType")
      return 0
    elsif options[:csv]
      puts records_as_csv([user_source_type], options)
      return 0
    end
    title = "Identity Source Type"
    subtitles = []
    print_h1 title, subtitles
    print cyan
    description_cols = {
      #"ID" => lambda {|it| it['id'] },
      # "Name" => lambda {|it| it['name'] },
      # "Code" => lambda {|it| it['code'] },
      "Type" => lambda {|it| it['type'] },
      "External Login" => lambda {|it| format_boolean it['externalLogin'] },
      "Selectable" => lambda {|it| format_boolean it['userSelectable'] },
    }
    print_description_list(description_cols, user_source_type)

    # show config settings...
    my_option_types = user_source_type['optionTypes']
    
    
    if !my_option_types
      my_option_types = load_user_source_type_option_types(user_source_type['type'])
    end

    print_h2 "Configuration Option Types"
    if my_option_types && my_option_types.size > 0
      columns = [
        {"FIELD LABEL" => lambda {|it| it['fieldLabel'] } },
        {"FIELD NAME" => lambda {|it| [it['fieldContext'], it['fieldName']].select {|it| !it.to_s.empty? }.join('.') } },
        {"TYPE" => lambda {|it| it['type'] } },
        {"DEFAULT" => lambda {|it| it['defaultValue'] } },
        {"REQUIRED" => lambda {|it| format_boolean it['required'] } },
      ]
      print as_pretty_table(my_option_types, columns)
    else
      print cyan,"No option types found.","\n",reset
    end

    print reset,"\n"
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    return 1
  end
end

#handle(args) ⇒ Object



28
29
30
# File 'lib/morpheus/cli/user_sources_command.rb', line 28

def handle(args)
  handle_subcommand(args)
end

#list(args) ⇒ Object



33
34
35
36
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
# File 'lib/morpheus/cli/user_sources_command.rb', line 33

def list(args)
  options = {}
  params = {}
   = nil
   = nil
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage()
    opts.on( '--tenant TENANT', String, "Filter by Tenant" ) do |val|
       = val
    end
    opts.on( '-a', '--account ACCOUNT', "Filter by Tenant" ) do |val|
       = val
    end
    opts.add_hidden_option('-a, --account') if opts.is_a?(Morpheus::Cli::OptionParser)
    build_standard_list_options(opts, options)
    opts.footer = "List identity sources."
  end
  optparse.parse!(args)
  connect(options)
  # verify_args!(args:args, optparse:optparse, count:0)
  if args.count > 0
    options[:phrase] = args.join(" ")
  end
  if 
     = ()
    if .nil?
      return 1, "Tenant not found for '#{}'"
    end
     = ['id']
  end
  params.merge!(parse_list_options(options))
  @user_sources_interface.setopts(options)
  if options[:dry_run]
    print_dry_run @user_sources_interface.dry.list(, params)
    return 0, nil
  end
  json_response = @user_sources_interface.list(, params)
  render_response(json_response, options, "userSources") do
    user_sources = json_response["userSources"]
    title = "Morpheus Identity Sources"
    subtitles = []
    if 
      subtitles << "Tenant: #{['name']}".strip
    end
    subtitles += parse_list_subtitles(options)
    print_h1 title, subtitles
    if user_sources.empty?
      print cyan,"No identity sources found.",reset,"\n"
    else
      print_user_sources_table(user_sources, options)
      print_results_pagination(json_response)
    end
    print reset,"\n"
  end
  return 0, nil
  
end

#list_types(args) ⇒ Object



689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
# File 'lib/morpheus/cli/user_sources_command.rb', line 689

def list_types(args)
  options = {}
  params = {}
   = nil
   = nil
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = subcommand_usage()
    build_common_options(opts, options, [:list, :json, :yaml, :csv, :fields, :dry_run, :remote])
    opts.footer = "List identity source types."
  end
  optparse.parse!(args)
  connect(options)
  # instance is required right now.
  # account_id = args[0] if !account_id
  if args.count != 0
    print_error Morpheus::Terminal.angry_prompt
    puts_error  "wrong number of arguments, expected 0 and got (#{args.count}) #{args.inspect}\n#{optparse}"
    return 1
  end
  begin
    # construct payload
    params.merge!(parse_list_options(options))
    @user_sources_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @user_sources_interface.dry.list_types(params)
      return
    end

    json_response = @user_sources_interface.list_types(params)
    if options[:json]
      puts as_json(json_response, options, "userSourceTypes")
      return 0
    elsif options[:csv]
      puts records_as_csv(json_response['userSourceTypes'], options)
      return 0
    elsif options[:yaml]
      puts as_yaml(json_response, options, "userSourceTypes")
      return 0
    end
    user_source_types = json_response['userSourceTypes']
    title = "Morpheus Identity Source Types"
    subtitles = []
    subtitles += parse_list_subtitles(options)
    print_h1 title, subtitles
    if user_source_types.empty?
      print cyan,"No types found.",reset,"\n"
    else
      print_user_source_types_table(user_source_types, options)
      print_results_pagination(json_response, {:label => "type", :n_label => "types"})
    end
    print reset,"\n"
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    return 1
  end
end

#remove(args) ⇒ Object



648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
# File 'lib/morpheus/cli/user_sources_command.rb', line 648

def remove(args)
  options = {}
  optparse = Morpheus::Cli::OptionParser.new do|opts|
    opts.banner = subcommand_usage("[name]")
    build_common_options(opts, options, [:auto_confirm, :json, :dry_run, :remote])
    opts.footer = "Delete a user_source."
  end
  optparse.parse!(args)
  if args.count < 1
    puts optparse
    exit 1
  end
  connect(options)

  begin
    user_source = find_user_source_by_name_or_id(nil, args[0])
    exit 1 if user_source.nil?

    unless Morpheus::Cli::OptionTypes.confirm("Are you sure you want to delete the identity source #{user_source['name']}?", options)
      exit
    end
    @user_sources_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @user_sources_interface.dry.destroy(nil, user_source['id'])
      return
    end
    json_response = @user_sources_interface.destroy(nil, user_source['id'])

    if options[:json]
      print JSON.pretty_generate(json_response), "\n"
      return
    end

    print_green_success "Removed Identity Source #{user_source['name']}"
    #list([])
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#update(args) ⇒ Object



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
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
455
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
486
487
488
489
490
491
492
493
494
# File 'lib/morpheus/cli/user_sources_command.rb', line 392

def update(args)
  options = {}
  params = {}
   = nil
  role_mappings = nil
  role_mapping_names = nil
  optparse = Morpheus::Cli::OptionParser.new do|opts|
    opts.banner = subcommand_usage("[name] [options]")
    opts.on('--name VALUE', String, "Name for this identity source") do |val|
      params['name'] = val
    end
    opts.on('--description VALUE', String, "Description") do |val|
      params['description'] = val
    end
    opts.on("--allow-custom-mappings [on|off]", ['on','off'], "Allow Custom Mappings, Enable Role Mapping Permissions") do |val|
      params['allowCustomMappings'] = val.to_s == 'on' || val.to_s == 'true' || val.to_s == '1' || val.to_s == ''
    end
    opts.on("--allowCustomMappings [on|off]", ['on','off'], "Allow Custom Mappings, Enable Role Mapping Permissions") do |val|
      params['allowCustomMappings'] = val.to_s == 'on' || val.to_s == 'true' || val.to_s == '1' || val.to_s == ''
    end
    opts.add_hidden_option('--allowCustomMappings')
    opts.on('--role-mappings MAPPINGS', String, "Role Mappings in the format id1:FQN,id2:FQN2") do |val|
      role_mappings = {}
      val.split(',').collect {|it| it.strip.split(':') }.each do |pair|
        k, v = pair[0], pair[1]
        if !k.to_s.empty?
          role_mappings[k.to_s] = v
        end
      end
    end
    opts.on('--role-mapping-names MAPPINGS', String, "Role Mapping Names in the format id1:Name1,id2:Name2") do |val|
      role_mapping_names = {}
      val.split(',').collect {|it| it.strip.split(':') }.each do |pair|
        k, v = pair[0], pair[1]
        if !k.to_s.empty?
          role_mapping_names[k.to_s] = v
        end
      end
    end
    build_standard_update_options(opts, options)
    opts.footer = "Update an identity source." + "\n" +
                  "[name] is required. This is the name or id of an identity source."
  end
  optparse.parse!(args)
  if args.count < 1
    puts optparse
    exit 1
  end
  connect(options)
  begin
    user_source = find_user_source_by_name_or_id(nil, args[0])
    exit 1 if user_source.nil?
    payload = {}
    if options[:payload]
      payload = options[:payload]
      payload.deep_merge!({'userSource' => parse_passed_options(options)})
    else
      payload.deep_merge!({'userSource' => parse_passed_options(options)})

      # Name
      if params['name']
        payload['userSource']['name'] = params['name']
      end
      
      # Description
      if params['description']
        payload['userSource']['description'] = params['description']
      end
      
      # Allow Custom Mappings
      if !params['allowCustomMappings'].nil?
        payload['userSource']['allowCustomMappings'] = params['allowCustomMappings']
      end

      if role_mappings
        payload['roleMappings'] = role_mappings
      end

      if role_mapping_names
        payload['roleMappingNames'] = role_mapping_names
      end

    end
    @user_sources_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @user_sources_interface.dry.update(nil, user_source['id'], payload)
      return
    end
    
    json_response = @user_sources_interface.update(nil, user_source['id'], payload)
    
    if options[:json]
      puts JSON.pretty_generate(json_response)
      return
    end

    print_green_success "Updated Identity Source #{params['name'] || user_source['name']}"
    get([user_source['id']] + (options[:remote] ? ["-r",options[:remote]] : []))
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end

#update_subdomain(args) ⇒ Object



596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
# File 'lib/morpheus/cli/user_sources_command.rb', line 596

def update_subdomain(args)
  options = {}
  params = {}
   = nil
  optparse = Morpheus::Cli::OptionParser.new do|opts|
    opts.banner = subcommand_usage("[name]")
    opts.on('--subdomain VALUE', String, "New subdomain for this identity source") do |val|
      params['subdomain'] = (val == 'null') ? nil : val
    end
    build_common_options(opts, options, [:options, :json, :dry_run, :remote])
    opts.footer = "Update subdomain for an identity source." + "\n" +
                  "[name] is required. This is the name or id of an identity source."
  end
  optparse.parse!(args)
  if args.count < 1
    puts optparse
    exit 1
  end
  connect(options)
  begin
    user_source = find_user_source_by_name_or_id(nil, args[0])
    exit 1 if user_source.nil?
    payload = nil
    if options[:payload]
      payload = options[:payload]
    else
      payload = {}
      payload['subdomain'] = params['subdomain'] if params.key?('subdomain')
      # support old -O options
      payload.deep_merge!(options[:options].reject {|k,v| k.is_a?(Symbol) }) if options[:options]
    end
    @user_sources_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @user_sources_interface.dry.update_subdomain(nil, user_source['id'], payload)
      return
    end
    
    json_response = @user_sources_interface.update_subdomain(nil, user_source['id'], payload)
    
    if options[:json]
      puts JSON.pretty_generate(json_response)
      return
    end
    # JD: uhh this updates the account too, it cannot be set per identity source ...yet
    print_green_success "Updated Identity Source #{user_source['name']} subdomain to '#{payload['subdomain']}'"
    get([user_source['id']] + (options[:remote] ? ["-r",options[:remote]] : []))
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    exit 1
  end
end