Class: Academical::HttpClient::AuthHandler

Inherits:
Faraday::Middleware
  • Object
show all
Defined in:
lib/academical/http_client/auth_handler.rb

Overview

AuthHandler takes care of devising the auth type and using it

Constant Summary collapse

HTTP_HEADER =
1

Instance Method Summary collapse

Constructor Details

#initialize(app, auth = {}, options = {}) ⇒ AuthHandler

Returns a new instance of AuthHandler.



12
13
14
15
# File 'lib/academical/http_client/auth_handler.rb', line 12

def initialize(app, auth = {}, options = {})
  @auth = auth
  super(app)
end

Instance Method Details

#call(env) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/academical/http_client/auth_handler.rb', line 17

def call(env)
  if !@auth.empty?
    auth = get_auth_type
    flag = false

    if auth == HTTP_HEADER
      env = http_header(env)
      flag = true
    end

    if !flag
      raise StandardError.new "Unable to calculate authorization method. Please check"
    end
  else
    raise StandardError.new "Server requires authentication to proceed further. Please check"
  end

  @app.call(env)
end

#get_auth_typeObject

Calculating the Authentication Type



38
39
40
41
42
43
44
45
# File 'lib/academical/http_client/auth_handler.rb', line 38

def get_auth_type()

  if @auth.has_key?(:http_header)
    return HTTP_HEADER
  end

  return -1
end

#http_header(env) ⇒ Object

Authorization with HTTP header



48
49
50
51
52
# File 'lib/academical/http_client/auth_handler.rb', line 48

def http_header(env)
  env[:request_headers]["Authorization"] = "Bearer #{@auth[:http_header]}"

  return env
end

#merge_query(env, query) ⇒ Object



62
63
64
65
66
67
68
# File 'lib/academical/http_client/auth_handler.rb', line 62

def merge_query(env, query)
  query = query.update query_params(env[:url])

  env[:url].query = Faraday::Utils.build_query(query)

  return env
end

#query_params(url) ⇒ Object



54
55
56
57
58
59
60
# File 'lib/academical/http_client/auth_handler.rb', line 54

def query_params(url)
  if url.query.nil? or url.query.empty?
    {}
  else
    Faraday::Utils.parse_query(url.query)
  end
end