Class: Booqable::Middleware::Auth::OAuth
- 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.
Instance Method Summary collapse
-
#call(env) ⇒ Faraday::Response
Process the HTTP request and add OAuth authentication.
-
#initialize(app, options = {}) ⇒ OAuth
constructor
Initialize the OAuth authentication middleware.
Constructor Details
#initialize(app, options = {}) ⇒ OAuth
Initialize the OAuth authentication middleware
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, = {}) super(app) @client_id = .fetch(:client_id) @client_secret = .fetch(:client_secret) @api_endpoint = .fetch(:api_endpoint) @read_token = .fetch(:read_token) @write_token = .fetch(:write_token) @around_refresh_token = [: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.
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 |