Module: HermesAPI::BearerAuth

Defined in:
lib/hermes_api/bearer_auth.rb

Instance Method Summary collapse

Instance Method Details

#clear_token_cache(client_id, client_secret) ⇒ Object



21
22
23
24
# File 'lib/hermes_api/bearer_auth.rb', line 21

def clear_token_cache(client_id, client_secret)
  cache_key = "HermesAPI/#{client_id}/#{client_secret}/#{oauth_audience}/oauth_token"
  HermesAPI.cache.delete(cache_key)
end

#fetch_token(client_id, client_secret) ⇒ Object



26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/hermes_api/bearer_auth.rb', line 26

def fetch_token(client_id, client_secret)
  cache_key = "HermesAPI/#{client_id}/#{client_secret}/#{oauth_audience}/oauth_token"
  cached_token = HermesAPI.cache.read(cache_key)
  return cached_token if cached_token

  response = OAuth.create(audience: oauth_audience, client_id: client_id, client_secret: client_secret)
  HermesAPI.cache.write(
    cache_key,
    response.access_token,
    expires_in: response.expires_in - 15 # clear cache earlier
  )
  response.access_token
end

#oauth_audienceObject



17
18
19
# File 'lib/hermes_api/bearer_auth.rb', line 17

def oauth_audience
  prefix.match(/^\/?([^\/]*)/).captures.first
end

#with_oauth_session(api_key, client_id, client_secret) ⇒ Object



3
4
5
6
7
8
9
10
11
12
13
14
15
# File 'lib/hermes_api/bearer_auth.rb', line 3

def with_oauth_session(api_key, client_id, client_secret)
  existing_apikey = headers["apikey"]
  existing_bearer_token = connection.bearer_token
  headers["apikey"] = api_key
  connection.bearer_token = fetch_token(client_id, client_secret)
  response = yield
  headers["apikey"] = existing_apikey
  connection.bearer_token = existing_bearer_token
  response
rescue ActiveResource::UnauthorizedAccess => e
  clear_token_cache(client_id, client_secret)
  raise e
end