Class: Morpheus::Cli::Whoami

Inherits:
Object
  • Object
show all
Extended by:
Term::ANSIColor
Includes:
AccountsHelper, CliCommand, InfrastructureHelper, WhoamiHelper
Defined in:
lib/morpheus/cli/commands/whoami.rb

Constant Summary collapse

@@whoami_cache =

@@whoami_cache is for caching the the contents the Whoami api results as YAML files at $home/whoami/$appliance_name/$user_id.json

nil

Instance Attribute Summary

Attributes included from CliCommand

#no_prompt

Class Method Summary collapse

Instance Method Summary collapse

Methods included from InfrastructureHelper

#cloud_type_for_id, #cloud_type_for_name, #cloud_type_for_name_or_id, #clouds_interface, #find_cloud_by_id, #find_cloud_by_name, #find_cloud_by_name_or_id, #find_group_by_id, #find_group_by_name, #find_group_by_name_or_id, #find_network_by_id, #find_network_by_name, #find_network_by_name_or_id, #find_network_group_by_id, #find_network_group_by_name, #find_network_group_by_name_or_id, #find_network_server_type_by_id, #find_network_server_type_by_name, #find_network_server_type_by_name_or_code, #find_network_server_type_by_name_or_id, #find_network_type_by_id, #find_network_type_by_name, #find_network_type_by_name_or_id, #find_resource_pool_by_id, #find_resource_pool_by_name, #find_resource_pool_by_name_or_id, #find_resource_pool_group_by_id, #find_resource_pool_group_by_name, #find_resource_pool_group_by_name_or_id, #find_subnet_by_id, #find_subnet_by_name, #find_subnet_by_name_or_id, #find_subnet_type_by_id, #find_subnet_type_by_name, #find_subnet_type_by_name_or_id, #format_network_pool_server_status, #get_available_cloud_types, #groups_interface, included, #network_groups_interface, #network_pool_server_column_definitions, #network_pool_server_list_column_definitions, #network_pool_server_type_column_definitions, #network_pool_server_type_list_column_definitions, #network_server_type_column_definitions, #network_server_type_list_column_definitions, #network_types_interface, #networks_interface, #prompt_for_network, #prompt_for_networks, #prompt_for_pools, #prompt_for_subnets, #resource_pool_groups_interface, #resource_pools_interface, #subnet_types_interface, #subnets_interface

Methods included from AccountsHelper

#account_column_definitions, #account_users_interface, #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

Methods included from WhoamiHelper

#current_account, #current_user, #current_user_permissions, included, #is_master_account, #load_whoami

Methods included from CliCommand

#add_query_parameter, #apply_options, #build_common_options, #build_get_options, #build_list_options, #build_option_type_options, #build_standard_add_many_options, #build_standard_add_options, #build_standard_api_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, #confirm, #confirm!, #default_refresh_interval, #default_sigdig, #default_subcommand, #establish_remote_appliance_connection, #execute_api, #execute_api_payload, #execute_api_request, #find_all, #find_all_json, #find_by_id, #find_by_name, #find_by_name_or_id, #find_record, #find_record_json, #full_command_usage, #get_interface, #get_list_key, #get_object_key, #get_subcommand_description, #handle_each_payload, #handle_subcommand, included, #interactive?, #my_help_command, #my_terminal, #my_terminal=, #parse_array, #parse_bytes_param, #parse_get_options!, #parse_id_list, #parse_labels, #parse_list_options, #parse_list_options!, #parse_list_subtitles, #parse_options, #parse_parameter_as_resource_id!, #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

Class Method Details

.clear_whoami(appliance_name, user_id) ⇒ Object



301
302
303
304
# File 'lib/morpheus/cli/commands/whoami.rb', line 301

def clear_whoami(appliance_name, user_id)
  delete_whoami_file(appliance_name, user_id)
  set_whoami_cache(appliance_name, user_id, nil)
end

.clear_whoami_cache(appliance_name, user_id) ⇒ Object



