# frozen_string_literal: true require 'faraday' require 'multi_json' require 'truelayer/configuration' require 'truelayer/errors' require 'truelayer/version' require 'truelayer/token' require 'truelayer/auth_link' require 'truelayer/provider' module Truelayer class AuthenticationRepository def generate_direct_bank_link(provider_id:, consent_id:, redirect_uri:, scopes:, state: nil, tracking_id: nil, data_use_description: nil) params = { response_type: 'code', client_id: Truelayer.configuration.client_id, provider_id: provider_id, redirect_uri: redirect_uri, scope: scopes, consent_id: consent_id } params[:state] = state if state params[:tracking_id] = tracking_id if tracking_id params[:data_use_description] = data_use_description if data_use_description result = post('/v1/authuri', params: nil) do |req| req.headers[:content_type] = 'application/json' req.body = MultiJson.dump(params) end AuthLink.build(json: result.body) end def exchange_code(code, redirect_uri) params = { grant_type: 'authorization_code', client_id: Truelayer.configuration.client_id, client_secret: Truelayer.configuration.client_secret, redirect_uri: redirect_uri, code: code } result = post('/connect/token', params: params) Token.build(json: result.body) end def refresh_token(refresh_token) params = { grant_type: 'refresh_token', client_id: Truelayer.configuration.client_id, client_secret: Truelayer.configuration.client_secret, refresh_token: refresh_token } result = post('/connect/token', params: params) Token.build(json: result.body) end def providers response = get('/api/providers', params: { clientId: Truelayer.configuration.client_id }) (response.body || []).map do |result| Provider.build(json: result) end end private def get(path, params:) response = connection.get(path, params) return response if response.success? raise GenericError, "#{response.status}: #{response.body}" end def post(path, params:, &block) response = connection.post(path, params, &block) return response if response.success? if response.status == 400 raise InvalidRequestError, response.body else raise GenericError, "#{response.status}: #{response.body}" end end def connection auth_url = Truelayer.configuration.auth_url @connection ||= Faraday.new(url: auth_url) do |conn| conn.request :url_encoded conn.headers.merge!( user_agent: "finpoint/#{Truelayer::VERSION}" ) conn.response :multi_json, symbolize_keys: true if Truelayer.configuration.debug conn.response :logger, nil, { headers: true, bodies: Truelayer.configuration.verbose } end conn.adapter Faraday.default_adapter end end end end