OAuth2Refresh.call()   A
last analyzed

Complexity

Conditions 3

Size

Total Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 3
c 2
b 0
f 0
dl 0
loc 11
rs 9.4285
1
require 'base64'
2
require 'faraday'
3
require 'forwardable'
4
5
module FaradayMiddleware
6
  class OAuth2Refresh < Faraday::Middleware
7
    AUTH_HEADER = 'Authorization'.freeze
8
9
    attr_reader :oauth2_token
10
11
    extend Forwardable
12
13
    def call(env)
14
      if @oauth2_token.expired?
15
        @oauth2_token = @oauth2_token.refresh!({ headers: { 'Authorization' => 'Basic ' + get_api_key() } })
16
      end
17
      
18
      unless @oauth2_token.token.to_s.empty?
19
        env[:request_headers][AUTH_HEADER] = %(Bearer #{@oauth2_token.token})
20
      end
21
22
      @app.call env
23
    end
24
25
    def get_api_key
26
      api_key = Base64.encode64("#{@oauth2_token.client.id}:#{@oauth2_token.client.secret}").gsub(/[\s\t\r\n]/,'')
27
      return api_key
28
    end
29
30
    def initialize(app = nil, token = nil)
31
      super app
32
      @oauth2_token = token
33
    end
34
35
  end
36
end
37
38
Faraday::Request.register_middleware oauth2_refresh: FaradayMiddleware::OAuth2Refresh
39