243
244
245
246
247
# File 'lib/morpheus/cli/commands/whoami.rb', line 243

def clear_whoami_cache(appliance_name, user_id)
  @@whoami_cache ||= {}
  @@whoami_cache[appliance_name.to_s] ||= {}
  @@whoami_cache[appliance_name.to_s][user_id.to_s] = result
end

.delete_whoami_file(appliance_name, user_id) ⇒ Object



275
276
277
278
279
280
281
282
# File 'lib/morpheus/cli/commands/whoami.rb', line 275

def delete_whoami_file(appliance_name, user_id)
  fn = File.join(whoami_file_path, appliance_name.to_s, user_id.to_s + ".json")
  if File.exist?(fn)
    #Morpheus::Logging::DarkPrinter.puts "deleting file #{fn}" if Morpheus::Logging.debug?
    FileUtils.rm(fn)
  end
  return nil
end

.get_whoami_cache(appliance_name, user_id) ⇒ Object



255
256
257
258
# File 'lib/morpheus/cli/commands/whoami.rb', line 255

def get_whoami_cache(appliance_name, user_id)
  @@whoami_cache ||= {}
  @@whoami_cache[appliance_name.to_s] ? @@whoami_cache[appliance_name.to_s][user_id.to_s] : nil
end

.load_whoami(appliance_name, user_id, refresh = false) ⇒ Object



306
307
308
309
310
311
312
313
314
315
316
317
318
319
# File 'lib/morpheus/cli/commands/whoami.rb', line 306

def load_whoami(appliance_name, user_id, refresh=false)
  result = nil
  # load from cache (memory) or file or else api
  if refresh == false
    # load from memory
    result = whoami_cache[appliance_name.to_s] ? whoami_cache[appliance_name.to_s][user_id.to_s] : nil
    # load from file
    if result.nil?
      result = load_whoami_file(appliance_name, user_id)
      set_whoami_cache(appliance_name, user_id, result)
    end
  end
  return result
end

.load_whoami_file(appliance_name, user_id) ⇒ Object



284
285
286
287
288
289
290
291
292
293
294
# File 'lib/morpheus/cli/commands/whoami.rb', line 284

def load_whoami_file(appliance_name, user_id)
  raise "appliance_name is required" if appliance_name.to_s.empty?
  raise "user_id is required" if user_id.to_s.empty?
  fn = File.join(whoami_file_path, appliance_name.to_s, user_id.to_s + ".json")
  if File.exist?(fn)
    Morpheus::Logging::DarkPrinter.puts "reading file #{fn}" if Morpheus::Logging.debug?
    return YAML.load_file(fn)
  else
    return nil
  end
end

.save_whoami(appliance_name, user_id, result) ⇒ Object



296
297
298
299
# File 'lib/morpheus/cli/commands/whoami.rb', line 296

def save_whoami(appliance_name, user_id, result)
  save_whoami_file(appliance_name, user_id, result)
  set_whoami_cache(appliance_name, user_id, result)
end

.save_whoami_file(appliance_name, user_id, json_response) ⇒ Object



264
265
266
267
268
269
270
271
272
273
# File 'lib/morpheus/cli/commands/whoami.rb', line 264

def save_whoami_file(appliance_name, user_id, json_response)
  fn = File.join(whoami_file_path, appliance_name.to_s, user_id.to_s + ".json")
  if !Dir.exist?(File.dirname(fn))
    FileUtils.mkdir_p(File.dirname(fn))
  end
  Morpheus::Logging::DarkPrinter.puts "writing file #{fn}" if Morpheus::Logging.debug?
  File.open(fn, 'w') {|f| f.write json_response.to_yaml }
  FileUtils.chmod(0600, fn)
  return json_response
end

.set_whoami_cache(appliance_name, user_id, result) ⇒ Object



249
250
251
252
253
# File 'lib/morpheus/cli/commands/whoami.rb', line 249

