Module: MrMurano::AccountBase

Includes:
Http, Verbose
Included in:
Account, Business, Content::Base, Exchange, Gateway::GweBase, SolutionBase, Webservice::WebserviceBase
Defined in:
lib/MrMurano/AccountBase.rb

Constant Summary collapse

LOGIN_NOTICE =

'Please login.'
LOGIN_ADVICE =
%(
  Please login using `murano login` or `murano init`.
  Or set your password with `murano password set <username>`.
).strip.gsub(/^\s+/, '')

Constants included from Verbose

Verbose::TABULARIZE_DATA_FORMAT_ERROR

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Verbose

ask_yes_no, #ask_yes_no, #assert, assert, cmd_confirm_delete!, #cmd_confirm_delete!, debug, #debug, dump_file_json, dump_file_plain, dump_file_yaml, #dump_output_file, #error, error, #error_file_format!, fancy_ticks, #fancy_ticks, #load_file_json, #load_file_plain, #load_file_yaml, #load_input_file, outf, #outf, #outformat_engine, #pluralize?, pluralize?, #prepare_hash_csv, #read_hashf!, #tabularize, tabularize, verbose, #verbose, warning, #warning, #whirly_interject, whirly_interject, #whirly_linger, whirly_linger, #whirly_msg, whirly_msg, #whirly_pause, whirly_pause, #whirly_start, whirly_start, #whirly_stop, whirly_stop, #whirly_unpause, whirly_unpause

Methods included from Http

#curldebug, curldebug_after, curldebug_elapsed, curldebug_log, #delete, #endpoint, #host, #http, #http_reset, #isJSON, #json_opts, #patch, #post, #postf, #put, #showHttpError, #user, #workit, #workit_response

Class Method Details

.warn_configfile_env_maybeObject



293
294
295
296
297
298
299
300
301
# File 'lib/MrMurano/AccountBase.rb', line 293

def self.warn_configfile_env_maybe
  if !$cfg.get('business.id', :env).to_s.empty? &&
     !$cfg.get('business.id', :project).to_s.empty? &&
     $cfg.get('business.id', :env) != $cfg.get('business.id', :project)
    MrMurano::Verbose.warning %(
      NOTE: MURANO_CONFIGFILE specifies different business.id than local project file
    ).strip
  end
end

Instance Method Details

#add_headers(request) ⇒ Object



30
31
32
33
34
# File 'lib/MrMurano/AccountBase.rb', line 30

def add_headers(request)
  super
  MrMurano::HttpAuthed.instance.add_headers(request) unless @authless
  request
end

#ask_for_password!Object



94
95
96
97
98
99
100
101
102
# File 'lib/MrMurano/AccountBase.rb', line 94

