require 'soar_xt' require 'jwt' require 'securerandom' module SoarAuthenticationToken class TokenGenerator DEFAULT_CONFIGURATION = { 'mode' => 'remote', 'url' => '' } unless defined? DEFAULT_CONFIGURATION; DEFAULT_CONFIGURATION.freeze def initialize(configuration) @configuration = merge_with_default_configuration(configuration) validate_configuration @private_key = OpenSSL::PKey::EC.new(@configuration['private_key']) end def generate(authenticated_identifier:) encode(payload(authenticated_identifier)) end private def payload(authenticated_identifier) { 'authenticated_identifier' => authenticated_identifier, 'issue_time' => Time.now.utc.iso8601(3), 'nounce' => SecureRandom.hex(32) } end def encode(payload) JWT.encode(payload, @private_key, 'ES512') end def validate_configuration raise "'mode' must be configured" unless @configuration['mode'] raise "'mode' must be configured as either 'local' or 'remote'" unless ['local','remote'].include?(@configuration['mode']) end def merge_with_default_configuration(configuration) configuration = {} unless configuration Hash.deep_merge(DEFAULT_CONFIGURATION,configuration) end end end