Sha256: 377862684c6fbd447fa11984c65ea61b7507e3d8129d567f01d7c2dd18cce06e

Contents?: true

Size: 1.44 KB

Versions: 1

Compression:

Stored size: 1.44 KB

Contents

module G5AuthenticatableApi
  class TokenValidator
    attr_reader :error

    def initialize(params={},headers={})
      @params = params || {}
      @headers = headers || {}
    end

    def validate!
      begin
        auth_client.token_info
      rescue StandardError => @error
        raise error
      end
    end

    def valid?
      begin
        validate!
        true
      rescue StandardError => e
        false
      end
    end

    def access_token
      @access_token ||= if @headers['Authorization']
        parts = @headers['Authorization'].match(/Bearer (?<access_token>\S+)/)
        parts['access_token']
      else
        @params['access_token']
      end
    end

    def auth_response_header
      if error
        auth_header = "Bearer"

        if access_token
          auth_header << " error=\"#{error_code}\""
          auth_header << ",error_description=\"#{error_description}\"" if error_description
        end

        auth_header
      end
    end

    def auth_client
      @auth_client ||= G5AuthenticationClient::Client.new(allow_password_credentials: 'false',
                                                          access_token: access_token)
    end

    private
    def error_code
      error_code = error.code if error.respond_to?(:code)
      error_code || 'invalid_request'
    end

    def error_description
      error_description = error.description if error.respond_to?(:description)
      error_description
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
g5_authenticatable_api-0.2.0 lib/g5_authenticatable_api/token_validator.rb