Sha256: 5bce60585726b64a4ce515a2f57fba4da46e5e1f0ea20f9293679f5b21a84073

Contents?: true

Size: 1.95 KB

Versions: 4

Compression:

Stored size: 1.95 KB

Contents

# frozen_string_literal: true

require 'multi_json'
require 'faraday'
require 'faraday_middleware'
require 'addressable'

module CapitalOnTap
  class Auth
    extend Forwardable

    TOKEN_PATH = '/connect/token'
    DEFAULT_GRANT_TYPE = 'password'
    REFRESH_GRANT_TYPE = 'refresh_token'

    def_delegators :@configuration, :client_id, :client_secret, :username, :password

    def self.refresh_access_token(refresh_token)
      new.refresh_access_token(refresh_token)
    end

    def self.obtain_token
      new.obtain_token
    end

    # Requests a new token. The response will be something like:
    #
    # {
    #   scope: 'profile offline_access',
    #   token_type: 'Bearer',
    #   access_token: '<access_token>',
    #   expires_in: 1200,
    #   refresh_token: '<refresh_token>'
    # }
    def obtain_token
      token_request(token_params)
    end

    def refresh_access_token(refresh_token)
      return {} unless refresh_token

      refresh_params = token_params(grant_type: REFRESH_GRANT_TYPE, refresh_token: refresh_token)

      token_request(refresh_params)
    end

    private

    def client
      Faraday.new(url: config.base_auth_url) do |conn|
        conn.headers['Content-Type'] = 'application/x-www-form-urlencoded'
        conn.response :logger if config.debug?
        conn.adapter Faraday.default_adapter
      end
    end

    def token_request(token_params)
      puts "[DEBUG] Sending #{token_params.inspect}" if config.debug?

      result = client.post do |req|
        req.url TOKEN_PATH
        req.body = URI.encode_www_form(token_params)
      end

      MultiJson.load(result.body, symbolize_keys: true)
    end

    def config
      CapitalOnTap.configuration
    end

    def token_params(params = {})
      {
        client_id: config.client_id,
        client_secret: config.client_secret,
        grant_type: DEFAULT_GRANT_TYPE,
        username: config.username,
        password: config.password
      }.merge(params)
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
capital_on_tap-1.0.0 lib/capital_on_tap/auth.rb
capital_on_tap-0.2.1 lib/capital_on_tap/auth.rb
capital_on_tap-0.2.0 lib/capital_on_tap/auth.rb
capital_on_tap-0.1.8 lib/capital_on_tap/auth.rb