# 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: '', # expires_in: 1200, # 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