Module: Wso2Toolbox::TokenManager::Adapters::LocalFileAdapter

Defined in:
lib/wso2_toolbox/token_manager/adapters/local_file_adapter.rb

Constant Summary collapse

TOKEN_DELAY =
5.minutes

Class Method Summary collapse

Class Method Details

.active_token?Boolean

Returns:

  • (Boolean)


35
36
37
38
# File 'lib/wso2_toolbox/token_manager/adapters/local_file_adapter.rb', line 35

def active_token?
  return false unless read(:token_time_for_job)
  Time.parse(read(:token_time_for_job)) - TOKEN_DELAY > Time.now
end

.file_pathObject



61
62
63
# File 'lib/wso2_toolbox/token_manager/adapters/local_file_adapter.rb', line 61

def file_path
  @file_path ||= 'tmp/localstorage.json'
end

.generate_tokenObject



14
15
16
17
# File 'lib/wso2_toolbox/token_manager/adapters/local_file_adapter.rb', line 14

def generate_token
  new_token unless active_token?
  store_token(read(:token_for_job))
end

.local_storage {|local_store| ... } ⇒ Object

Yields:

  • (local_store)


48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/wso2_toolbox/token_manager/adapters/local_file_adapter.rb', line 48

def local_storage
  file = File.open(file_path, 'a+').read
  file_read = file == '' ? '{}' : file

  local_store = JSON.parse(file_read)
  yield(local_store)

  File.open(file_path, 'w+') do |f|
    f.write(local_store.to_json)
    f.rewind
  end
end

.new_tokenObject



21
22
23
24
25
26
27
28
29
# File 'lib/wso2_toolbox/token_manager/adapters/local_file_adapter.rb', line 21

def new_token
  token_params =
    Wso2Toolbox::TokenManager::ApiManagerService.create_token

  write(:token_time_for_job,
        Time.now + token_params[:expires_in].to_i.seconds)
  write(:token_for_job,
        "#{token_params[:token_type]} #{token_params[:access_token]}")
end

.read(key) ⇒ Object



40
41
42
# File 'lib/wso2_toolbox/token_manager/adapters/local_file_adapter.rb', line 40

def read(key)
  local_storage { |store| return store.try(:[], key.to_s) }
end

.store_token(token) ⇒ Object



31
32
33
# File 'lib/wso2_toolbox/token_manager/adapters/local_file_adapter.rb', line 31

def store_token(token)
  RequestStore.store[:token] = token
end

.write(key, value) ⇒ Object



44
45
46
# File 'lib/wso2_toolbox/token_manager/adapters/local_file_adapter.rb', line 44

def write(key, value)
  local_storage { |store| store[key] = value }
end