Class: Faraday::Panoptes::ClientCredentialsAuthentication

Inherits:
Middleware
  • Object
show all
Defined in:
lib/faraday/panoptes/client_credentials_authentication.rb

Instance Method Summary collapse

Constructor Details

#initialize(app, url:, client_id:, client_secret:) ⇒ ClientCredentialsAuthentication

Returns a new instance of ClientCredentialsAuthentication.



15
16
17
18
19
20
21
# File 'lib/faraday/panoptes/client_credentials_authentication.rb', line 15

def initialize(app, url:, client_id:, client_secret:)
  super(app)
  @client_id = client_id
  @client_secret = client_secret
  @conn = Faraday.new(url: url)
  @current_token = nil
end

Instance Method Details

#access_tokenObject



32
33
34
35
36
37
38
# File 'lib/faraday/panoptes/client_credentials_authentication.rb', line 32

def access_token
  if need_new_token?
    @current_token = get_token
  end

  @current_token["access_token"]
end

#authorization_headerObject



28
29
30
# File 'lib/faraday/panoptes/client_credentials_authentication.rb', line 28

def authorization_header
  "Bearer #{access_token}"
end

#call(env) ⇒ Object



23
24
25
26
# File 'lib/faraday/panoptes/client_credentials_authentication.rb', line 23

def call(env)
  env[:request_headers]["Authorization"] = authorization_header
  @app.call(env)
end

#get_tokenObject



48
49
50
51
52
53
54
55
56
# File 'lib/faraday/panoptes/client_credentials_authentication.rb', line 48

def get_token
  result = @conn.post("/oauth/token",
    grant_type: 'client_credentials',
    client_id: @client_id,
    client_secret: @client_secret)

  raise CredentialsOAuthError.new "Failed to obtain access token" if result.status == 401 or result.status == 422 or result.body.empty?
  JSON.parse(result.body)
end

#need_new_token?Boolean

Returns:

  • (Boolean)


40
41
42
43
44
45
46
# File 'lib/faraday/panoptes/client_credentials_authentication.rb', line 40

def need_new_token?
  return true unless @current_token

  created_at = Time.at(@current_token.fetch("created_at"))
  expires_by = created_at + @current_token.fetch("expires_in")
  Time.now > expires_by
end