Sha256: 402d5fcda6b590f03a5dfc0d88f57a92137965a612eab99052e4c7bf6608501e

Contents?: true

Size: 1.51 KB

Versions: 1

Compression:

Stored size: 1.51 KB

Contents

require 'aptible/auth'
require 'json'

module Comply
  module CLI
    module Helpers
      module Token
        TOKEN_ENV_VAR = 'APTIBLE_ACCESS_TOKEN'.freeze

        def current_user_email
          @current_user_email ||=
            Aptible::Auth::Agent.new(token: fetch_token).me.email
        end

        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 comply 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 ENV['HOME'], '.aptible', 'tokens.json'
        end
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
comply-cli-0.0.1 lib/comply/cli/helpers/token.rb