Module: Gzr::Session

Included in:
Command, Commands::Session::Get, Commands::Session::Update
Defined in:
lib/gzr/modules/session.rb

Instance Method Summary collapse

Instance Method Details

#build_connection_hash(api_version = nil) ⇒ 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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
# File 'lib/gzr/modules/session.rb', line 91

def build_connection_hash(api_version=nil)
  conn_hash = Hash.new
  conn_hash[:api_endpoint] = "http#{@options[:ssl] ? "s" : ""}://#{@options[:host]}:#{@options[:port]}/api/#{api_version||@current_version||""}"
  if @options[:http_proxy]
    conn_hash[:connection_options] ||= {}
    conn_hash[:connection_options][:proxy] = {
      :uri => @options[:http_proxy]
    }
  end
  if @options[:ssl]
    conn_hash[:connection_options] ||= {}
    if @options[:verify_ssl] then
      conn_hash[:connection_options][:ssl] = {
        :verify => true,
        :verify_mode => (OpenSSL::SSL::VERIFY_PEER | OpenSSL::SSL::VERIFY_FAIL_IF_NO_PEER_CERT)
      }
    else
      conn_hash[:connection_options][:ssl] = {
        :verify => false,
        :verify_mode => (OpenSSL::SSL::VERIFY_NONE)
      }
    end
  end
  if @options[:timeout]
    conn_hash[:connection_options] ||= {}
    conn_hash[:connection_options][:request] = {
      :timeout => @options[:timeout]
    }
  end
  conn_hash[:user_agent] = "Gazer #{Gzr::VERSION}"

  return conn_hash if @options[:token] || @options[:token_file]

  if @options[:client_id] then
    conn_hash[:client_id] = @options[:client_id]
    if @options[:client_secret] then
      conn_hash[:client_secret] = @options[:client_secret]
    else
      reader = TTY::Reader.new
      @secret ||= reader.read_line("Enter your client_secret:", echo: false)
      conn_hash[:client_secret] = @secret
    end
  else
    conn_hash[:netrc] = true
    conn_hash[:netrc_file] = "~/.netrc"
  end
  conn_hash
end

#login(min_api_version = "4.0") ⇒ Object

Raises:



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
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
# File 'lib/gzr/modules/session.rb', line 140

