Sha256: 3597e55e7fa135a10a0a6f8549a2c1560087821c8125315f205c057e2a0402da

Contents?: true

Size: 1.43 KB

Versions: 16

Compression:

Stored size: 1.43 KB

Contents

require 'aptible/auth'

require_relative 'config_path'

module Aptible
  module CLI
    module Helpers
      module Token
        include Helpers::ConfigPath

        TOKEN_ENV_VAR = 'APTIBLE_ACCESS_TOKEN'.freeze

        def fetch_token
          @token ||= ENV[TOKEN_ENV_VAR] ||
                     current_token_hash[Aptible::Auth.configuration.root_url]
          return @token if @token
          raise Thor::Error, 'Could not read token: please run aptible login ' \
                             "or set #{TOKEN_ENV_VAR}"
        end

        def save_token(token)
          hash = current_token_hash.merge(
            Aptible::Auth.configuration.root_url => token
          )

          FileUtils.mkdir_p(File.dirname(token_file))

          File.open(token_file, 'w', 0o600) do |file|
            file.puts hash.to_json
          end
        rescue StandardError => e
          m = "Could not write token to #{token_file}: #{e}. " \
              'Check filesystem permissions.'
          raise Thor::Error, m
        end

        def current_token_hash
          # NOTE: older versions of the CLI did not properly create the
          # token_file with mode 600, which is why we update it when reading.
          File.chmod(0o600, token_file)
          JSON.parse(File.read(token_file))
        rescue
          {}
        end

        def token_file
          File.join(aptible_config_path, 'tokens.json').freeze
        end
      end
    end
  end
end

Version data entries

16 entries across 16 versions & 1 rubygems

Version Path
aptible-cli-0.24.2 lib/aptible/cli/helpers/token.rb
aptible-cli-0.24.1 lib/aptible/cli/helpers/token.rb
aptible-cli-0.24.0 lib/aptible/cli/helpers/token.rb
aptible-cli-0.23.0 lib/aptible/cli/helpers/token.rb
aptible-cli-0.22.0 lib/aptible/cli/helpers/token.rb
aptible-cli-0.21.0 lib/aptible/cli/helpers/token.rb
aptible-cli-0.20.0 lib/aptible/cli/helpers/token.rb
aptible-cli-0.19.9 lib/aptible/cli/helpers/token.rb
aptible-cli-0.19.7 lib/aptible/cli/helpers/token.rb
aptible-cli-0.19.6 lib/aptible/cli/helpers/token.rb
aptible-cli-0.19.4 lib/aptible/cli/helpers/token.rb
aptible-cli-0.19.3 lib/aptible/cli/helpers/token.rb
aptible-cli-0.19.2 lib/aptible/cli/helpers/token.rb
aptible-cli-0.19.1 lib/aptible/cli/helpers/token.rb
aptible-cli-0.19.0 lib/aptible/cli/helpers/token.rb
aptible-cli-0.18.3 lib/aptible/cli/helpers/token.rb