I have a class with different methods but on these methods i need to do a check on the access token before doing some calls
class SomeClass
def initialize
@client = SomeModule::Client.new
end
def get_intervention_chart(subId:, projectId:, interventionId:)
@client.check_presence_of_access_token()
SomeModule::Service::Project.new(@client).get_intervention_chart(subId: subId, projectId: projectId, interventionId: interventionId)
end
def get_intervention_documents(subId:, projectId:, interventionId:)
@client.check_presence_of_access_token()
SomeModule::Service::Project.new(@client).get_intervention_documents(subId: subId, projectId: projectId, interventionId: interventionId)
end
end
As you can see, i call the method "check_presence_of_access_token" which check if the access token is there and if it's good to go, if not it gets another one and stock it in a file.
There is my Client class :
class Client
class Configuration
attr_accessor :access_token
attr_reader :access_token_path, :endpoint, :client_id, :client_secret, :subId
def initialize
@access_token = ''
@access_token_path = Rails.root.join('tmp/connection_response.json')
@endpoint = ENV['TOKEN_ENDPOINT']
@client_id = ENV['CLIENT_ID']
@client_secret = ENV['CLIENT_SECRET']
@subId = "SOME_ID"
end
end
def initialize
@configuration = Configuration.new
end
# Check if the file 'connection_response' is present and if the token provided is still valid (only 30 min)
def check_presence_of_access_token
if File.exist?(self.configuration.access_token_path.to_s)
access_token = JSON.parse(File.read(self.configuration.access_token_path.to_s))["access_token"]
if access_token
jwt_decoded = JWT.decode(access_token, nil, false).first
# we want to check if the token will be valid in 60s to avoid making calls with expired token
if jwt_decoded["exp"] > (DateTime.now.to_i + 60)
self.configuration.access_token = access_token
return
end
end
end
get_token()
end
def get_token
config_hash = Hash.new {}
config_hash["grant_type"] = "client_credentials"
config_hash["client_id"] = self.configuration.client_id
config_hash["client_secret"] = self.configuration.client_secret
response = RestClient.post(self.configuration.endpoint, config_hash, headers: { 'Content-Type' => 'application/x-www-form-urlencoded' })
response_body = JSON.parse(response.body)
self.configuration.access_token = response_body["access_token"]
stock_jwt(response_body.to_json)
end
def stock_jwt(response_body)
File.open(self.configuration.access_token_path.to_s, 'w+') do |file|
file.write(response_body)
end
end
end
I don't know how to refactor this, can you help me ?