def set_whoami_cache(appliance_name, user_id, result)
  @@whoami_cache ||= {}
  @@whoami_cache[appliance_name.to_s] ||= {}
  @@whoami_cache[appliance_name.to_s][user_id.to_s] = result
end

.whoami_cacheObject



236
237
238
239
240
241
# File 'lib/morpheus/cli/commands/whoami.rb', line 236

def whoami_cache
  if @@whoami_cache.nil?
    @@whoami_cache = {}
  end
  return @@whoami_cache
end

.whoami_file_pathObject



260
261
262
# File 'lib/morpheus/cli/commands/whoami.rb', line 260

def whoami_file_path
  File.join(Morpheus::Cli.home_directory, "cache", "whoami")
end

Instance Method Details

#connect(options) ⇒ Object

no subcommands, just show()



13
14
15
16
17
# File 'lib/morpheus/cli/commands/whoami.rb', line 13

def connect(options)
  # @api_client = establish_remote_appliance_connection(options)
  @api_client = establish_remote_appliance_connection(options.merge({:skip_verify_access_token => true, :skip_login => true}))
  @whoami_interface = @api_client.whoami
end

#get(args) ⇒ Object



23
24
25
26
27
28
29
30
31
32
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
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
# File 'lib/morpheus/cli/commands/whoami.rb', line 23

def get(args)
  options = {}
  params = {}
  username_only = false
  access_token_only = false
  optparse = Morpheus::Cli::OptionParser.new do |opts|
    opts.banner = usage
    opts.on( '-n', '--name', "Print only your username." ) do
      username_only = true
    end
    opts.on('-a','--all', "Display All Details") do
      options[:include_feature_access] = true
      options[:include_group_access] = true
      options[:include_cloud_access] = true
      options[:include_instance_type_access] = true
    end
    opts.on('-p','--permissions', "Display Permissions") do
      options[:include_feature_access] = true
      # options[:include_group_access] = true
      # options[:include_cloud_access] = true
      # options[:include_instance_type_access] = true
    end
    # opts.on('-f','--feature-access', "Display Feature Access") do
    #   options[:include_feature_access] = true
    # end
    # opts.add_hidden_option('--feature-access')
    # these are things that morpheus users get has to display...
    # opts.on(nil,'--group-access', "Display Group Access") do
    #   options[:include_group_access] = true
    # end
    # opts.on(nil,'--cloud-access', "Display Cloud Access") do
    #   options[:include_cloud_access] = true
    # end
    # opts.on(nil,'--instance-type-access', "Display Instance Type Access") do
    #   options[:include_instance_type_access] = true
    # end
    opts.on('-t','--token-only', "Print your access token only") do
      access_token_only = true
    end
    opts.on('--offline', '--offline', "Do this offline without an api request to refresh the remote appliance status.") do
      options[:do_offline] = true
    end
    build_standard_get_options(opts, options)
    opts.footer = <<-EOT