def ask_for_password!
  prologue = "No Murano password found for #{user}."
  must_prompt_if_logged_off!(prologue)
  MrMurano::Verbose.whirly_pause
  error(%(#{prologue} #{LOGIN_NOTICE}).strip) unless @warned_once
  password = ask('Password: ') { |q| q.echo = '*' }
  MrMurano::Verbose.whirly_unpause
  password
end

#ask_for_user!Object



81
82
83
84
85
86
87
88
89
90
91
92
# File 'lib/MrMurano/AccountBase.rb', line 81

def ask_for_user!
  prologue = 'No Murano user account found.'
  must_prompt_if_logged_off!(prologue)
  MrMurano::Verbose.whirly_pause
  error("#{prologue} #{LOGIN_NOTICE}")
  @warned_once = true
  username = ask('User name: ')
  $cfg.set('user.name', username, :user)
  $project.refresh_user_name
  MrMurano::Verbose.whirly_unpause
  username
end

#cfg_clear_user_and_business(net_host, user_name) ⇒ Object



190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
# File 'lib/MrMurano/AccountBase.rb', line 190

def cfg_clear_user_and_business(net_host, user_name)
  user_net_host = $cfg.get('net.host', :user)
  user_net_host = $cfg.get('net.host', :defaults) if user_net_host.nil?
  user_user_name = $cfg.get('user.name', :user)
  # Only clear user name from the user config if the net.host
  # or user.name did not come from a different config, like the
  # --project config.
  unless (user_net_host == net_host) && (user_user_name == user_name)
    verbose 'Skipping config scrub: net.host and/or user.name do not match.'
    return
  end
  $cfg.set('user.name', nil, :user)
  $cfg.set('business.id', nil, :user)
  $cfg.set('business.name', nil, :user)
end

#credentials_resetObject



77
78
79
# File 'lib/MrMurano/AccountBase.rb', line 77

def credentials_reset
  MrMurano::HttpAuthed.instance.credentials_reset
end

#get(path = '', query = nil, &block) ⇒ Object

Handle pagination for all commands derived from this class.



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
# File 'lib/MrMurano/AccountBase.rb', line 221

def get(path='', query=nil, &block)
  aggregate = nil
  total = nil
  remaining = -1
  first_count = nil
  orig_query = (query || []).dup
  while remaining != 0
    ret = super
    return nil if ret.nil?
    # Return now if not paginating.
    if (!ret.is_a?(Hash) ||
        !ret.key?(:items) ||
        !(ret.key?(:total) || ret.key?(:count))
       )
      # ret is not a hash, or it's missing :items or :total/:count.
      unless aggregate.nil?
        warning %(Unexpected: aggregate set: #{aggregate} / ret: #{ret})
      end
      aggregate = ret
      remaining = 0
      break
    end
    query = orig_query.dup
    if ret.key?(:total)
      if total.nil?
        total = ret[:total]
        remaining = total
        # The response also includes a hint of how to get the next page.
        #   ret[:next] == "/api/v1/eventhandler?query={         #     \"solution_id\":\"XXXXXXXXXXXXXXXX\"}&limit=20&offset=20"
        # But note that the URL we use is a little different
        #   https://bizapi.hosted.exosite.io/api:1/solution/<sid>/eventhandler
      elsif total != ret[:total]
        warning %(
          Unexpected subsequence total: #{ret[:total]} != #{total}
        ).strip
      end
      remaining -= ret[:items].length
    else
      # This should be true:
      #   assert(ret.key?(:count))
      #   assert(ret[:count] == ret[:items].length)
      # Not all pageable commands indicate :total (ahem, /exchange/).
      if total.nil?
        first_count = ret[:items].length
        total = first_count
      elsif ret[:items].length < first_count
        # Last batch!
        first_count = 0
      end
      # Our next command will grab the next batch of limit size.
      total += ret[:items].length
      remaining = first_count
    end
    if remaining > 0
      # DEVS: You can test pagination, e.g.,
      #   query.push ['limit', 5]
      query.push ['offset', total - remaining]
    elsif remaining != 0
      warning %(Unexpected: negative remaining: #{fancy_ticks(total)})
      remaining = 0
    end
    if aggregate.nil?
      aggregate = ret
    else
      aggregate[:items].concat ret[:items]
      aggregate[:count] = aggregate[:items].length
    end
  end
  aggregate
end

#initialize(authless: false) ⇒ Object



20
21
22
23
24
25
26
27
28
# File 'lib/MrMurano/AccountBase.rb', line 20

def initialize(authless: false)
  super()
  # Set up the HttpAuthed instance. If 'authless', caller wants an
  # Account object but does not want to ask user for name and password,
  # nor does caller want credentials added to any HTTP requests. This
  # is so far only useful for the `murano token delete` command.
   unless authless
  @authless = false
end

#invalidate_token(tok) ⇒ Object



173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
# File 'lib/MrMurano/AccountBase.rb', line 173

def invalidate_token(tok)
  # Delete/invalidate the remote tok.
  return if tok.to_s.empty?
  verbose 'Removing token.'
  @suppress_error = true
  # (lb): This is a bit of a kludge. The DELETE token/ call does not need
  # authentication creds (like username and password). So tell our
  # add_headers method not to call HttpAuthed.add_headers, which would
  # otherwise add Authentication headers to the HTTP request.
  @authless = true
  delete('token/' + tok)
  @authless = false
  # The response is nil if token was not recognized, else it's {}.
  # We don't care, because we'll forget our copy of the token.
  @suppress_error = false
end

#login_infoObject



55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/MrMurano/AccountBase.rb', line 55

def 
  verify_cfg_auth!
  # (lb): This is a little hokey, but someone has to init the Singleton,
  # so we make sure it's ready anytime a new AccountBase instance is created.
  email_pwd = MrMurano::HttpAuthed.instance.
  return email_pwd unless email_pwd.nil?
  @warned_once = false
  ask_for_user! if user.empty?
  # Do not prompt for password if using token.
  if !MrMurano::HttpAuthed.instance.logging_on && $cfg['auth.scheme-token']
    token = MrMurano::HttpAuthed.instance.token_resolve
    # (lb): FIXME/2018-08-09: These appears to be missing a return value...!
    return unless token.to_s.empty?
  end
  password = MrMurano::HttpAuthed.instance.password_get_or_ask(
    host, user
  ) { ask_for_password! }
  email_pwd = { email: user, password: password }
  email_pwd['ttl'] = $cfg.get('auth.ttl') unless $cfg.get('auth.ttl').to_s.empty?
  MrMurano::HttpAuthed.instance. = email_pwd
end

#logout(keep_user: false, keep_password: false, no_invalidate: false) ⇒ Object




152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
# File 'lib/MrMurano/AccountBase.rb', line 152

def logout(keep_user: false, keep_password: false, no_invalidate: false)
  MrMurano::HttpAuthed.instance.logging_on = true

  token = MrMurano::HttpAuthed.instance.token_lookup
  invalidate_token(token) unless no_invalidate

  net_host = verify_set('net.host')
  user_name = verify_set('user.name')
  if net_host && user_name
    MrMurano::HttpAuthed.instance.token_forget(
      net_host, user_name, keep_password: keep_password,
    )
  else
    verbose 'Skipping password scrub: need both host and username to remove.'
  end

  cfg_clear_user_and_business(net_host, user_name) unless keep_user

  MrMurano::HttpAuthed.instance.logging_on = false
end

#must_prompt_if_logged_off!(prologue) ⇒ Object



104
105
106
107
108
109
# File 'lib/MrMurano/AccountBase.rb', line 104

def must_prompt_if_logged_off!(prologue)
  return if $cfg.prompt_if_logged_off
  MrMurano::Verbose.whirly_stop
  error("#{prologue}\n#{LOGIN_ADVICE}")
  exit 2
end

#tokenObject



36
37
38
39
40
# File 'lib/MrMurano/AccountBase.rb', line 36

def token
  token_biz = MrMurano::HttpAuthed.instance.token_biz
  return token_biz unless token_biz.to_s.empty?
  MrMurano::HttpAuthed.instance.ensure_token!
end

#token_reset(new_token = '') ⇒ Object



42
43
44
# File 'lib/MrMurano/AccountBase.rb', line 42

def token_reset(new_token='')
  MrMurano::HttpAuthed.instance.token_reset(new_token)
end

#verify_cfg_auth!Object



111
112
113
114
115
# File 'lib/MrMurano/AccountBase.rb', line 111

def verify_cfg_auth!
  verify_cfg_auth_scheme!
  verify_cfg_auth_persist
  verify_cfg_auth_ttl
end

#verify_cfg_auth_persistObject



134
135
136
137
138
139
# File 'lib/MrMurano/AccountBase.rb', line 134

def verify_cfg_auth_persist
  return unless $cfg['auth.persist-token'].nil? && $cfg['auth.persist-basic'].nil?
  # User did not specify either --[no-]login or --[no-]cache.
  # Default to caching the token.
  $cfg['auth.persist-token'] = true
end

#verify_cfg_auth_scheme!Object



117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
# File 'lib/MrMurano/AccountBase.rb', line 117

def verify_cfg_auth_scheme!
  if $cfg['auth.scheme-token'] && $cfg['auth.scheme-basic']
    error(%(Please only specify 'token' or 'basic' authentication))
    exit 1
  elsif !($cfg['auth.scheme-token'] || $cfg['auth.scheme-basic'])
    if $cfg['auth.scheme-token'].nil?
      # Default to token auth.
      # E.g., user ran `murano cmd`, or `murano cmd --no-basic`.
      $cfg['auth.scheme-token'] = true
    else
      # $cfg['auth.scheme-token'] is false(y), so use basic auth.
      # E.g., user ran `cmd --no-token`, or `cmd --no-token --basic`.
      $cfg['auth.scheme-basic'] = true
    end
  end
end

#verify_cfg_auth_ttlObject



141
142
143
144
145
146
147
148
# File 'lib/MrMurano/AccountBase.rb', line 141

def verify_cfg_auth_ttl
  return unless $cfg['auth.ttl'].nil? && !$cfg['auth.persist-token']
  # User did not specify TTL, and token *not* being cached,
  # so set a low time-to-live (2018-03-07: currently 60 secs).
  $cfg['auth.ttl'] = MrMurano::Config::CFG_AUTH_DEFAULT_TTL
  # Otherwise, user overrode the value; or
  # token being persisted, so leave nil and let BizAPI set default.
end

#verify_set(cfg_key) ⇒ Object




208
209
210
211
212
213
214
215
216
# File 'lib/MrMurano/AccountBase.rb', line 208

def verify_set(cfg_key)
  cfg_val = $cfg.get(cfg_key)
  if cfg_val.to_s.empty?
    cfg_val = nil
    cfg_key_q = MrMurano::Verbose.fancy_ticks(cfg_key)
    MrMurano::Verbose.warning("No config key #{cfg_key_q}: no password to delete")
  end
  cfg_val
end