Class: VagrantCloud::Auth

Inherits:
Object
  • Object
show all
Defined in:
lib/vagrant_cloud/auth.rb

Defined Under Namespace

Classes: HCPConfig, HCPToken

Constant Summary collapse

DEFAULT_AUTH_URL =

Default authentication URL

"https://auth.idp.hashicorp.com".freeze
DEFAULT_AUTH_PATH =

Default authorize path

"/oauth2/auth".freeze
DEFAULT_TOKEN_PATH =

Default token path

"/oauth2/token".freeze
TOKEN_EXPIRY_PADDING =

Number of seconds to pad token expiry

5

Instance Method Summary collapse

Constructor Details

#initialize(access_token: nil) ⇒ Auth

Note:

If no access token is provided, the token will be extracted

Create a new auth instance

from the VAGRANT_CLOUD_TOKEN environment variable. If that value is not set, the HCP_CLIENT_ID and HCP_CLIENT_SECRET environment variables will be checked. If found, tokens will be generated as needed using the client id and secret. Otherwise, no token will will be available.

Parameters:

  • access_token (String) (defaults to: nil)

    Static access token



69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
# File 'lib/vagrant_cloud/auth.rb', line 69

def initialize(access_token: nil)
  @token = access_token

  # The Vagrant Cloud token has precedence over
  # anything else, so if it is set then it is
  # the only value used.
  @token = ENV["VAGRANT_CLOUD_TOKEN"] if @token.nil?

  # If there is no token set, attempt to load HCP configuration
  if @token.to_s.empty? && (ENV["HCP_CLIENT_ID"] || ENV["HCP_CLIENT_SECRET"])
    @config = HCPConfig.new(
      client_id: ENV["HCP_CLIENT_ID"],
      client_secret: ENV["HCP_CLIENT_SECRET"],
      auth_url: ENV.fetch("HCP_AUTH_URL", DEFAULT_AUTH_URL),
      auth_path: ENV.fetch("HCP_AUTH_PATH", DEFAULT_AUTH_PATH),
      token_path: ENV.fetch("HCP_TOKEN_PATH", DEFAULT_TOKEN_PATH)
    )

    # Validate configuration is populated
    @config.validate!
  end
end

Instance Method Details

#available?Boolean

Returns Authentication token is available.

Returns:

  • (Boolean)

    Authentication token is available



110
111
112
# File 'lib/vagrant_cloud/auth.rb', line 110

def available?
  !!(@token || @config)
end

#tokenString

Returns authentication token.

Returns:

  • (String)

    authentication token



93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
# File 'lib/vagrant_cloud/auth.rb', line 93

def token
  # If a static token is defined, use that value
  return @token if @token

  # If no configuration is set, there is no auth to provide
  return if @config.nil?

  # If an HCP token exists and is not expired
  return @hcp_token.token if @hcp_token&.valid?

  # Generate a new HCP token
  refresh_token!

  @hcp_token.token
end