Class: Google::Cloud::Credentials

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Defined in:
lib/google/cloud/credentials.rb

Overview

Represents the OAuth 2.0 signing logic. This class is intended to be inherited by API-specific classes which overrides the SCOPE constant.

Constant Summary collapse

TOKEN_CREDENTIAL_URI =
"https://accounts.google.com/o/oauth2/token"
AUDIENCE =
"https://accounts.google.com/o/oauth2/token"
SCOPE =
[]
PATH_ENV_VARS =
%w(GOOGLE_CLOUD_KEYFILE GCLOUD_KEYFILE)
JSON_ENV_VARS =
%w(GOOGLE_CLOUD_KEYFILE_JSON GCLOUD_KEYFILE_JSON)
DEFAULT_PATHS =
["~/.config/gcloud/application_default_credentials.json"]

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(keyfile, scope: nil) ⇒ Credentials

Returns a new instance of Credentials.



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/google/cloud/credentials.rb', line 45

def initialize keyfile, scope: nil
  verify_keyfile_provided! keyfile
  if keyfile.is_a? Signet::OAuth2::Client
    @client = keyfile
  elsif keyfile.is_a? Hash
    hash = stringify_hash_keys keyfile
    hash["scope"] ||= scope
    @client = init_client hash
  else
    verify_keyfile_exists! keyfile
    json = JSON.parse ::File.read(keyfile)
    json["scope"] ||= scope
    @client = init_client json
  end
  @client.fetch_access_token!
end

Instance Attribute Details

#clientObject

Returns the value of attribute client.



36
37
38
# File 'lib/google/cloud/credentials.rb', line 36

def client
  @client
end

Class Method Details

.default(scope: nil) ⇒ Object

Returns the default credentials.



65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
# File 'lib/google/cloud/credentials.rb', line 65

def self.default scope: nil
  env  = ->(v) { ENV[v] }
  json = ->(v) { JSON.parse ENV[v] rescue nil unless ENV[v].nil? }
  path = ->(p) { ::File.file? p }

  # First try to find keyfile file from environment variables.
  self::PATH_ENV_VARS.map(&env).reject(&:nil?).select(&path)
    .each do |file|
      return new file, scope: scope
    end
  # Second try to find keyfile json from environment variables.
  self::JSON_ENV_VARS.map(&json).reject(&:nil?).each do |hash|
    return new hash, scope: scope
  end
  # Third try to find keyfile file from known file paths.
  self::DEFAULT_PATHS.select(&path).each do |file|
    return new file, scope: scope
  end
  # Finally get instantiated client from Google::Auth.
  scope ||= self::SCOPE
  client = Google::Auth.get_application_default scope
  new client
end