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, #get_available_cloud_types, #groups_interface, included

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

Methods included from WhoamiHelper

included, #load_whoami

Methods included from CliCommand

#build_common_options, #build_option_type_options, #command_name, #default_refresh_interval, #default_subcommand, #establish_remote_appliance_connection, #full_command_usage, #handle_subcommand, included, #interactive?, #my_help_command, #my_terminal, #my_terminal=, #parse_id_list, #parse_list_options, #parse_list_subtitles, #print, #print_error, #puts, #puts_error, #raise_command_error, #render_with_format, #run_command_for_each_arg, #subcommand_aliases, #subcommand_usage, #subcommands, #usage, #verify_access_token!

Constructor Details

#initializeWhoami

no subcommands, just show()



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

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

Instance Method Details

#connect(opts) ⇒ Object



24
25
26
27
28
29
30
31
32
33
# File 'lib/morpheus/cli/whoami.rb', line 24

def connect(opts)
  #@api_client = establish_remote_appliance_connection(opts)
  # begin
    @api_client = establish_remote_appliance_connection(opts.merge({:no_prompt => true, :skip_verify_access_token => true}))
    @groups_interface = @api_client.groups
    @active_group_id = Morpheus::Cli::Groups.active_group
  # rescue Morpheus::Cli::CommandError => err
  #   puts_error err
  # end
end

#handle(args) ⇒ Object



35
36
37
# File 'lib/morpheus/cli/whoami.rb', line 35

def handle(args)
  show(args)
end

#show(args) ⇒ Object



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/whoami.rb', line 39

def show(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('-f','--feature-access', "Display Feature Access") do
      options[:include_feature_access] = true
    end
    # 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('-a','--all-access', "Display All Access Lists") 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('-t','--token-only', "Print your access token only") do
      access_token_only = true
    end
    build_common_options(opts, options, [:json, :remote, :dry_run, :quiet])
  end
  optparse.parse!(args)
  connect(options)
  begin
    # check to see if they have credentials instead of just trying to connect (and prompting)

    if !@appliance_name
      # never gets here..
      #raise_command_error "Please specify a Morpheus Appliance with -r or see the command `remote use`"
      print yellow,"Please specify a Morpheus Appliance with -r or see `remote use`.#{reset}\n"
      return 1
    end
    
    if options[:dry_run]
      print_dry_run @api_client.whoami.setopts(options).dry.get(params)
      return 0
    end

    # todo: fix potential issue here, should be able to use --remote-url or --username
    # in which case you do not have to be logged in (saved credentials)...
    # maybe just update connect() to do @api_client = establish_remote_appliance_connection(opts)
    # wallet = Morpheus::Cli::Credentials.new(@appliance_name, @appliance_url).request_credentials(options)
    wallet = Morpheus::Cli::Credentials.new(@appliance_name, @appliance_url).load_saved_credentials()
    token = wallet ? wallet['access_token'] : nil
    if !token
      if options[:quiet]
        return 1
      elsif access_token_only
        puts_error "(logged out)" # stderr probably
        return 1
      else
        print yellow,"You are not currently logged in to #{display_appliance(@appliance_name, @appliance_url)}",reset,"\n"
        print yellow,"Use the 'login' command.",reset,"\n"
        return 1
      end
    end

    #json_response = load_whoami()

    whoami_interface = @api_client.whoami.setopts(options)
    whoami_response = whoami_interface.get()
    json_response = whoami_response
    @current_user = whoami_response["user"]
    if @current_user.empty?
      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

    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

    
    active_group = nil
    begin
      active_group = @active_group_id ? find_group_by_name_or_id(@active_group_id) : nil # via InfrastructureHelper mixin
    rescue => err
      if options[:debug]
        print red,"Unable to determine active group: #{err}\n",reset
      end
    end

    if options[:json]
      print JSON.pretty_generate(json_response)
      print "\n"
    else
      if @current_user.nil?
        print yellow,"\n","No active session. Please login",reset,"\n"
        exit 1
      end

      print_h1 "Current User", options
      print cyan
      print_description_list({
        "ID" => 'id',
        "Account" => 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) }
      }, @current_user)
      print cyan

      if options[:include_feature_access]
        if @user_permissions
          print_h2 "Feature Permissions", options
          print cyan
          rows = @user_permissions.collect do |code, access|
            {code: code, access: get_access_string(access) }
          end
          print as_pretty_table(rows, [:code, :access], options)
        else
          puts yellow,"No permissions found.",reset
        end
      end

      print_h1 "Remote Appliance", options
      print cyan
      appliance_data = {
        'name' => @appliance_name,
        'url' => @appliance_url,
        'buildVersion' => @appliance_build_verison
      }
      print_description_list({
        "Name" => 'name',
        "URL" => 'url',
        "Version" => 'buildVersion'
      }, appliance_data)

      if active_group
        print cyan
        # print_h1 "Active Group", options
        # print cyan
        # print_description_list({
        #   "ID" => 'id',
        #   "Name" => 'name'
        # }, active_group)
        print cyan, "\n# => Currently using group #{active_group['name']}\n", reset
        print reset,"\n"
      else
        print "\n", reset
        print "No active group. See `groups use`\n",reset
        print reset,"\n"
      end

      # 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