require 'json' require 'authenticated_client' module SoarAuthenticationToken class RemoteTokenGenerator def initialize(configuration) @configuration = configuration set_configuration_defaults validate_configuration end def inject_store_provider(store_provider) #ignore the store provider since this generator does not use a store end def generate(authenticated_identifier:, flow_identifier: nil) attempt = 0 begin Timeout::timeout(@configuration['timeout']) do client = authenticated_client(authenticated_identifier,flow_identifier) validate_and_extract_token_from_response(client.request) end rescue Timeout::Error attempt += 1 retry if attempt < @configuration['attempts'] raise end end private def set_configuration_defaults @configuration['timeout'] ||= 3 @configuration['attempts'] ||= 2 end def authenticated_client(authenticated_identifier,flow_identifier) client = AuthenticatedClient::Client.new client.url = @configuration['generator-url'] client.token = @configuration['generator-client-auth-token'] client.verb = :post client.parameters = {'flow_identifier' => flow_identifier} client.body = { 'authenticated_identifier' => authenticated_identifier } client end def validate_and_extract_token_from_response(response) raise "Failure generating token with token generation service. Code #{response.code}" if '200' != response.code body = JSON.parse(response.body) raise 'Failure generating token by token service' if 'success' != body['status'] raise 'Token service did not provide token' if body['data'].nil? or body['data']['token'].nil? body['data']['token'] end def validate_configuration raise "'generator-url' must be configured" unless @configuration['generator-url'] raise "'timeout' must be configured" unless @configuration['timeout'] raise "'timeout' must be an integer" unless Integer(@configuration['timeout']) raise "'attempts' must be configured" unless @configuration['attempts'] raise "'attempts' must be an integer" unless Integer(@configuration['attempts']) end end end