class Simpal::Middleware::Authorization
Requests an OAuth2 access token for a `Simpal::Client`, adding the resulting access token into each request.
Attributes
access_token[R]
@return [String] The access token to include in each request.
access_token_expires_at[R]
@return [Time] The time at which the access token expires.
client[R]
@return [Simpal::Client] The client which we're handling the 'Authorization' header for.
Public Class Methods
new(app, client)
click to toggle source
Calls superclass method
# File lib/simpal/middleware/authorization.rb, line 20 def initialize(app, client) super(app) @client = client end
Public Instance Methods
call(request_env)
click to toggle source
Calls superclass method
# File lib/simpal/middleware/authorization.rb, line 25 def call(request_env) retryable = true refresh_access_token begin request_env[:request_headers].merge!('Authorization' => "Bearer #{access_token}") super(request_env) rescue Faraday::UnauthorizedError raise unless retryable retryable = false refresh_access_token! retry end end
Private Instance Methods
connection()
click to toggle source
# File lib/simpal/middleware/authorization.rb, line 43 def connection @connection ||= Faraday.new(client.service_url, headers: client.headers) do |connection| connection.use Faraday::Request::UrlEncoded connection.use Faraday::Response::RaiseError connection.use FaradayMiddleware::ParseJson connection.request(:basic_auth, client.client_id, client.client_secret) end end
expiry_base_date_for(response)
click to toggle source
# File lib/simpal/middleware/authorization.rb, line 52 def expiry_base_date_for(response) Time.httpdate(response.headers['date']) rescue StandardError Time.now end
refresh_access_token()
click to toggle source
# File lib/simpal/middleware/authorization.rb, line 64 def refresh_access_token return if access_token && access_token_expires_at && (access_token_expires_at - Time.now) >= 1 refresh_access_token! end
refresh_access_token!()
click to toggle source
# File lib/simpal/middleware/authorization.rb, line 58 def refresh_access_token! response = connection.post('/v1/oauth2/token', grant_type: :client_credentials) @access_token = response.body['access_token'] @access_token_expires_at = expiry_base_date_for(response) + response.body['expires_in'].to_i end