Class: Craigslist::API::TokenProvider

Inherits:
Object
  • Object
show all
Defined in:
lib/craigslist/api/token_provider.rb

Overview

Acquires and caches the OAuth2 access token used by the JSON API.

Tokens live an hour. This holds one per client instance, guarded by a mutex so concurrent callers on a shared client cannot stampede the token endpoint or read a half-replaced token. Deliberately an instance, not a class-level cache: one process may talk to several accounts.

Constant Summary collapse

TOKEN_PATH =

OAuth2 token endpoint.

"/bulkpost/oauth/access-token"

Instance Method Summary collapse

Constructor Details

#initialize(config:, connection:) ⇒ TokenProvider

Returns a new instance of TokenProvider.

Parameters:

  • config (Configuration)
  • connection (Faraday::Connection)

    pointed at the bapi host



20
21
22
23
24
25
# File 'lib/craigslist/api/token_provider.rb', line 20

def initialize(config:, connection:)
  @config = config
  @connection = connection
  @mutex = Mutex.new
  @token = nil
end

Instance Method Details

#invalidate!void

This method returns an undefined value.

Drops the cached token so the next call re-authenticates.

Called after a 401, which can happen before the recorded expiry if the token was revoked server-side.



43
44
45
# File 'lib/craigslist/api/token_provider.rb', line 43

def invalidate!
  @mutex.synchronize { @token = nil }
end

#tokenAccessToken

Returns a live token, fetching or refreshing if needed.

Returns:



30
31
32
33
34
35
# File 'lib/craigslist/api/token_provider.rb', line 30

def token
  @mutex.synchronize do
    @token = fetch if @token.nil? || @token.expired?
    @token
  end
end