Sha256: 81622ce7464eff2bfbdd9df34e20fb53bac6002a7134a2912c8dfd6f94b28a08

Contents?: true

Size: 949 Bytes

Versions: 4

Compression:

Stored size: 949 Bytes

Contents

module Mrkt
  module Authentication
    def authenticate!
      authenticate unless authenticated?
      fail Mrkt::Errors::AuthorizationError, 'Client not authenticated' unless authenticated?
    end

    def authenticated?
      @token && valid_token?
    end

    def valid_token?
      @valid_until && Time.now < @valid_until
    end

    def authenticate
      connection.get('/identity/oauth/token', authentication_params).tap do |response|
        data = response.body

        @token = data.fetch(:access_token)
        @token_type = data.fetch(:token_type)
        @valid_until = Time.now + data.fetch(:expires_in)
        @scope = data.fetch(:scope)
      end
    end

    def authentication_params
      {
        grant_type: 'client_credentials',
        client_id: @client_id,
        client_secret: @client_secret
      }
    end

    def add_authorization(req)
      req.headers[:authorization] = "Bearer #{@token}"
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
mrkt-0.6.2 lib/mrkt/concerns/authentication.rb
mrkt-0.6.1 lib/mrkt/concerns/authentication.rb
mrkt-0.6.0 lib/mrkt/concerns/authentication.rb
mrkt-0.5.0 lib/mrkt/concerns/authentication.rb