Sha256: 742bb569897bc50eb30facd99909e90564f9e73080d8f640e448a173845b1ea8

Contents?: true

Size: 1.3 KB

Versions: 1

Compression:

Stored size: 1.3 KB

Contents

# frozen_string_literal: true

module Bs2Api
  module Request
    class Auth
      class << self
        def token
          Bs2Api.configuration.valid?

          response = create_session

          raise Bs2Api::Errors::Unauthorized, response.parse["error_description"] if response.status.unauthorized?
          raise Bs2Api::Errors::BadRequest, response.parse["error_description"] if response.status.bad_request?
          raise Bs2Api::Errors::ServerError, response.body.to_s if !response.status.success?

          response.parse["access_token"]
        end

        private
          def create_session
            HTTP.basic_auth(
              user: Bs2Api.configuration.client_id,
              pass: Bs2Api.configuration.client_secret
            ).post(
              auth_url,
              body: body, 
              headers: headers
            )
          end

          def headers
            {
              "Content-Type": "application/x-www-form-urlencoded",
              "Accept": "application/json"
            }
          end

          def body
            {
              grant_type: "client_credentials",
              scope: "pix.write%20pix.read"
            }.to_query
          end

          def auth_url
            "#{Bs2Api.endpoint}/auth/oauth/v2/token"
          end
     end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
bs2_api-0.2.0 lib/bs2_api/request/auth.rb