Skip to content

Commit

Permalink
👔 Zoho connection mutex refresh token (#18)
Browse files Browse the repository at this point in the history
* reset authorization header on retry request

* refactor with authorization request

* mutext refresh token

* mutext on refresh token

* rubocop fixes
  • Loading branch information
qen authored Jul 19, 2024
1 parent bba6c42 commit 80b6d62
Showing 1 changed file with 21 additions and 10 deletions.
31 changes: 21 additions & 10 deletions lib/zoho_hub/connection.rb
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ def initialize(access_token: nil, api_domain: nil, api_version: nil, expires_in:
@api_domain = api_domain || self.class.infer_api_domain
@api_version = api_version || ZohoHub.configuration.api_version
@refresh_token ||= refresh_token # do not overwrite if it's already set
@mutex = Mutex.new
end

def get(path, params = {})
Expand Down Expand Up @@ -85,32 +86,42 @@ def log(text)
puts Rainbow("[ZohoHub] #{text}").magenta.bright
end

private
def refresh_token!
was_locked = @mutex.locked?
@mutex.synchronize do
next if was_locked

def with_refresh
adapter.headers['Authorization'] = authorization if access_token?
params = ZohoHub::Auth.refresh_token(@refresh_token)
@on_refresh_cb.call(params) if @on_refresh_cb
@access_token = params[:access_token] unless @access_token.respond_to?(:call)
end
end

private

http_response = yield
def with_refresh(&block)
http_response = with_authorization(&block)

response = Response.new(http_response.body)

# Try to refresh the token and try again
if (response.invalid_token? || response.authentication_failure?) && refresh_token?
log "Refreshing outdated token... #{@access_token}"
params = ZohoHub::Auth.refresh_token(@refresh_token)

@on_refresh_cb.call(params) if @on_refresh_cb

@access_token = params[:access_token] unless @access_token.respond_to?(:call)
refresh_token!

http_response = yield
http_response = with_authorization(&block)
elsif response.authentication_failure?
raise ZohoAPIError, response.msg
end

http_response
end

def with_authorization
adapter.headers['Authorization'] = authorization if access_token?
yield
end

def base_url
Addressable::URI.join(api_domain, BASE_PATH, api_version).to_s
end
Expand Down

0 comments on commit 80b6d62

Please sign in to comment.