Class: Booqable::Middleware::Auth::OAuth

Inherits:
Base
  • Object
show all
Defined in:
lib/booqable/middleware/auth/oauth.rb

Overview

Faraday middleware for OAuth2 authentication

This middleware handles OAuth2 token-based authentication for HTTP requests. It automatically manages access tokens, refreshing them when expired, and adds the Bearer token to the Authorization header.

Examples:

Adding to Faraday middleware stack

builder.use Booqable::Middleware::Auth::OAuth,
  client_id: "your_client_id",
  client_secret: "your_client_secret",
  api_endpoint: "https://company.booqable.com/api/v4/oauth/token",
  read_token: -> { stored_token },
  write_token: ->(token) { store_token(token) }

Instance Method Summary collapse

Constructor Details

#initialize(app, options = {}) ⇒ OAuth

Initialize the OAuth authentication middleware

Parameters:

  • app (#call)

    The next middleware in the Faraday stack

  • options (Hash) (defaults to: {})

    Configuration options

Options Hash (options):

  • :client_id (String)

    OAuth client ID

  • :client_secret (String)

    OAuth client secret

  • :api_endpoint (String)

    API endpoint URL for the OAuth provider

  • :read_token (Proc)

    Proc to read stored token

  • :write_token (Proc)

    Proc to store new token

  • :around_refresh_token (Proc, nil)

    Optional callable invoked with a block around the read+check+refresh sequence. The host application can use it to serialize concurrent refreshes (e.g. wrap the block in a database transaction + advisory lock).

Raises:

  • (KeyError)

    If required options are not provided



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/booqable/middleware/auth/oauth.rb', line 32

def initialize(app, options = {})
  super(app)

  @client_id = options.fetch(:client_id)
  @client_secret = options.fetch(:client_secret)
  @api_endpoint = options.fetch(:api_endpoint)
  @read_token = options.fetch(:read_token)
  @write_token = options.fetch(:write_token)
  @around_refresh_token = options[:around_refresh_token]

  @client = OAuthClient.new(
    client_id: @client_id,
    client_secret: @client_secret,
    api_endpoint: @api_endpoint,
  )
end

Instance Method Details

#call(env) ⇒ Faraday::Response

Process the HTTP request and add OAuth authentication

Retrieves the stored access token, refreshes it if expired, and adds it to the Authorization header. Then passes the request to the next middleware in the stack.

Parameters:

  • env (Faraday::Env)

    The request environment

Returns:

  • (Faraday::Response)

    The response from the next middleware



57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/booqable/middleware/auth/oauth.rb', line 57

def call(env)
  around_refresh_token do
    @token = @client.get_access_token_from_hash(@read_token.call)

    if @token.expired? || @token.expires_at.nil?
      @token = refresh_token!
    end
  end

  env.request_headers["Authorization"] ||= "Bearer #{@token.token}"

  @app.call(env)
end