Class: ChefAnalytics::Identity

Inherits:
Object
  • Object
show all
Defined in:
lib/chef-analytics/identity.rb

Defined Under Namespace

Classes: IdentityServerAPI

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Identity

Returns a new instance of Identity.



39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/chef-analytics/identity.rb', line 39

def initialize(options = {})
  options = options.dup
  options[:identity_server_url] ||= default_identity_server_url
  options[:client_name] ||= Chef::Config[:node_name]
  options[:signing_key_filename] ||= Chef::Config[:client_key]

  Chef::Log.debug("Using Identity Server: #{options[:identity_server_url]}")

  @options = options
  @identity_server = IdentityServerAPI.new(options)
  @cache_file_name = construct_file_name(options[:identity_server_url],
                                         options[:client_name])
end

Instance Method Details

#tokenObject



53
54
55
56
57
58
59
60
# File 'lib/chef-analytics/identity.rb', line 53

def token
  fs_token = token_from_filesystem
  if fs_token
    fs_token
  else
    token_from_signed_request
  end
end

#token_from_filesystemObject



79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
# File 'lib/chef-analytics/identity.rb', line 79

def token_from_filesystem
  if File.exists?(@cache_file_name) && File.readable?(@cache_file_name)
    Chef::Log.debug("Loading token from FS: #{@cache_file_name}")
    token = ChefAnalytics::Token.from_file(@cache_file_name)
    if token.expired?
      Chef::Log.debug("Found expired cached credentials: #{@cache_file_name}")
      return nil
    end

    token
  else
    Chef::Log.debug("Couldn't find cached credentials: #{@cache_file_name}")
    nil
  end
end

#token_from_signed_requestObject



62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# File 'lib/chef-analytics/identity.rb', line 62

def token_from_signed_request
  begin
    result = @identity_server.request(:post, "oauth/token?grant_type=password",
                                      {'Content-Type' => 'application/json'})
    token = ChefAnalytics::Token.from_hash(result)
    token.identity_server_url @options[:identity_server_url]
    token.client_name @options[:client_name]
    token.to_file(@cache_file_name)
    token
  rescue Timeout::Error, Errno::EINVAL, Errno::ECONNRESET,
         EOFError, Net::HTTPBadResponse, Net::HTTPHeaderSyntaxError,
         Net::ProtocolError => e
    Chef::Log.error("Exception caught on getting token: #{e}")
    nil
  end
end