Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 20 additions & 3 deletions lib/hubspot/auth/management/token.ex
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,35 @@ defmodule Hubspot.Auth.Manage.Token do

use Hubspot.Common.Config

@ttl :timer.seconds(1_800)
# Set TTL to 25 minutes
@ttl :timer.seconds(1_500)

@spec get_client_scopes(any, any) :: {:not_found, any} | {:ok, any} | {:commit, any}
def get_client_scopes(client_code, refresh_token) do
Cachex.fetch(:hubspot_cache, client_code <> "_scopes", fn _key ->
case generate_new_access_token(refresh_token) do
{:ok, %{"scopes" => scopes}} ->
{:commit, scopes, expire: @ttl}

error ->
{:ignore,
"Failed to generate an access token for Hubspot OAuth management API for client with code #{client_code} with error #{inspect(error)}"}
end
end)
|> normalize_cache_fetch()
end

# Hubspot clients are identified by their code(returned after initial authentication flow)
@spec get_client_access_token(any, any) :: {:not_found, any} | {:ok, any}
@spec get_client_access_token(any, any) :: {:not_found, any} | {:ok, any} | {:commit, any}
def get_client_access_token(client_code, refresh_token) do
Cachex.fetch(:hubspot_cache, client_code, fn key ->
Logger.info(
"Hubspot Cache key '#{key}' not found, running fallback for hubspot access token"
)

case generate_new_access_token(refresh_token) do
{:ok, %{"access_token" => access_token}} ->
{:ok, %{"access_token" => access_token, "scopes" => scopes}} ->
Cachex.put(:hubspot_cache, client_code <> "_scopes", scopes, ttl: @ttl)
{:commit, access_token, expire: @ttl}

error ->
Expand Down
4 changes: 4 additions & 0 deletions lib/hubspot/common/api.ex
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,10 @@ defmodule Hubspot.Common.API do
defp decode_response({:error, %Mint.TransportError{reason: reason} = error}),
do: {:error, %{status: nil, body: "#{reason}: #{Exception.message(error)}", headers: nil}}

defp decode_response(%Finch.Response{status: status, body: body, headers: headers} = _response)
when status >= 200 and status < 300 and body == "",
do: {:ok, %{status: status, body: body, headers: headers}}

defp decode_response(%Finch.Response{status: status, body: body, headers: headers} = _response)
when status >= 200 and status < 300,
do: {:ok, %{status: status, body: Jason.decode!(body), headers: headers}}
Expand Down
Loading
Loading