def (min_api_version="4.0")
  if !@options[:token] && !@options[:token_file]
    if (@options[:client_id].nil? && ENV["LOOKERSDK_CLIENT_ID"])
      @options[:client_id] = ENV["LOOKERSDK_CLIENT_ID"]
    end

    if (@options[:client_secret].nil? && ENV["LOOKERSDK_CLIENT_SECRET"])
      @options[:client_secret] = ENV["LOOKERSDK_CLIENT_SECRET"]
    end
  end

  if (@options[:verify_ssl] && ENV["LOOKERSDK_VERIFY_SSL"])
    @options[:verify_ssl] = !(/^f(alse)?$/i =~ ENV["LOOKERSDK_VERIFY_SSL"])
  end

  if ((@options[:host] == 'localhost') && ENV["LOOKERSDK_BASE_URL"])
    base_url = ENV["LOOKERSDK_BASE_URL"]
    @options[:ssl] = !!(/^https/ =~ base_url)
    @options[:host] = /^https?:\/\/([^:\/]+)/.match(base_url)[1]
    md = /:([0-9]+)\/?$/.match(base_url)
    @options[:port] = md[1] if md
  end

  say_ok("using options #{@options.select { |k,v| k != 'client_secret' }.map { |k,v| "#{k}=>#{v}" }}") if @options[:debug]

  @secret = nil
  begin
    conn_hash = build_connection_hash

    sawyer_options = {
      :links_parser => Sawyer::LinkParsers::Simple.new,
      :serializer  => LookerSDK::Client::Serializer.new(JSON),
      :faraday => Faraday.new(conn_hash[:connection_options]) do |conn|
        conn.use LookerSDK::Response::RaiseError
        if @options[:persistent]
          conn.adapter :net_http_persistent
        end
      end
    }

    endpoint = conn_hash[:api_endpoint]
    endpoint_uri = URI.parse(endpoint)
    root = endpoint.slice(0..-endpoint_uri.path.length)

    agent = Sawyer::Agent.new(root, sawyer_options) do |http|
      http.headers[:accept] = 'application/json'
      http.headers[:user_agent] = conn_hash[:user_agent]
    end

    begin
      versions_response = agent.call(:get,"/versions")
      @versions = versions_response.data.supported_versions.map {|v| v.version}
      @current_version = versions_response.data.current_version.version || "4.0"
    rescue Faraday::SSLError => e
      raise Gzr::CLI::Error, "SSL Certificate could not be verified\nDo you need the --no-verify-ssl option or the --no-ssl option?"
    rescue Faraday::ConnectionFailed => cf
      raise Gzr::CLI::Error, "Connection Failed.\nDid you specify the --no-ssl option for an ssl secured server?\nYou may need to use --port=443 in some cases as well."
    rescue LookerSDK::NotFound => nf
      say_warning "endpoint #{root}/versions was not found"
    end
  end

  say_warning "API current_version #{@current_version}" if @options[:debug]
  say_warning "Supported API versions #{@versions}" if @options[:debug]

  api_version = [min_api_version, @current_version].max
  raise Gzr::CLI::Error, "Operation requires API v#{api_version}, which is not available from this host" if api_version && !@versions.any? {|v| v == api_version}

  conn_hash = build_connection_hash(api_version)
  @secret = nil

  say_ok("connecting to #{conn_hash.map { |k,v| "#{k}=>#{(k == :client_secret) ? '*********' : v}" }}") if @options[:debug]

  begin
    faraday = Faraday.new(conn_hash[:connection_options]) do |conn|
      conn.use LookerSDK::Response::RaiseError
      if @options[:persistent]
        conn.adapter :net_http_persistent
      end
    end
    @sdk = LookerSDK::Client.new(conn_hash.merge(faraday: faraday)) unless @sdk

    say_ok "check for connectivity: #{@sdk.alive?}" if @options[:debug]
    if @options[:token_file]
      entry = read_token_data&.fetch(@options[:host].to_sym,nil)&.fetch(@options[:su]&.to_sym || :default,nil)
      if entry.nil?
        say_error "No token found for host #{@options[:host]} and user #{@options[:su] || "default"}"
        say_error "login with `gzr session login --host #{@options[:host]}` to set a token"
        raise LookerSDK::Unauthorized.new
      end
      (day, time, tz) = entry[:expiration].split(' ')
      day_parts = day.split('-')
      time_parts = time.split(':')
      date_time_parts = day_parts + time_parts + [tz]
      expiration = Time.new(*date_time_parts)
      if expiration < (Time.now + 300)
        if expiration < Time.now
          say_error "token expired at #{expiration}"
        else
          say_error "token expires at #{expiration}, which is in the next 5 minutes"
        end
        say_error "login again with `gzr session login --host #{@options[:host]}`"
        raise LookerSDK::Unauthorized.new
      end
      @sdk.access_token = entry[:token]
    elsif @options[:token]
      @sdk.access_token = @options[:token]
    end
    say_ok "verify authentication: #{@sdk.authenticated?}" if @options[:debug]
  rescue LookerSDK::Unauthorized => e
    say_error "Unauthorized - credentials are not valid"
    raise
  rescue LookerSDK::Error => e
    say_error "Unable to connect"
    say_error e
    say_error e.errors if e.respond_to?(:errors) && e.errors
    raise
  end
  raise Gzr::CLI::Error, "Invalid credentials" unless @sdk.authenticated?


  if @options[:su] && !(@options[:token] || @options[:token_file])then
    say_ok "su to user #{@options[:su]}" if @options[:debug]
    @access_token_stack.push(@sdk.access_token)
    begin
      @sdk.access_token = @sdk.(@options[:su]).access_token
      say_warning "verify authentication: #{@sdk.authenticated?}" if @options[:debug]
    rescue LookerSDK::Error => e
      say_error "Unable to su to user #{@options[:su]}"
      say_error e
      say_error e.errors if e.respond_to?(:errors) && e.errors
      raise
    end
  end
  @sdk
end

#logout_allObject



277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
# File 'lib/gzr/modules/session.rb', line 277

def logout_all
  pastel = Pastel.new(enabled: true)
  say_ok "logout" if @options[:debug]
  begin
    @sdk.logout
  rescue LookerSDK::Error => e
    say_error "Unable to logout"
    say_error e
    say_error e.errors if e.respond_to?(:errors) && e.errors
  end if @sdk
  loop do
    token = @access_token_stack.pop
    break unless token
    say_ok "logout the parent session" if @options[:debug]
    @sdk.access_token = token
    begin
      @sdk.logout
    rescue LookerSDK::Error => e
      say_error "Unable to logout"
      say_error e
      say_error e.errors if e.respond_to?(:errors) && e.errors
    end
  end
end

#pastelObject



33
34
35
# File 'lib/gzr/modules/session.rb', line 33

def pastel
  @pastel ||= Pastel.new
end

#read_token_dataObject



62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/gzr/modules/session.rb', line 62

def read_token_data
  return nil unless File.exist?(token_file)
  s = File.stat(token_file)
  if !(s.mode.to_s(8)[3..5] == "600")
    say_error "#{token_file} mode is #{s.mode.to_s(8)[3..5]}. It must be 600. Ignoring."
    return nil
  end
  token_data = nil
  file = nil
  begin
    file = File.open(token_file)
    token_data = JSON.parse(file.read,{:symbolize_names => true})
  ensure
    file.close if file
  end
  token_data
end

#say_error(data, output: $stderr) ⇒ Object



45
46
47
# File 'lib/gzr/modules/session.rb', line 45

def say_error(data, output: $stderr)
  output.puts pastel.red data
end

#say_ok(data, output: $stdout) ⇒ Object



37
38
39
# File 'lib/gzr/modules/session.rb', line 37

def say_ok(data, output: $stdout)
  output.puts pastel.green data
end

#say_warning(data, output: $stderr) ⇒ Object



41
42
43
# File 'lib/gzr/modules/session.rb', line 41

def say_warning(data, output: $stderr)
  output.puts pastel.yellow data
end

#sufficient_version?(given_version, minimum_version) ⇒ Boolean

Returns:

  • (Boolean)


52
53
54
55
56
# File 'lib/gzr/modules/session.rb', line 52

def sufficient_version?(given_version, minimum_version)
  return true unless (given_version && minimum_version)
  versions = @versions.sort
  !versions.drop_while {|v| v < minimum_version}.reverse.drop_while {|v| v > given_version}.empty?
end

#token_fileObject



58
59
60
# File 'lib/gzr/modules/session.rb', line 58

def token_file
  "#{ENV["HOME"]}/.gzr_auth"
end

#update_auth(workspace_id) ⇒ Object



316
317
318
319
320
321
322
323
324
325
# File 'lib/gzr/modules/session.rb', line 316

def update_auth(workspace_id)
  body = {}
  body[:workspace_id] = workspace_id
  begin
    @sdk.update_session(body)&.to_attrs
  rescue LookerSDK::Error => e
    say_error "Unable to run update_session(#{JSON.pretty_generate(body)})"
    say_error e
  end
end

#with_session(min_api_version = "4.0") ⇒ Object



302
303
304
305
306
307
308
309
310
311
312
313
314
# File 'lib/gzr/modules/session.rb', line 302

def with_session(min_api_version="4.0")
  return nil unless block_given?
  begin
    (min_api_version) unless @sdk
    yield
  rescue LookerSDK::Error => e
    say_error e.errors if e.respond_to?(:errors) && e.errors
    e.backtrace.each { |b| say_error b } if @options[:debug]
    raise Gzr::CLI::Error, e.message
  ensure
    logout_all unless @options[:token] || @options[:token_file]
  end
end

#write_token_data(token_data) ⇒ Object



80
81
82
83
84
85
86
87
88
89
# File 'lib/gzr/modules/session.rb', line 80

def write_token_data(token_data)
  file = nil
  begin
    file = File.new(token_file, "wt")
    file.chmod(0600)
    file.write JSON.pretty_generate(token_data)
  ensure
    file.close if file
  end
end