Last active
March 28, 2023 16:58
-
-
Save bhargavrpatel/79132d53557cf0485b235b17525549d7 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class TokenStore | |
include Singleton | |
attr_reader :params | |
def initialize | |
@params = { | |
client_id: ENV['PUBLIX_AUTH_CLIENT_ID'], | |
client_secret: ENV['PUBLIX_AUTH_CLIENT_SECRET'], | |
grant_type: "client_credentials", | |
scope: ENV['PUBLIX_AUTH_PARAM_SCOPE'], | |
requested_token_use: ENV['PUBLIX_AUTH_REQUESTED_TOKEN_USE'], | |
}.compact | |
end | |
def token | |
cached_token = cached | |
if cached_token.present? | |
puts "Returning cached token" | |
return cached_token | |
end | |
puts "Fetching a new token" | |
fetch_token! | |
end | |
def cached | |
token_and_expiry = Rails.cache.read(cache_key) | |
return nil unless token_and_expiry.present? | |
token, expires_at = token_and_expiry | |
# In reality, we do a jitter based check, but this is being ignored for simplicity for testing | |
return token if (utc_now + 120) > expires_at | |
end | |
def fetch_token! | |
response = Faraday.post(ENV['PUBLIX_AUTH_URL'], params) do |f| | |
f.response :json | |
f.request :url_encoded | |
end | |
access_token = response.body['access_token'] | |
# In reality, we do a jitter based reduction here but this is being ignored for simplicity for testing | |
expires_in = response.body["expires_in"].to_i.seconds | |
expires_at = (utc_now + expires_in).to_i | |
Rails.cache.write(cache_key, [access_token, expires_at]) | |
access_token | |
end | |
def cache_key | |
Digest::SHA256.hexdigest("access_tokens/publix/dev_test") | |
end | |
def utc_now | |
Time.now.utc.to_i | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment