Class: Morpheus::Cli::Whoami

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

Instance Attribute Summary

Attributes included from CliCommand

#no_prompt

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_type_by_id, #find_network_type_by_name, #find_network_type_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, #get_available_cloud_types, #groups_interface, included, #network_groups_interface, #network_types_interface, #networks_interface, #prompt_for_network, #prompt_for_networks, #prompt_for_subnets, #subnet_types_interface, #subnets_interface

Methods included from AccountsHelper

#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, #get_access_color, #get_access_string, included, #print_accounts_table, #print_roles_table, #print_users_table, #roles_interface, #user_groups_interface, #users_interface

Methods included from WhoamiHelper

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

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_name, #default_refresh_interval, #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, #puts, #puts_error, #raise_args_error, #raise_command_error, #render_response, #render_with_format, #run_command_for_each_arg, #subcommand_aliases, #subcommand_description, #subcommand_usage, #subcommands, #usage, #verify_args!, #visible_subcommands

Instance Method Details

#connect(options) ⇒ Object

no subcommands, just show()



20
21
22
23
24
# File 'lib/morpheus/cli/whoami.rb', line 20

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



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
227
228
229
230
231
232
233
# File 'lib/morpheus/cli/whoami.rb', line 30

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',
        "Tenant" => lambda {|it| (it['account'] ? it['account']['name'] : '') + (@is_master_account ? " (Master Account)" : '') },
        "First Name" => 'firstName',
        "Last Name" => 'lastName',
        # "Name" => 'displayName',
        #"Name" => lambda {|it| it['firstName'] ? it['displayName'] : '' },
        "Username" => 'username',
        "Email" => 'email',
        "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



26
27
28
# File 'lib/morpheus/cli/whoami.rb', line 26

def handle(args)
  get(args)
end