View information about the current user.
EOT
  end
  optparse.parse!(args)
  verify_args!(args:args, optparse:optparse, count:0)
  connect(options)
  begin
    if @access_token.nil?
      print_error yellow,"You are not currently logged in",reset,"\n"
      return 1, "no current user"
    end
    @whoami_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @whoami_interface.dry.get(params)
      return 0
    end

    #json_response = load_whoami()
    whoami_response = nil
    if options[:do_offline]
      # if @remote_appliance && @remote_appliance[:username]
      #   exit_code = 0
      # else
      #   exit_code = 1
      # end
      # no permissions, or even name stored atm, we should start storing that.
      # then we can start checking permissions nd restricting command visibility.
      whoami_response = {
        "user" => {
          "username" => @remote_appliance ? @remote_appliance[:username] : nil
        },
        # "isMasterAccount" => true,
        "permissions" => [],
        "appliance" => {
         "buildVersion" => @remote_appliance ? @remote_appliance[:build_version] : nil
        }
      }
    else
      whoami_response = @whoami_interface.get(params)
    end
    json_response = whoami_response
    @current_user = whoami_response["user"]
    # if @current_user.nil?
    #   print_red_alert "Unauthenticated. Please login."
    #   exit 1
    # end
    @is_master_account = whoami_response["isMasterAccount"]
    @user_permissions = whoami_response["permissions"]

    if whoami_response["appliance"]
      @appliance_build_verison = whoami_response["appliance"]["buildVersion"]
    else
      @appliance_build_verison = nil
    end

    render_response(json_response, options) do

      if access_token_only
        if options[:quiet]
          return @current_user ? 0 : 1
        end
        if @access_token.nil?
          print yellow,"\n","No access token. Please login",reset,"\n"
          return false
        end
        print cyan,@access_token.to_s,reset,"\n"
        return 0
      end

      if username_only
        if options[:quiet]
          return @current_user ? 0 : 1
        end
        if @current_user.nil?
          puts_error "(logged out)" # "(anonymous)" || ""
          return 1
        else
          print cyan,@current_user['username'].to_s,reset,"\n"
          return 0
        end
      end

      if @current_user.nil?
        print yellow,"\n","No active session. Please login",reset,"\n"
        exit 1
      end
      subtitles = []
      #subtitles << "#{display_appliance(@appliance_name, @appliance_url)}"
      print_h1 "Current User", subtitles, options
      print cyan
      print_description_list({
        "ID" => 'id',
        "Username" => 'username',
        # "First Name" => 'firstName',
        # "Last Name" => 'lastName',
        # "Name" => 'displayName',
        "Name" => lambda {|it| "#{it['firstName']} #{it['lastName']}".strip },
        "Email" => 'email',
        "Tenant" => lambda {|it| (it['account'] ? it['account']['name'] : '') + (@is_master_account ? " (Master Tenant)" : '') },
        "Role" => lambda {|it| format_user_role_names(it) },
        "Remote" => lambda {|it| display_appliance(@appliance_name, @appliance_url) },
      }, @current_user)
      print cyan

      if options[:include_feature_access]
        if @user_permissions
          print_h2 "Feature Permissions", options
          print cyan
          begin
            rows = []
            if @user_permissions.is_a?(Hash)
              # api used to return map like [code:access]
              rows = @user_permissions.collect do |code, access|
                {permission: code, access: format_access_string(access) }
              end
            else
              # api now returns an array of objects like [[name:"Foo",code:"foo",access:"full"], ...]
              rows = @user_permissions.collect do |it|
                {permission: (it['name'] || it['code']), access: format_access_string(it['access']) }
              end
            end
            # api sort sux right now
            rows = rows.sort {|a,b| a[:permission] <=> b[:permission] }
            print as_pretty_table(rows, [:permission, :access], options)
          rescue => ex
            puts_error "Failed to parse feature permissions: #{ex}"
          end
        else
          puts yellow,"No permissions found.",reset
        end
      end

      print reset, "\n"

      # save pertinent session info to the appliance
      begin
        now = Time.now.to_i
        app_map = ::Morpheus::Cli::Remote.load_remote(@appliance_name)
        app_map[:username] = @current_user['username']
        app_map[:authenticated] = true
        app_map[:status] = 'ready'
        app_map[:build_version] = @appliance_build_verison if @appliance_build_verison
        app_map[:last_success_at] = now
        ::Morpheus::Cli::Remote.save_remote(@appliance_name, app_map)
      rescue => err
        puts "failed to save remote appliance info"
      end
    end
    return 0
  rescue RestClient::Exception => e
    print_rest_exception(e, options)
    # if e.response && e.response.code == 401
    #   puts "It looks like you need to login to the remote appliance [#{@appliance_name}] #{@appliance_url}"
    #   if Morpheus::Cli::OptionTypes.confirm("Would you like to login now?")
    #     return Morpheus::Cli::Login.new.login([])
    #   end
    # end
    return 1
  end
end

#handle(args) ⇒ Object



19
20
21
# File 'lib/morpheus/cli/commands/whoami.rb', line 19

def handle(args)
  get(args)
end