# 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' def_delegators :@configuration, :client_id, :client_secret, :username, :password def self.refresh_token(refresh_token) new.refresh_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: '', # expires_in: 1200, # refresh_token: '' # } def obtain_token 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 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 private def config CapitalOnTap.configuration end def token_params { client_id: config.client_id, client_secret: config.client_secret, grant_type: DEFAULT_GRANT_TYPE, username: config.username, password: config.password } end end end