class Faraday::Panoptes::ClientCredentialsAuthentication

Public Class Methods

new(app, url:, client_id:, client_secret:) click to toggle source
Calls superclass method
# 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

Public Instance Methods

access_token() click to toggle source
# 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_header() click to toggle source
# File lib/faraday/panoptes/client_credentials_authentication.rb, line 28
def authorization_header
  "Bearer #{access_token}"
end
call(env) click to toggle source
# File lib/faraday/panoptes/client_credentials_authentication.rb, line 23
def call(env)
  env[:request_headers]["Authorization"] = authorization_header
  @app.call(env)
end
get_token() click to toggle source
# 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?() click to toggle source
# 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