diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..a60266b --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,120 @@ +name: Release Ruby Connector + +on: + push: + branches: + - main + +jobs: + create-release: + name: Create GitHub Release + runs-on: ubuntu-latest + steps: + - name: Checkout repository + uses: actions/checkout@v4 + + - name: Extract SDK version from Ruby file + id: extract_version + run: | + # Extract SDK version from Ruby file + SDK_VERSION=$(ruby -e " + require './lib/queueit_knownuserv3/user_in_queue_service' + puts QueueIt::UserInQueueService::SDK_VERSION_NO + ") + + if [ -z \"$SDK_VERSION\" ]; then + echo \"Error: Could not extract SDK version.\" + exit 1 + fi + + # Generate a build suffix with date + commit SHA short + BUILD_DATE=$(date +%Y%m%d) + SHORT_SHA=$(echo $GITHUB_SHA | cut -c1-7) + BUILD_SUFFIX=\"$BUILD_DATE-$SHORT_SHA\" + + echo "SDK_VERSION=$SDK_VERSION" >> $GITHUB_ENV + echo "BUILD_SUFFIX=$BUILD_SUFFIX" >> $GITHUB_ENV + echo "VERSION_TAG=$SDK_VERSION" >> $GITHUB_ENV + + echo "Extracted SDK Version: $SDK_VERSION" + echo "Build Suffix: $BUILD_SUFFIX" + echo "Full Tag: $SDK_VERSION-$BUILD_SUFFIX" + + # Find the PR associated with this commit (merge, squash or rebase) + - name: Get PR for this commit + id: pr + uses: actions/github-script@v7 + with: + script: | + const {owner, repo} = context.repo; + const sha = context.sha; + // REST: list PRs associated with a commit + const res = await github.request('GET /repos/{owner}/{repo}/commits/{ref}/pulls', { + owner, repo, ref: sha, + headers: { accept: 'application/vnd.github+json' } + }); + + if (!res.data.length) { + core.notice('No PR associated with this commit. Falling back to default body.'); + core.setOutput('number', ''); + core.setOutput('title', ''); + core.setOutput('body', ''); + } else { + // If multiple, grab the first (usually the relevant one for the head commit) + const pr = res.data[0]; + core.setOutput('number', String(pr.number)); + core.setOutput('title', pr.title ?? ''); + core.setOutput('body', pr.body ?? ''); + } + + # Prepare PR body for release notes + - name: Write PR body to file + run: | + cat <<'EOF' > pr_body.md + ${{ steps.pr.outputs.body }} + EOF + + - name: Create release asset archive + run: | + mkdir -p release-assets + tar -czf "release-assets/ruby-connector-${{ env.VERSION_TAG }}.tar.gz" \ + lib/ \ + test/ \ + bin/ \ + *.gemspec \ + Gemfile \ + Rakefile \ + README.md \ + license.txt + + - name: Show debug release variables + run: | + echo "SDK_VERSION: ${{ env.SDK_VERSION }}" + echo "BUILD_SUFFIX: ${{ env.BUILD_SUFFIX }}" + echo "VERSION_TAG: ${{ env.VERSION_TAG }}" + echo "PR_NUMBER: ${{ steps.pr.outputs.number }}" + echo "PR_TITLE: ${{ steps.pr.outputs.title }}" + echo "RELEASE_NAME: ${{ env.RELEASE_NAME }}" + echo "Asset path: release-assets/ruby-connector-${{ env.VERSION_TAG }}.tar.gz" + + - name: Create Git tag + run: | + git config user.name "$QUEUEIT_GITHUB_NAME" + git config user.email "$QUEUEIT_GITHUB_EMAIL" + git tag "${{ env.VERSION_TAG }}" + git push origin "${{ env.VERSION_TAG }}" + + - name: Create GitHub Release + uses: softprops/action-gh-release@v2 + with: + tag_name: ${{ env.VERSION_TAG }} + name: ${{ env.VERSION_TAG }} + body_path: pr_body.md + files: release-assets/ruby-connector-${{ env.VERSION_TAG }}.tar.gz + + - name: Display release links + run: | + echo "Release creation completed. Check:" + echo "- Tags: https://github.com/${{ github.repository }}/tags" + echo "- Releases: https://github.com/${{ github.repository }}/releases" + echo "- Latest Release: https://github.com/${{ github.repository }}/releases/tag/${{ env.VERSION_TAG }}" diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..e915029 --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +################################################################################ +# This .gitignore file was automatically created by Microsoft(R) Visual Studio. +################################################################################ + +/.vs diff --git a/README.md b/README.md index aada9d0..540a5ce 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ # KnownUser.V3.RubyOnRails Before getting started please read the [documentation](https://github.com/queueit/Documentation/tree/main/serverside-connectors) to get acquainted with server-side connectors. -This connector supports Ruby v.1.9.3+ and Rails v.3.2+. +This connector supports Ruby v.3.4+ and Rails v.5.0.5+. ## Installation Queue-it KnownUser V3 is distributed as a gem, which is how it should be used in your app. @@ -40,10 +40,9 @@ class ResourceController < ApplicationController #requestUriNoToken.host = "INSERT-REPLACEMENT-HOST-HERE" #requestUrlWithoutToken = requestUriNoToken.to_s - queueitToken = request.query_parameters[QueueIt::KnownUser::QUEUEIT_TOKEN_KEY.to_sym] + queueitToken = QueueIt::Utils::getParameterByName(requestUrl, QueueIt::KnownUser::QUEUEIT_TOKEN_KEY) - # Initialize the SDK with the rails http context (must be done before calling validateRequestByIntegrationConfig) - QueueIt::HttpContextProvider::setHttpContext(QueueIt::RailsHttpContext.new(request)) + httpContextProvider = QueueIt::HttpContextProvider.new(QueueIt::RailsHttpContext.new(request)) # Verify if the user has been through the queue validationResult = QueueIt::KnownUser.validateRequestByIntegrationConfig( @@ -51,7 +50,8 @@ class ResourceController < ApplicationController queueitToken, configJson, customerId, - secretKey) + secretKey, + httpContextProvider) if(validationResult.doRedirect) #Adding no cache headers to prevent browsers to cache requests @@ -63,19 +63,21 @@ class ResourceController < ApplicationController if(!validationResult.isAjaxResult) # Send the user to the queue - either becuase hash was missing or becuase is was invalid redirect_to validationResult.redirectUrl + return else - head :ok ajaxQueueRedirectHeaderName = validationResult.getAjaxQueueRedirectHeaderKey() response.headers[ajaxQueueRedirectHeaderName] = validationResult.getAjaxRedirectUrl() response.headers["Access-Control-Expose-Headers"] = ajaxQueueRedirectHeaderName + head :ok + return end else # Request can continue, we remove queueittoken from url to avoid sharing of user specific token if(requestUrl != requestUrlWithoutToken && validationResult.actionType == "Queue") redirect_to requestUrlWithoutToken + return end end - rescue StandardError => stdErr # There was an error validating the request # Use your own logging framework to log the error @@ -110,10 +112,9 @@ class ResourceController < ApplicationController # eventConfig.layoutName = "NameOfYourCustomLayout" # Optional - Name of the queue layout. If unspecified then settings from Event will be used. requestUrl = request.original_url - queueitToken = request.query_parameters[QueueIt::KnownUser::QUEUEIT_TOKEN_KEY.to_sym] + queueitToken = QueueIt::Utils::getParameterByName(requestUrl, QueueIt::KnownUser::QUEUEIT_TOKEN_KEY) - # Initialize the SDK with the rails http context (must be done before calling validateRequestByIntegrationConfig) - QueueIt::HttpContextProvider::setHttpContext(QueueIt::RailsHttpContext.new(request)) + httpContextProvider = QueueIt::HttpContextProvider.new(QueueIt::RailsHttpContext.new(request)) # Verify if the user has been through the queue validationResult = QueueIt::KnownUser.resolveQueueRequestByLocalConfig( @@ -121,7 +122,8 @@ class ResourceController < ApplicationController queueitToken, eventConfig, customerId, - secretKey) + secretKey, + httpContextProvider) if(validationResult.doRedirect) #Adding no cache headers to prevent browsers to cache requests @@ -132,11 +134,13 @@ class ResourceController < ApplicationController if(!validationResult.isAjaxResult) # Send the user to the queue - either becuase hash was missing or becuase is was invalid redirect_to validationResult.redirectUrl + return else - head :ok ajaxQueueRedirectHeaderName = validationResult.getAjaxQueueRedirectHeaderKey() response.headers[ajaxQueueRedirectHeaderName] = validationResult.getAjaxRedirectUrl() response.headers["Access-Control-Expose-Headers"] = ajaxQueueRedirectHeaderName + head :ok + return end else # Request can continue - we remove queueittoken form querystring parameter to avoid sharing of user specific token @@ -145,9 +149,9 @@ class ResourceController < ApplicationController if(requestUrl != requestUrlWithoutToken && validationResult.actionType == "Queue") redirect_to requestUrlWithoutToken + return end end - rescue StandardError => stdErr # There was an error validating the request # Use your own logging framework to log the error @@ -158,6 +162,7 @@ class ResourceController < ApplicationController end ``` + ## Advanced Features ### Request body trigger @@ -184,5 +189,5 @@ end Then, on each request, before calling the any of the SDK methods, you should initialize the SDK with your custom RailsHttpContext implementation, instead of the RailsHttpContext: ```ruby -QueueIt::HttpContextProvider::setHttpContext(RailsHttpContextWithRequestBody.new(request)) +httpContextProvider = QueueIt::HttpContextProvider.new(QueueIt::RailsHttpContextWithRequestBody.new(request)) ``` \ No newline at end of file diff --git a/bin/console b/bin/console old mode 100755 new mode 100644 diff --git a/bin/setup b/bin/setup old mode 100755 new mode 100644 diff --git a/lib/queueit_knownuserv3/httpcontext_provider.rb b/lib/queueit_knownuserv3/httpcontext_provider.rb index 01c1f29..4e281c2 100644 --- a/lib/queueit_knownuserv3/httpcontext_provider.rb +++ b/lib/queueit_knownuserv3/httpcontext_provider.rb @@ -1,6 +1,5 @@ module QueueIt class IHttpContext - def userAgent raise 'userAgent not implemented' end @@ -24,70 +23,52 @@ def cookieManager def requestBodyAsString raise 'requestBodyAsString not implemented' end - end class RailsHttpContext < IHttpContext - @request - def initialize(request) @request = request end def userAgent - return @request.user_agent + @request.user_agent end def headers - return @request.headers + @request.headers end def url - return @request.env["rack.url_scheme"] + "://" + @request.env["HTTP_HOST"] + @request.original_fullpath + @request.env["rack.url_scheme"] + "://" + @request.env["HTTP_HOST"] + @request.original_fullpath end def userHostAddress - return @request.remote_ip + @request.remote_ip end def cookieManager - cookieManager = CookieManager.new(@request.cookie_jar) - return cookieManager + CookieManager.new(@request.cookie_jar) end def requestBodyAsString - return '' + '' end - end - # Used to initialize SDK for each request - class SDKInitializer - def self.setHttpContext(httpContext) - if (httpContext.class < IHttpContext) - HttpContextProvider.setHttpContext(httpContext) - else - raise "httpContext must be a subclass of IHttpContext (e.g. MyHttpContext < IHttpContext)" - end - end + class HttpContextProvider - end + def initialize(httpContext, userInQueueService = nil) + @httpContext = httpContext + @userInQueueService = userInQueueService + end - class HttpContextProvider - @@httpContext - - def self.httpContext - if (defined?(@@httpContext)) - return @@httpContext - else - raise "Please initialize the SDK using SDKInitializer.setHttpContext(httpContext) method" - end + def httpContext + @httpContext end - def self.setHttpContext(httpContext) - @@httpContext = httpContext + def userInQueueService + @userInQueueService end - end -end +end \ No newline at end of file diff --git a/lib/queueit_knownuserv3/known_user.rb b/lib/queueit_knownuserv3/known_user.rb index d5e58ec..649907d 100644 --- a/lib/queueit_knownuserv3/known_user.rb +++ b/lib/queueit_knownuserv3/known_user.rb @@ -2,179 +2,12 @@ require 'json' module QueueIt - class KnownUser QUEUEIT_TOKEN_KEY = "queueittoken" QUEUEIT_DEBUG_KEY = "queueitdebug" QUEUEIT_AJAX_HEADER_KEY = "x-queueit-ajaxpageurl" - @@userInQueueService = nil - def self.getUserInQueueService() - if (@@userInQueueService == nil) - return UserInQueueService.new(UserInQueueStateCookieRepository.new(HttpContextProvider.httpContext.cookieManager)) - end - - return @@userInQueueService - end - private_class_method :getUserInQueueService - - def self.isQueueAjaxCall - headers = HttpContextProvider.httpContext.headers - return headers[QUEUEIT_AJAX_HEADER_KEY] != nil - end - private_class_method :isQueueAjaxCall - - def self.generateTargetUrl(originalTargetUrl) - unless isQueueAjaxCall() - return originalTargetUrl - end - headers = HttpContextProvider.httpContext.headers - return CGI::unescape(headers[QUEUEIT_AJAX_HEADER_KEY]) - end - private_class_method :generateTargetUrl - - def self.convertToInt(value) - begin - converted = Integer(value) - rescue - converted = 0 - end - return converted - end - private_class_method :convertToInt - - def self.logMoreRequestDetails(debugEntries) - httpContext = HttpContextProvider.httpContext - headers = httpContext.headers - - debugEntries["ServerUtcTime"] = Time.now.utc.iso8601 - debugEntries["RequestIP"] = httpContext.userHostAddress - debugEntries["RequestHttpHeader_Via"] = headers["via"] - debugEntries["RequestHttpHeader_Forwarded"] = headers["forwarded"] - debugEntries["RequestHttpHeader_XForwardedFor"] = headers["x-forwarded-for"] - debugEntries["RequestHttpHeader_XForwardedHost"] = headers["x-forwarded-host"] - debugEntries["RequestHttpHeader_XForwardedProto"] = headers["x-forwarded-proto"] - end - private_class_method :logMoreRequestDetails - - def self.setDebugCookie(debugEntries) - if(debugEntries == nil || debugEntries.length == 0) - return - end - - cookieManager = HttpContextProvider.httpContext.cookieManager - cookieValue = '' - debugEntries.each do |entry| - cookieValue << (entry[0].to_s + '=' + entry[1].to_s + '|') - end - cookieValue = cookieValue.chop # remove trailing char - cookieManager.setCookie(QUEUEIT_DEBUG_KEY, cookieValue, nil, nil, false, false) - end - private_class_method :setDebugCookie - - def self._resolveQueueRequestByLocalConfig(targetUrl, queueitToken, queueConfig, customerId, secretKey, debugEntries, isDebug) - - if(isDebug) - debugEntries["SdkVersion"] = UserInQueueService::SDK_VERSION - debugEntries["Runtime"] = getRuntime() - debugEntries["TargetUrl"] = targetUrl - debugEntries["QueueitToken"] = queueitToken - debugEntries["OriginalUrl"] = getRealOriginalUrl() - if(queueConfig == nil) - debugEntries["QueueConfig"] = "NULL" - else - debugEntries["QueueConfig"] = queueConfig.toString() - end - logMoreRequestDetails(debugEntries) - end - - if(Utils.isNilOrEmpty(customerId)) - raise KnownUserError, "customerId can not be nil or empty." - end - - if(Utils.isNilOrEmpty(secretKey)) - raise KnownUserError, "secretKey can not be nil or empty." - end - - if(queueConfig == nil) - raise KnownUserError, "queueConfig can not be nil." - end - - if(Utils.isNilOrEmpty(queueConfig.eventId)) - raise KnownUserError, "queueConfig.eventId can not be nil or empty." - end - - if(Utils.isNilOrEmpty(queueConfig.queueDomain)) - raise KnownUserError, "queueConfig.queueDomain can not be nil or empty." - end - - minutes = convertToInt(queueConfig.cookieValidityMinute) - if(minutes <= 0) - raise KnownUserError, "queueConfig.cookieValidityMinute should be integer greater than 0." - end - - if(![true, false].include? queueConfig.extendCookieValidity) - raise KnownUserError, "queueConfig.extendCookieValidity should be valid boolean." - end - - userInQueueService = getUserInQueueService() - result = userInQueueService.validateQueueRequest(targetUrl, queueitToken, queueConfig, customerId, secretKey) - result.isAjaxResult = isQueueAjaxCall() - - return result - end - private_class_method :_resolveQueueRequestByLocalConfig - - def self._cancelRequestByLocalConfig(targetUrl, queueitToken, cancelConfig, customerId, secretKey, debugEntries, isDebug) - targetUrl = generateTargetUrl(targetUrl) - - if(isDebug) - debugEntries["SdkVersion"] = UserInQueueService::SDK_VERSION - debugEntries["Runtime"] = getRuntime() - debugEntries["TargetUrl"] = targetUrl - debugEntries["QueueitToken"] = queueitToken - debugEntries["OriginalUrl"] = getRealOriginalUrl() - if(cancelConfig == nil) - debugEntries["CancelConfig"] = "NULL" - else - debugEntries["CancelConfig"] = cancelConfig.toString() - end - logMoreRequestDetails(debugEntries) - end - - if(Utils.isNilOrEmpty(targetUrl)) - raise KnownUserError, "targetUrl can not be nil or empty." - end - - if(Utils.isNilOrEmpty(customerId)) - raise KnownUserError, "customerId can not be nil or empty." - end - - if(Utils.isNilOrEmpty(secretKey)) - raise KnownUserError, "secretKey can not be nil or empty." - end - - if(cancelConfig == nil) - raise KnownUserError, "cancelConfig can not be nil." - end - - if(Utils.isNilOrEmpty(cancelConfig.eventId)) - raise KnownUserError, "cancelConfig.eventId can not be nil or empty." - end - - if(Utils.isNilOrEmpty(cancelConfig.queueDomain)) - raise KnownUserError, "cancelConfig.queueDomain can not be nil or empty." - end - - userInQueueService = getUserInQueueService() - result = userInQueueService.validateCancelRequest(targetUrl, cancelConfig, customerId, secretKey) - result.isAjaxResult = isQueueAjaxCall() - - return result - end - private_class_method :_cancelRequestByLocalConfig - - def self.extendQueueCookie(eventId, cookieValidityMinute, cookieDomain, isCookieHttpOnly, isCookieSecure, secretKey) + def self.extendQueueCookie(eventId, cookieValidityMinute, cookieDomain, isCookieHttpOnly, isCookieSecure, secretKey, httpContextProvider) if(Utils.isNilOrEmpty(eventId)) raise KnownUserError, "eventId can not be nil or empty." end @@ -188,11 +21,11 @@ def self.extendQueueCookie(eventId, cookieValidityMinute, cookieDomain, isCookie raise KnownUserError, "cookieValidityMinute should be integer greater than 0." end - userInQueueService = getUserInQueueService() + userInQueueService = getUserInQueueService(httpContextProvider) userInQueueService.extendQueueCookie(eventId, cookieValidityMinute, cookieDomain, isCookieHttpOnly, isCookieSecure, secretKey) end - def self.resolveQueueRequestByLocalConfig(targetUrl, queueitToken, queueConfig, customerId, secretKey) + def self.resolveQueueRequestByLocalConfig(targetUrl, queueitToken, queueConfig, customerId, secretKey, httpContextProvider) debugEntries = Hash.new connectorDiagnostics = ConnectorDiagnostics.verify(customerId, secretKey, queueitToken) @@ -200,19 +33,19 @@ def self.resolveQueueRequestByLocalConfig(targetUrl, queueitToken, queueConfig, return connectorDiagnostics.validationResult end begin - targetUrl = generateTargetUrl(targetUrl) - return _resolveQueueRequestByLocalConfig(targetUrl, queueitToken, queueConfig, customerId, secretKey, debugEntries, connectorDiagnostics.isEnabled) + targetUrl = generateTargetUrl(targetUrl, httpContextProvider) + return _resolveQueueRequestByLocalConfig(targetUrl, queueitToken, queueConfig, customerId, secretKey, debugEntries, connectorDiagnostics.isEnabled, httpContextProvider) rescue Exception => e if(connectorDiagnostics.isEnabled) debugEntries["Exception"] = e.message end raise e ensure - setDebugCookie(debugEntries) + setDebugCookie(debugEntries, httpContextProvider) end end - def self.validateRequestByIntegrationConfig(currentUrlWithoutQueueITToken, queueitToken, integrationConfigJson, customerId, secretKey) + def self.validateRequestByIntegrationConfig(currentUrlWithoutQueueITToken, queueitToken, integrationConfigJson, customerId, secretKey, httpContextProvider) debugEntries = Hash.new customerIntegration = Hash.new connectorDiagnostics = ConnectorDiagnostics.verify(customerId, secretKey, queueitToken) @@ -226,8 +59,8 @@ def self.validateRequestByIntegrationConfig(currentUrlWithoutQueueITToken, queue debugEntries["Runtime"] = getRuntime() debugEntries["PureUrl"] = currentUrlWithoutQueueITToken debugEntries["QueueitToken"] = queueitToken - debugEntries["OriginalUrl"] = getRealOriginalUrl() - logMoreRequestDetails(debugEntries) + debugEntries["OriginalUrl"] = getRealOriginalUrl(httpContextProvider) + logMoreRequestDetails(debugEntries, httpContextProvider) end customerIntegration = JSON.parse(integrationConfigJson) @@ -249,7 +82,7 @@ def self.validateRequestByIntegrationConfig(currentUrlWithoutQueueITToken, queue end integrationEvaluator = IntegrationEvaluator.new - matchedConfig = integrationEvaluator.getMatchedIntegrationConfig(customerIntegration, currentUrlWithoutQueueITToken, HttpContextProvider.httpContext) + matchedConfig = integrationEvaluator.getMatchedIntegrationConfig(customerIntegration, currentUrlWithoutQueueITToken, httpContextProvider.httpContext) if(connectorDiagnostics.isEnabled) if(matchedConfig == nil) @@ -266,17 +99,17 @@ def self.validateRequestByIntegrationConfig(currentUrlWithoutQueueITToken, queue # unspecified or 'Queue' specified if(!matchedConfig.key?("ActionType") || Utils.isNilOrEmpty(matchedConfig["ActionType"]) || matchedConfig["ActionType"].eql?(ActionTypes::QUEUE)) return handleQueueAction(currentUrlWithoutQueueITToken, queueitToken, customerIntegration, - customerId, secretKey, matchedConfig, debugEntries, connectorDiagnostics.isEnabled) + customerId, secretKey, matchedConfig, debugEntries, connectorDiagnostics.isEnabled, httpContextProvider) elsif(matchedConfig["ActionType"].eql?(ActionTypes::CANCEL)) return handleCancelAction(currentUrlWithoutQueueITToken, queueitToken, customerIntegration, - customerId, secretKey, matchedConfig, debugEntries, connectorDiagnostics.isEnabled) + customerId, secretKey, matchedConfig, debugEntries, connectorDiagnostics.isEnabled, httpContextProvider) # for all unknown types default to 'Ignore' else - userInQueueService = getUserInQueueService() + userInQueueService = getUserInQueueService(httpContextProvider) result = userInQueueService.getIgnoreActionResult(matchedConfig["Name"]) - result.isAjaxResult = isQueueAjaxCall() + result.isAjaxResult = isQueueAjaxCall(httpContextProvider) return result end @@ -286,11 +119,11 @@ def self.validateRequestByIntegrationConfig(currentUrlWithoutQueueITToken, queue end raise e ensure - setDebugCookie(debugEntries) + setDebugCookie(debugEntries, httpContextProvider) end end - def self.handleQueueAction(currentUrlWithoutQueueITToken, queueitToken, customerIntegration, customerId, secretKey, matchedConfig, debugEntries, isDebug) + def self.handleQueueAction(currentUrlWithoutQueueITToken, queueitToken, customerIntegration, customerId, secretKey, matchedConfig, debugEntries, isDebug, httpContextProvider) queueConfig = QueueEventConfig.new queueConfig.eventId = matchedConfig["EventId"] queueConfig.layoutName = matchedConfig["LayoutName"] @@ -310,13 +143,13 @@ def self.handleQueueAction(currentUrlWithoutQueueITToken, queueitToken, customer when "EventTargetUrl" targetUrl = '' else - targetUrl = generateTargetUrl(currentUrlWithoutQueueITToken) + targetUrl = generateTargetUrl(currentUrlWithoutQueueITToken, httpContextProvider) end - return _resolveQueueRequestByLocalConfig(targetUrl, queueitToken, queueConfig, customerId, secretKey, debugEntries, isDebug) + return _resolveQueueRequestByLocalConfig(targetUrl, queueitToken, queueConfig, customerId, secretKey, debugEntries, isDebug, httpContextProvider) end - def self.handleCancelAction(currentUrlWithoutQueueITToken, queueitToken, customerIntegration, customerId, secretKey, matchedConfig, debugEntries, isDebug) + def self.handleCancelAction(currentUrlWithoutQueueITToken, queueitToken, customerIntegration, customerId, secretKey, matchedConfig, debugEntries, isDebug, httpContextProvider) cancelConfig = CancelEventConfig.new cancelConfig.eventId = matchedConfig["EventId"] cancelConfig.queueDomain = matchedConfig["QueueDomain"] @@ -326,10 +159,10 @@ def self.handleCancelAction(currentUrlWithoutQueueITToken, queueitToken, custome cancelConfig.version = customerIntegration["Version"] cancelConfig.actionName = matchedConfig["Name"] - return _cancelRequestByLocalConfig(currentUrlWithoutQueueITToken, queueitToken, cancelConfig, customerId, secretKey, debugEntries, isDebug) + return _cancelRequestByLocalConfig(currentUrlWithoutQueueITToken, queueitToken, cancelConfig, customerId, secretKey, debugEntries, isDebug, httpContextProvider) end - def self.cancelRequestByLocalConfig(targetUrl, queueitToken, cancelConfig, customerId, secretKey) + def self.cancelRequestByLocalConfig(targetUrl, queueitToken, cancelConfig, customerId, secretKey, httpContextProvider) debugEntries = Hash.new connectorDiagnostics = ConnectorDiagnostics.verify(customerId, secretKey, queueitToken) @@ -337,26 +170,146 @@ def self.cancelRequestByLocalConfig(targetUrl, queueitToken, cancelConfig, custo return connectorDiagnostics.validationResult end begin - return _cancelRequestByLocalConfig(targetUrl, queueitToken, cancelConfig, customerId, secretKey, debugEntries, connectorDiagnostics.isEnabled) + return _cancelRequestByLocalConfig(targetUrl, queueitToken, cancelConfig, customerId, secretKey, debugEntries, connectorDiagnostics.isEnabled, httpContextProvider) rescue Exception => e if(connectorDiagnostics.isEnabled) debugEntries["Exception"] = e.message end raise e ensure - setDebugCookie(debugEntries) + setDebugCookie(debugEntries, httpContextProvider) end end - def self.getRealOriginalUrl() - return HttpContextProvider.httpContext.url + def self.getRealOriginalUrl(httpContextProvider) + return httpContextProvider.httpContext.url # RoR could modify request.original_url if request contains x-forwarded-host/proto http headers. # Therefore we need this method to be able to access the 'real' original url. #return request.env["rack.url_scheme"] + "://" + request.env["HTTP_HOST"] + request.original_fullpath end - def self.getRuntime() - return RUBY_VERSION.to_s + def self.getRuntime + RUBY_VERSION.to_s + end + + private + + def self.getUserInQueueService(httpContextProvider) + if (httpContextProvider.userInQueueService == nil) + return UserInQueueService.new(UserInQueueStateCookieRepository.new(httpContextProvider.httpContext.cookieManager)) + end + + return httpContextProvider.userInQueueService + end + + def self.isQueueAjaxCall(httpContextProvider) + headers = httpContextProvider.httpContext.headers + + headers[QUEUEIT_AJAX_HEADER_KEY] != nil + end + + def self.generateTargetUrl(originalTargetUrl, httpContextProvider) + return originalTargetUrl unless isQueueAjaxCall(httpContextProvider) + + headers = httpContextProvider.httpContext.headers + + CGI.unescape(headers[QUEUEIT_AJAX_HEADER_KEY]) + end + + def self.convertToInt(value) + Integer(value) rescue 0 + end + + def self.logMoreRequestDetails(debugEntries, httpContextProvider) + headers = httpContextProvider.httpContext.headers + + debugEntries["ServerUtcTime"] = Time.now.utc.iso8601 + debugEntries["RequestIP"] = httpContextProvider.httpContext.userHostAddress + debugEntries["RequestHttpHeader_Via"] = headers["via"] + debugEntries["RequestHttpHeader_Forwarded"] = headers["forwarded"] + debugEntries["RequestHttpHeader_XForwardedFor"] = headers["x-forwarded-for"] + debugEntries["RequestHttpHeader_XForwardedHost"] = headers["x-forwarded-host"] + debugEntries["RequestHttpHeader_XForwardedProto"] = headers["x-forwarded-proto"] + end + + def self.setDebugCookie(debugEntries, httpContextProvider) + return if debugEntries == nil || debugEntries.length == 0 + + cookieManager = httpContextProvider.httpContext.cookieManager + cookieValue = +'' + debugEntries.each do |entry| + cookieValue << (entry[0].to_s + '=' + entry[1].to_s + '|') + end + cookieValue = cookieValue.chop # remove trailing char + cookieManager.setCookie(QUEUEIT_DEBUG_KEY, cookieValue, nil, nil, false, false) + end + + def self._resolveQueueRequestByLocalConfig(targetUrl, queueitToken, queueConfig, customerId, secretKey, debugEntries, isDebug, httpContextProvider) + if(isDebug) + debugEntries["SdkVersion"] = UserInQueueService::SDK_VERSION + debugEntries["Runtime"] = getRuntime + debugEntries["TargetUrl"] = targetUrl + debugEntries["QueueitToken"] = queueitToken + debugEntries["OriginalUrl"] = getRealOriginalUrl(httpContextProvider) + if queueConfig == nil + debugEntries["QueueConfig"] = "NULL" + else + debugEntries["QueueConfig"] = queueConfig.toString + end + logMoreRequestDetails(debugEntries, httpContextProvider) + end + + raise KnownUserError, "customerId can not be nil or empty." if Utils.isNilOrEmpty(customerId) + raise KnownUserError, "secretKey can not be nil or empty." if Utils.isNilOrEmpty(secretKey) + raise KnownUserError, "queueConfig can not be nil." if queueConfig == nil + raise KnownUserError, "queueConfig.eventId can not be nil or empty." if Utils.isNilOrEmpty(queueConfig.eventId) + raise KnownUserError, "queueConfig.queueDomain can not be nil or empty." if Utils.isNilOrEmpty(queueConfig.queueDomain) + + minutes = convertToInt(queueConfig.cookieValidityMinute) + if(minutes <= 0) + raise KnownUserError, "queueConfig.cookieValidityMinute should be integer greater than 0." + end + + if(![true, false].include? queueConfig.extendCookieValidity) + raise KnownUserError, "queueConfig.extendCookieValidity should be valid boolean." + end + + userInQueueService = getUserInQueueService(httpContextProvider) + result = userInQueueService.validateQueueRequest(targetUrl, queueitToken, queueConfig, customerId, secretKey) + result.isAjaxResult = isQueueAjaxCall(httpContextProvider) + + return result + end + + def self._cancelRequestByLocalConfig(targetUrl, queueitToken, cancelConfig, customerId, secretKey, debugEntries, isDebug, httpContextProvider) + targetUrl = generateTargetUrl(targetUrl, httpContextProvider) + + if isDebug + debugEntries["SdkVersion"] = UserInQueueService::SDK_VERSION + debugEntries["Runtime"] = getRuntime() + debugEntries["TargetUrl"] = targetUrl + debugEntries["QueueitToken"] = queueitToken + debugEntries["OriginalUrl"] = getRealOriginalUrl(httpContextProvider) + if(cancelConfig == nil) + debugEntries["CancelConfig"] = "NULL" + else + debugEntries["CancelConfig"] = cancelConfig.toString() + end + logMoreRequestDetails(debugEntries, httpContextProvider) + end + + raise KnownUserError, "targetUrl can not be nil or empty." if Utils.isNilOrEmpty(targetUrl) + raise KnownUserError, "customerId can not be nil or empty." if Utils.isNilOrEmpty(customerId) + raise KnownUserError, "secretKey can not be nil or empty." if Utils.isNilOrEmpty(secretKey) + raise KnownUserError, "cancelConfig can not be nil." if cancelConfig == nil + raise KnownUserError, "cancelConfig.eventId can not be nil or empty." if Utils.isNilOrEmpty(cancelConfig.eventId) + raise KnownUserError, "cancelConfig.queueDomain can not be nil or empty." if Utils.isNilOrEmpty(cancelConfig.queueDomain) + + userInQueueService = getUserInQueueService(httpContextProvider) + result = userInQueueService.validateCancelRequest(targetUrl, cancelConfig, customerId, secretKey) + result.isAjaxResult = isQueueAjaxCall(httpContextProvider) + + result end end @@ -381,30 +334,23 @@ def setCookie(name, value, expire, domain, isHttpOnly, isSecure) deleteCookie = Utils.isNilOrEmpty(value) noExpire = Utils.isNilOrEmpty(expire) - if(noDomain) - if(deleteCookie) + if noDomain + if deleteCookie @cookies.delete(key) + elsif noExpire + @cookies[key] = { value: value, httponly: isHttpOnly, secure: isSecure } else - if(noExpire) - @cookies[key] = { :value => value, :httponly => isHttpOnly, :secure => isSecure } - else - @cookies[key] = { :value => value, :expires => expire, :httponly => isHttpOnly, :secure => isSecure } - end + @cookies[key] = { value: value, expires: expire, httponly: isHttpOnly, secure: isSecure } end else - if(deleteCookie) - @cookies.delete(key, :domain => domain) + if deleteCookie + @cookies.delete(key, domain: domain) + elsif noExpire + @cookies[key] = { value: value, domain: domain, httponly: isHttpOnly, secure: isSecure } else - if(noExpire) - @cookies[key] = { :value => value, :domain => domain, :httponly => isHttpOnly, :secure => isSecure } - else - @cookies[key] = { :value => value, :expires => expire, :domain => domain, :httponly => isHttpOnly, :secure => isSecure } - end + @cookies[key] = { value: value, expires: expire, domain: domain, httponly: isHttpOnly, secure: isSecure } end end end end -end - - - +end \ No newline at end of file diff --git a/lib/queueit_knownuserv3/models.rb b/lib/queueit_knownuserv3/models.rb index e7e552b..7c385e1 100644 --- a/lib/queueit_knownuserv3/models.rb +++ b/lib/queueit_knownuserv3/models.rb @@ -17,6 +17,18 @@ def self.urlEncode(value) def self.urlDecode(value) return CGI.unescape(value) end + def self.getParameterByName(url, parameterName) + name = Regexp.escape(parameterName) + regex = /[?&]#{name}(=([^&#]*)|&|#|$)/ + match = url.match(regex) + + return nil unless match + return '' if match[2].nil? + + response = CGI.unescape(match[2]) + + return response + end end class QueueEventConfig diff --git a/lib/queueit_knownuserv3/queue_url_params.rb b/lib/queueit_knownuserv3/queue_url_params.rb index 5997eef..7d9b670 100644 --- a/lib/queueit_knownuserv3/queue_url_params.rb +++ b/lib/queueit_knownuserv3/queue_url_params.rb @@ -36,46 +36,51 @@ def self.extractQueueParams(queueitToken) if(Utils.isNilOrEmpty(queueitToken)) return nil end - result = QueueUrlParams.new - result.queueITToken = queueitToken - paramsNameValueList = result.queueITToken.split(KEY_VALUE_SEPARATOR_GROUP_CHAR) + + begin + result = QueueUrlParams.new + result.queueITToken = queueitToken + paramsNameValueList = result.queueITToken.split(KEY_VALUE_SEPARATOR_GROUP_CHAR) - paramsNameValueList.each do |pNameValue| - paramNameValueArr = pNameValue.split(KEY_VALUE_SEPARATOR_CHAR) - - if(!paramNameValueArr.length().eql? 2) - next - end + paramsNameValueList.each do |pNameValue| + paramNameValueArr = pNameValue.split(KEY_VALUE_SEPARATOR_CHAR) + + if(!paramNameValueArr.length().eql? 2) + next + end - case paramNameValueArr[0] - when HASH_KEY - result.hashCode = paramNameValueArr[1] - when TIMESTAMP_KEY - if paramNameValueArr[1] !~ /\D/ - result.timeStamp = paramNameValueArr[1].to_i - else - result.timeStamp = 0 - end - when COOKIE_VALIDITY_MINUTES_KEY - if paramNameValueArr[1] !~ /\D/ - result.cookieValidityMinutes = paramNameValueArr[1].to_i - else - result.cookieValidityMinutes = nil - end - when EVENT_ID_KEY - result.eventId = paramNameValueArr[1] - when EXTENDABLE_COOKIE_KEY - if paramNameValueArr[1].upcase.eql? 'TRUE' - result.extendableCookie = true - end - when QUEUE_ID_KEY - result.queueId = paramNameValueArr[1] - when REDIRECT_TYPE_KEY - result.redirectType = paramNameValueArr[1] - end + case paramNameValueArr[0] + when HASH_KEY + result.hashCode = paramNameValueArr[1] + when TIMESTAMP_KEY + if paramNameValueArr[1] !~ /\D/ + result.timeStamp = paramNameValueArr[1].to_i + else + result.timeStamp = 0 + end + when COOKIE_VALIDITY_MINUTES_KEY + if paramNameValueArr[1] !~ /\D/ + result.cookieValidityMinutes = paramNameValueArr[1].to_i + else + result.cookieValidityMinutes = nil + end + when EVENT_ID_KEY + result.eventId = paramNameValueArr[1] + when EXTENDABLE_COOKIE_KEY + if paramNameValueArr[1].upcase.eql? 'TRUE' + result.extendableCookie = true + end + when QUEUE_ID_KEY + result.queueId = paramNameValueArr[1] + when REDIRECT_TYPE_KEY + result.redirectType = paramNameValueArr[1] + end + end + result.queueITTokenWithoutHash = result.queueITToken.gsub((KEY_VALUE_SEPARATOR_GROUP_CHAR + HASH_KEY + KEY_VALUE_SEPARATOR_CHAR + result.hashCode), "") + return result + rescue + return nil end - result.queueITTokenWithoutHash = result.queueITToken.gsub((KEY_VALUE_SEPARATOR_GROUP_CHAR + HASH_KEY + KEY_VALUE_SEPARATOR_CHAR + result.hashCode), "") - return result end end end \ No newline at end of file diff --git a/lib/queueit_knownuserv3/user_in_queue_service.rb b/lib/queueit_knownuserv3/user_in_queue_service.rb index 9b35baa..47b462d 100644 --- a/lib/queueit_knownuserv3/user_in_queue_service.rb +++ b/lib/queueit_knownuserv3/user_in_queue_service.rb @@ -3,7 +3,7 @@ module QueueIt class UserInQueueService - SDK_VERSION_NO = "3.7.1" + SDK_VERSION_NO = "3.7.2" SDK_VERSION = "v3-ruby-" + SDK_VERSION_NO def initialize(userInQueueStateRepository) @@ -30,26 +30,26 @@ def validateQueueRequest(targetUrl, queueitToken, config, customerId, secretKey) queueParams = QueueUrlParams::extractQueueParams(queueitToken) requestValidationResult = nil - isTokenValid = false + isTokenValid = false - if (!queueParams.nil?) + if (queueParams.nil?) + requestValidationResult = getQueueResult(targetUrl, config, customerId) + else tokenValidationResult = validateToken(config, queueParams, secretKey) - isTokenValid = tokenValidationResult.isValid - - if (isTokenValid) + if (tokenValidationResult.nil?) + requestValidationResult = getQueueResult(targetUrl, config, customerId) + elsif (tokenValidationResult.isValid) requestValidationResult = getValidTokenResult(config, queueParams, secretKey) else requestValidationResult = getErrorResult(customerId, targetUrl, config, queueParams, tokenValidationResult.errorCode) end - else - requestValidationResult = getQueueResult(targetUrl, config, customerId) - end + end if (state.isFound && !isTokenValid) @userInQueueStateRepository.cancelQueueCookie(config.eventId, config.cookieDomain, config.isCookieHttpOnly, config.isCookieSecure); end - return requestValidationResult; + return requestValidationResult; end def validateCancelRequest(targetUrl, cancelConfig, customerId, secretKey) @@ -141,18 +141,22 @@ def getIgnoreActionResult(actionName) end def validateToken(config, queueParams, secretKey) - calculatedHash = OpenSSL::HMAC.hexdigest('sha256', secretKey, queueParams.queueITTokenWithoutHash) - if (calculatedHash.upcase() != queueParams.hashCode.upcase()) - return TokenValidationResult.new(false, "hash") - end - if (queueParams.eventId.upcase() != config.eventId.upcase()) - return TokenValidationResult.new(false, "eventid") - end - if (queueParams.timeStamp < Time.now.getutc.tv_sec) - return TokenValidationResult.new(false, "timestamp") - end + begin + calculatedHash = OpenSSL::HMAC.hexdigest('sha256', secretKey, queueParams.queueITTokenWithoutHash) + if (calculatedHash.upcase() != queueParams.hashCode.upcase()) + return TokenValidationResult.new(false, "hash") + end + if (queueParams.eventId.upcase() != config.eventId.upcase()) + return TokenValidationResult.new(false, "eventid") + end + if (queueParams.timeStamp < Time.now.getutc.tv_sec) + return TokenValidationResult.new(false, "timestamp") + end - return TokenValidationResult.new(true, nil) + return TokenValidationResult.new(true, nil) + rescue + return nil + end end class TokenValidationResult diff --git a/license.txt b/license.txt new file mode 100644 index 0000000..6600f1c --- /dev/null +++ b/license.txt @@ -0,0 +1,165 @@ +GNU LESSER GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + + This version of the GNU Lesser General Public License incorporates +the terms and conditions of version 3 of the GNU General Public +License, supplemented by the additional permissions listed below. + + 0. Additional Definitions. + + As used herein, "this License" refers to version 3 of the GNU Lesser +General Public License, and the "GNU GPL" refers to version 3 of the GNU +General Public License. + + "The Library" refers to a covered work governed by this License, +other than an Application or a Combined Work as defined below. + + An "Application" is any work that makes use of an interface provided +by the Library, but which is not otherwise based on the Library. +Defining a subclass of a class defined by the Library is deemed a mode +of using an interface provided by the Library. + + A "Combined Work" is a work produced by combining or linking an +Application with the Library. The particular version of the Library +with which the Combined Work was made is also called the "Linked +Version". + + The "Minimal Corresponding Source" for a Combined Work means the +Corresponding Source for the Combined Work, excluding any source code +for portions of the Combined Work that, considered in isolation, are +based on the Application, and not on the Linked Version. + + The "Corresponding Application Code" for a Combined Work means the +object code and/or source code for the Application, including any data +and utility programs needed for reproducing the Combined Work from the +Application, but excluding the System Libraries of the Combined Work. + + 1. Exception to Section 3 of the GNU GPL. + + You may convey a covered work under sections 3 and 4 of this License +without being bound by section 3 of the GNU GPL. + + 2. Conveying Modified Versions. + + If you modify a copy of the Library, and, in your modifications, a +facility refers to a function or data to be supplied by an Application +that uses the facility (other than as an argument passed when the +facility is invoked), then you may convey a copy of the modified +version: + + a) under this License, provided that you make a good faith effort to + ensure that, in the event an Application does not supply the + function or data, the facility still operates, and performs + whatever part of its purpose remains meaningful, or + + b) under the GNU GPL, with none of the additional permissions of + this License applicable to that copy. + + 3. Object Code Incorporating Material from Library Header Files. + + The object code form of an Application may incorporate material from +a header file that is part of the Library. You may convey such object +code under terms of your choice, provided that, if the incorporated +material is not limited to numerical parameters, data structure +layouts and accessors, or small macros, inline functions and templates +(ten or fewer lines in length), you do both of the following: + + a) Give prominent notice with each copy of the object code that the + Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the object code with a copy of the GNU GPL and this license + document. + + 4. Combined Works. + + You may convey a Combined Work under terms of your choice that, +taken together, effectively do not restrict modification of the +portions of the Library contained in the Combined Work and reverse +engineering for debugging such modifications, if you also do each of +the following: + + a) Give prominent notice with each copy of the Combined Work that + the Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the Combined Work with a copy of the GNU GPL and this license + document. + + c) For a Combined Work that displays copyright notices during + execution, include the copyright notice for the Library among + these notices, as well as a reference directing the user to the + copies of the GNU GPL and this license document. + + d) Do one of the following: + + 0) Convey the Minimal Corresponding Source under the terms of this + License, and the Corresponding Application Code in a form + suitable for, and under terms that permit, the user to + recombine or relink the Application with a modified version of + the Linked Version to produce a modified Combined Work, in the + manner specified by section 6 of the GNU GPL for conveying + Corresponding Source. + + 1) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (a) uses at run time + a copy of the Library already present on the user's computer + system, and (b) will operate properly with a modified version + of the Library that is interface-compatible with the Linked + Version. + + e) Provide Installation Information, but only if you would otherwise + be required to provide such information under section 6 of the + GNU GPL, and only to the extent that such information is + necessary to install and execute a modified version of the + Combined Work produced by recombining or relinking the + Application with a modified version of the Linked Version. (If + you use option 4d0, the Installation Information must accompany + the Minimal Corresponding Source and Corresponding Application + Code. If you use option 4d1, you must provide the Installation + Information in the manner specified by section 6 of the GNU GPL + for conveying Corresponding Source.) + + 5. Combined Libraries. + + You may place library facilities that are a work based on the +Library side by side in a single library together with other library +facilities that are not Applications and are not covered by this +License, and convey such a combined library under terms of your +choice, if you do both of the following: + + a) Accompany the combined library with a copy of the same work based + on the Library, uncombined with any other library facilities, + conveyed under the terms of this License. + + b) Give prominent notice with the combined library that part of it + is a work based on the Library, and explaining where to find the + accompanying uncombined form of the same work. + + 6. Revised Versions of the GNU Lesser General Public License. + + The Free Software Foundation may publish revised and/or new versions +of the GNU Lesser General Public License from time to time. Such new +versions will be similar in spirit to the present version, but may +differ in detail to address new problems or concerns. + + Each version is given a distinguishing version number. If the +Library as you received it specifies that a certain numbered version +of the GNU Lesser General Public License "or any later version" +applies to it, you have the option of following the terms and +conditions either of that published version or of any later version +published by the Free Software Foundation. If the Library as you +received it does not specify a version number of the GNU Lesser +General Public License, you may choose any version of the GNU Lesser +General Public License ever published by the Free Software Foundation. + + If the Library as you received it specifies that a proxy can decide +whether future versions of the GNU Lesser General Public License shall +apply, that proxy's public statement of acceptance of any version is +permanent authorization for you to choose that version for the +Library. diff --git a/test/Dockerfile b/test/Dockerfile new file mode 100644 index 0000000..61397d0 --- /dev/null +++ b/test/Dockerfile @@ -0,0 +1,20 @@ +# open cmd in current folder knownuser-v3-ruby and run following commands +# docker build -f ./test/Dockerfile -t img-rails-tests-app . + +FROM ruby:3.4 + +RUN apt-get update -qq \ + && apt-get install -y --no-install-recommends \ + build-essential libpq-dev nodejs \ + && rm -rf /var/lib/apt/lists/* + +RUN mkdir /app +WORKDIR /app + +COPY Gemfile queueit_knownuserv3.gemspec /app/ +COPY lib/ /app/lib/ +RUN bundle install + +COPY . /app + +RUN ruby ./test/test_queueit_knownuserv3.rb \ No newline at end of file diff --git a/test/queueit_knownuserv3/test_known_user.rb b/test/queueit_knownuserv3/test_known_user.rb index 37c75a1..435f1f6 100644 --- a/test/queueit_knownuserv3/test_known_user.rb +++ b/test/queueit_knownuserv3/test_known_user.rb @@ -108,7 +108,6 @@ def self.generateDebugToken(eventId, secretKey, expired) class TestKnownUser < Test::Unit::TestCase def test_cancelRequestByLocalConfig userInQueueService = UserInQueueServiceMock.new - KnownUser.class_variable_set(:@@userInQueueService, userInQueueService) cancelConfig = CancelEventConfig.new cancelConfig.eventId = "eventId" @@ -117,7 +116,10 @@ def test_cancelRequestByLocalConfig cancelConfig.cookieDomain = "cookieDomain" cancelConfig.actionName = "CancelAction" - result = KnownUser.cancelRequestByLocalConfig("targetUrl", "token", cancelConfig, "customerId", "secretKey") + httpContextMock = HttpContextMock.new + httpContextProvider = QueueIt::HttpContextProvider.new(httpContextMock, userInQueueService) + + result = QueueIt::KnownUser.cancelRequestByLocalConfig("targetUrl", "token", cancelConfig, "customerId", "secretKey", httpContextProvider) assert(userInQueueService.validateCancelRequestCalls[0]["targetUrl"] == "targetUrl") assert(userInQueueService.validateCancelRequestCalls[0]["config"] == cancelConfig) @@ -128,7 +130,6 @@ def test_cancelRequestByLocalConfig def test_cancelRequestByLocalConfig_AjaxCall userInQueueService = UserInQueueServiceMock.new - KnownUser.class_variable_set(:@@userInQueueService, userInQueueService) cancelConfig = CancelEventConfig.new cancelConfig.eventId = "eventId" @@ -139,11 +140,11 @@ def test_cancelRequestByLocalConfig_AjaxCall httpContextMock = HttpContextMock.new httpContextMock.headers = { "x-queueit-ajaxpageurl" => "http%3a%2f%2furl" } - HttpContextProvider.setHttpContext(httpContextMock) + httpContextProvider = QueueIt::HttpContextProvider.new(httpContextMock, userInQueueService) userInQueueService.validateCancelRequestResult = RequestValidationResult.new(ActionTypes::CANCEL, "eventId", nil, "http://q.qeuue-it.com", nil, cancelConfig.actionName) - result = KnownUser.cancelRequestByLocalConfig("targetUrl", "token", cancelConfig, "customerId", "secretKey") + result = QueueIt::KnownUser.cancelRequestByLocalConfig("targetUrl", "token", cancelConfig, "customerId", "secretKey", httpContextProvider) assert(userInQueueService.validateCancelRequestCalls[0]["targetUrl"] == "http://url") assert(userInQueueService.validateCancelRequestCalls[0]["config"] == cancelConfig) @@ -155,7 +156,8 @@ def test_cancelRequestByLocalConfig_AjaxCall end def test_cancelRequestByLocalConfig_nil_QueueDomain - HttpContextProvider.setHttpContext(HttpContextMock.new) + httpContextMock = HttpContextMock.new + httpContextProvider = QueueIt::HttpContextProvider.new(httpContextMock) errorThrown = false @@ -163,7 +165,7 @@ def test_cancelRequestByLocalConfig_nil_QueueDomain cancelConfig.eventId = "eventId" begin - KnownUser.cancelRequestByLocalConfig("targetUrl", "token", cancelConfig, "customerId", "secretKey") + QueueIt::KnownUser.cancelRequestByLocalConfig("targetUrl", "token", cancelConfig, "customerId", "secretKey", httpContextProvider) rescue KnownUserError => err errorThrown = err.message.eql? "cancelConfig.queueDomain can not be nil or empty." end @@ -172,7 +174,8 @@ def test_cancelRequestByLocalConfig_nil_QueueDomain end def test_cancelRequestByLocalConfig_nil_EventId - HttpContextProvider.setHttpContext(HttpContextMock.new) + httpContextMock = HttpContextMock.new + httpContextProvider = QueueIt::HttpContextProvider.new(httpContextMock) errorThrown = false @@ -180,7 +183,7 @@ def test_cancelRequestByLocalConfig_nil_EventId cancelConfig.queueDomain = "queueDomain" begin - KnownUser.cancelRequestByLocalConfig("targetUrl", "token", cancelConfig, "customerId", "secretKey") + QueueIt::KnownUser.cancelRequestByLocalConfig("targetUrl", "token", cancelConfig, "customerId", "secretKey", httpContextProvider) rescue KnownUserError => err errorThrown = err.message.eql? "cancelConfig.eventId can not be nil or empty." end @@ -189,12 +192,13 @@ def test_cancelRequestByLocalConfig_nil_EventId end def test_cancelRequestByLocalConfig_nil_CancelConfig - HttpContextProvider.setHttpContext(HttpContextMock.new) + httpContextMock = HttpContextMock.new + httpContextProvider = QueueIt::HttpContextProvider.new(httpContextMock) errorThrown = false begin - KnownUser.cancelRequestByLocalConfig("targetUrl", "token", nil, "customerId", "secretKey") + QueueIt::KnownUser.cancelRequestByLocalConfig("targetUrl", "token", nil, "customerId", "secretKey", httpContextProvider) rescue KnownUserError => err errorThrown = err.message.eql? "cancelConfig can not be nil." end @@ -203,12 +207,13 @@ def test_cancelRequestByLocalConfig_nil_CancelConfig end def test_cancelRequestByLocalConfig_nil_CustomerId - HttpContextProvider.setHttpContext(HttpContextMock.new) + httpContextMock = HttpContextMock.new + httpContextProvider = QueueIt::HttpContextProvider.new(httpContextMock) errorThrown = false begin - KnownUser.cancelRequestByLocalConfig("targetUrl", "token", CancelEventConfig.new, nil, "secretKey") + QueueIt::KnownUser.cancelRequestByLocalConfig("targetUrl", "token", CancelEventConfig.new, nil, "secretKey", httpContextProvider) rescue KnownUserError => err errorThrown = err.message.eql? "customerId can not be nil or empty." end @@ -217,12 +222,13 @@ def test_cancelRequestByLocalConfig_nil_CustomerId end def test_cancelRequestByLocalConfig_nil_SeceretKey - HttpContextProvider.setHttpContext(HttpContextMock.new) + httpContextMock = HttpContextMock.new + httpContextProvider = QueueIt::HttpContextProvider.new(httpContextMock) errorThrown = false begin - KnownUser.cancelRequestByLocalConfig("targetUrl", "token", CancelEventConfig.new, "customerId", nil) + QueueIt::KnownUser.cancelRequestByLocalConfig("targetUrl", "token", CancelEventConfig.new, "customerId", nil, httpContextProvider) rescue KnownUserError => err errorThrown = err.message.eql? "secretKey can not be nil or empty." end @@ -231,12 +237,13 @@ def test_cancelRequestByLocalConfig_nil_SeceretKey end def test_cancelRequestByLocalConfig_nil_TargetUrl - HttpContextProvider.setHttpContext(HttpContextMock.new) + httpContextMock = HttpContextMock.new + httpContextProvider = QueueIt::HttpContextProvider.new(httpContextMock) errorThrown = false begin - KnownUser.cancelRequestByLocalConfig(nil, "token", CancelEventConfig.new, "customerId", nil) + QueueIt::KnownUser.cancelRequestByLocalConfig(nil, "token", CancelEventConfig.new, "customerId", nil, httpContextProvider) rescue KnownUserError => err errorThrown = err.message.eql? "targetUrl can not be nil or empty." end @@ -245,12 +252,13 @@ def test_cancelRequestByLocalConfig_nil_TargetUrl end def test_extendQueueCookie_nil_EventId - HttpContextProvider.setHttpContext(HttpContextMock.new) + httpContextMock = HttpContextMock.new + httpContextProvider = QueueIt::HttpContextProvider.new(httpContextMock) errorThrown = false begin - KnownUser.extendQueueCookie(nil, 10, "cookieDomain", false, false, "secretkey") + QueueIt::KnownUser.extendQueueCookie(nil, 10, "cookieDomain", false, false, "secretkey", httpContextProvider) rescue KnownUserError => err errorThrown = err.message.eql? "eventId can not be nil or empty." end @@ -259,12 +267,13 @@ def test_extendQueueCookie_nil_EventId end def test_extendQueueCookie_nil_SecretKey - HttpContextProvider.setHttpContext(HttpContextMock.new) + httpContextMock = HttpContextMock.new + httpContextProvider = QueueIt::HttpContextProvider.new(httpContextMock) errorThrown = false begin - KnownUser.extendQueueCookie("eventId", 10, "cookieDomain", false, false, nil) + QueueIt::KnownUser.extendQueueCookie("eventId", 10, "cookieDomain", false, false, nil, httpContextProvider) rescue KnownUserError => err errorThrown = err.message.eql? "secretKey can not be nil or empty." end @@ -273,12 +282,13 @@ def test_extendQueueCookie_nil_SecretKey end def test_extendQueueCookie_Invalid_CookieValidityMinute - HttpContextProvider.setHttpContext(HttpContextMock.new) + httpContextMock = HttpContextMock.new + httpContextProvider = QueueIt::HttpContextProvider.new(httpContextMock) errorThrown = false begin - KnownUser.extendQueueCookie("eventId", "invalidInt", "cookieDomain", false, false, "secrettKey") + QueueIt::KnownUser.extendQueueCookie("eventId", "invalidInt", "cookieDomain", false, false, "secrettKey", httpContextProvider) rescue KnownUserError => err errorThrown = err.message.eql? "cookieValidityMinute should be integer greater than 0." end @@ -287,12 +297,13 @@ def test_extendQueueCookie_Invalid_CookieValidityMinute end def test_extendQueueCookie_Negative_CookieValidityMinute - HttpContextProvider.setHttpContext(HttpContextMock.new) + httpContextMock = HttpContextMock.new + httpContextProvider = QueueIt::HttpContextProvider.new(httpContextMock) errorThrown = false begin - KnownUser.extendQueueCookie("eventId", -1, "cookieDomain", false, false, "secrettKey") + QueueIt::KnownUser.extendQueueCookie("eventId", -1, "cookieDomain", false, false, "secrettKey", httpContextProvider) rescue KnownUserError => err errorThrown = err.message.eql? "cookieValidityMinute should be integer greater than 0." end @@ -301,12 +312,11 @@ def test_extendQueueCookie_Negative_CookieValidityMinute end def test_extendQueueCookie - HttpContextProvider.setHttpContext(HttpContextMock.new) - userInQueueService = UserInQueueServiceMock.new - KnownUser.class_variable_set(:@@userInQueueService, userInQueueService) + httpContextMock = HttpContextMock.new + httpContextProvider = QueueIt::HttpContextProvider.new(httpContextMock, userInQueueService) - KnownUser.extendQueueCookie("evtId", 10, "domain", true, true, "key") + QueueIt::KnownUser.extendQueueCookie("evtId", 10, "domain", true, true, "key", httpContextProvider) assert(userInQueueService.extendQueueCookieCalls[0]["eventId"] == "evtId") assert(userInQueueService.extendQueueCookieCalls[0]["cookieValidityMinute"] == 10) @@ -317,7 +327,8 @@ def test_extendQueueCookie end def test_resolveQueueRequestByLocalConfig_empty_eventId - HttpContextProvider.setHttpContext(HttpContextMock.new) + httpContextMock = HttpContextMock.new + httpContextProvider = QueueIt::HttpContextProvider.new(httpContextMock) queueConfig = QueueEventConfig.new queueConfig.cookieDomain = "cookieDomain" @@ -332,7 +343,7 @@ def test_resolveQueueRequestByLocalConfig_empty_eventId errorThrown = false begin - KnownUser.resolveQueueRequestByLocalConfig("targeturl", "queueIttoken", queueConfig, "customerid", "secretkey") + QueueIt::KnownUser.resolveQueueRequestByLocalConfig("targeturl", "queueIttoken", queueConfig, "customerid", "secretkey", httpContextProvider) rescue KnownUserError => err errorThrown = err.message.eql? "queueConfig.eventId can not be nil or empty." end @@ -341,7 +352,8 @@ def test_resolveQueueRequestByLocalConfig_empty_eventId end def test_resolveQueueRequestByLocalConfig_empty_secretKey - HttpContextProvider.setHttpContext(HttpContextMock.new) + httpContextMock = HttpContextMock.new + httpContextProvider = QueueIt::HttpContextProvider.new(httpContextMock) queueConfig = QueueEventConfig.new queueConfig.cookieDomain = "cookieDomain" @@ -356,7 +368,7 @@ def test_resolveQueueRequestByLocalConfig_empty_secretKey errorThrown = false begin - KnownUser.resolveQueueRequestByLocalConfig("targeturl", "queueIttoken", queueConfig, "customerid", nil) + QueueIt::KnownUser.resolveQueueRequestByLocalConfig("targeturl", "queueIttoken", queueConfig, "customerid", nil, httpContextProvider) rescue KnownUserError => err errorThrown = err.message.eql? "secretKey can not be nil or empty." end @@ -365,7 +377,8 @@ def test_resolveQueueRequestByLocalConfig_empty_secretKey end def test_resolveQueueRequestByLocalConfig_empty_queueDomain - HttpContextProvider.setHttpContext(HttpContextMock.new) + httpContextMock = HttpContextMock.new + httpContextProvider = QueueIt::HttpContextProvider.new(httpContextMock) queueConfig = QueueEventConfig.new queueConfig.cookieDomain = "cookieDomain" @@ -380,7 +393,7 @@ def test_resolveQueueRequestByLocalConfig_empty_queueDomain errorThrown = false begin - KnownUser.resolveQueueRequestByLocalConfig("targeturl", "queueIttoken", queueConfig, "customerid", "secretkey") + QueueIt::KnownUser.resolveQueueRequestByLocalConfig("targeturl", "queueIttoken", queueConfig, "customerid", "secretkey", httpContextProvider) rescue KnownUserError => err errorThrown = err.message.eql? "queueConfig.queueDomain can not be nil or empty." end @@ -389,7 +402,8 @@ def test_resolveQueueRequestByLocalConfig_empty_queueDomain end def test_resolveQueueRequestByLocalConfig_empty_customerId - HttpContextProvider.setHttpContext(HttpContextMock.new) + httpContextMock = HttpContextMock.new + httpContextProvider = QueueIt::HttpContextProvider.new(httpContextMock) queueConfig = QueueEventConfig.new queueConfig.cookieDomain = "cookieDomain" @@ -404,7 +418,7 @@ def test_resolveQueueRequestByLocalConfig_empty_customerId errorThrown = false begin - KnownUser.resolveQueueRequestByLocalConfig("targeturl", "queueIttoken", queueConfig, nil, "secretKey") + QueueIt::KnownUser.resolveQueueRequestByLocalConfig("targeturl", "queueIttoken", queueConfig, nil, "secretKey", httpContextProvider) rescue KnownUserError => err errorThrown = err.message.eql? "customerId can not be nil or empty." end @@ -413,7 +427,8 @@ def test_resolveQueueRequestByLocalConfig_empty_customerId end def test_resolveQueueRequestByLocalConfig_Invalid_extendCookieValidity - HttpContextProvider.setHttpContext(HttpContextMock.new) + httpContextMock = HttpContextMock.new + httpContextProvider = QueueIt::HttpContextProvider.new(httpContextMock) queueConfig = QueueEventConfig.new queueConfig.cookieDomain = "cookieDomain" @@ -428,7 +443,7 @@ def test_resolveQueueRequestByLocalConfig_Invalid_extendCookieValidity errorThrown = false begin - KnownUser.resolveQueueRequestByLocalConfig("targeturl", "queueIttoken", queueConfig, "customerId", "secretKey") + QueueIt::KnownUser.resolveQueueRequestByLocalConfig("targeturl", "queueIttoken", queueConfig, "customerId", "secretKey", httpContextProvider) rescue KnownUserError => err errorThrown = err.message.eql? "queueConfig.extendCookieValidity should be valid boolean." end @@ -437,7 +452,8 @@ def test_resolveQueueRequestByLocalConfig_Invalid_extendCookieValidity end def test_resolveQueueRequestByLocalConfig_Invalid_cookieValidityMinute - HttpContextProvider.setHttpContext(HttpContextMock.new) + httpContextMock = HttpContextMock.new + httpContextProvider = QueueIt::HttpContextProvider.new(httpContextMock) queueConfig = QueueEventConfig.new queueConfig.cookieDomain = "cookieDomain" @@ -452,7 +468,7 @@ def test_resolveQueueRequestByLocalConfig_Invalid_cookieValidityMinute errorThrown = false begin - KnownUser.resolveQueueRequestByLocalConfig("targeturl", "queueIttoken", queueConfig, "customerId", "secretKey") + QueueIt::KnownUser.resolveQueueRequestByLocalConfig("targeturl", "queueIttoken", queueConfig, "customerId", "secretKey", httpContextProvider) rescue KnownUserError => err errorThrown = err.message.start_with? "queueConfig.cookieValidityMinute should be integer greater than 0" end @@ -461,7 +477,8 @@ def test_resolveQueueRequestByLocalConfig_Invalid_cookieValidityMinute end def test_resolveQueueRequestByLocalConfig_zero_cookieValidityMinute - HttpContextProvider.setHttpContext(HttpContextMock.new) + httpContextMock = HttpContextMock.new + httpContextProvider = QueueIt::HttpContextProvider.new(httpContextMock) queueConfig = QueueEventConfig.new queueConfig.cookieDomain = "cookieDomain" @@ -476,7 +493,7 @@ def test_resolveQueueRequestByLocalConfig_zero_cookieValidityMinute errorThrown = false begin - KnownUser.resolveQueueRequestByLocalConfig("targeturl", "queueIttoken", queueConfig, "customerId", "secretKey") + QueueIt::KnownUser.resolveQueueRequestByLocalConfig("targeturl", "queueIttoken", queueConfig, "customerId", "secretKey", httpContextProvider) rescue KnownUserError => err errorThrown = err.message.start_with? "queueConfig.cookieValidityMinute should be integer greater than 0" end @@ -485,9 +502,9 @@ def test_resolveQueueRequestByLocalConfig_zero_cookieValidityMinute end def test_resolveQueueRequestByLocalConfig - HttpContextProvider.setHttpContext(HttpContextMock.new) userInQueueService = UserInQueueServiceMock.new - KnownUser.class_variable_set(:@@userInQueueService, userInQueueService) + httpContextMock = HttpContextMock.new + httpContextProvider = QueueIt::HttpContextProvider.new(httpContextMock, userInQueueService) queueConfig = QueueEventConfig.new queueConfig.cookieDomain = "cookieDomain" @@ -500,7 +517,7 @@ def test_resolveQueueRequestByLocalConfig queueConfig.version = 12 queueConfig.actionName = "QueueAction" - result = KnownUser.resolveQueueRequestByLocalConfig("target", "token", queueConfig, "id", "key") + result = QueueIt::KnownUser.resolveQueueRequestByLocalConfig("target", "token", queueConfig, "id", "key", httpContextProvider) assert(userInQueueService.validateQueueRequestCalls[0]["targetUrl"] == "target") assert(userInQueueService.validateQueueRequestCalls[0]["queueitToken"] == "token") @@ -512,7 +529,6 @@ def test_resolveQueueRequestByLocalConfig def test_resolveQueueRequestByLocalConfig_AjaxCall userInQueueService = UserInQueueServiceMock.new - KnownUser.class_variable_set(:@@userInQueueService, userInQueueService) queueConfig = QueueEventConfig.new queueConfig.cookieDomain = "cookieDomain" @@ -527,11 +543,11 @@ def test_resolveQueueRequestByLocalConfig_AjaxCall httpContextMock = HttpContextMock.new httpContextMock.headers = { "x-queueit-ajaxpageurl" => "http%3a%2f%2furl" } - HttpContextProvider.setHttpContext(httpContextMock) + httpContextProvider = QueueIt::HttpContextProvider.new(httpContextMock, userInQueueService) userInQueueService.validateQueueRequestResult = RequestValidationResult.new(ActionTypes::QUEUE, "eventId", nil, "http://q.qeuue-it.com", nil, queueConfig.actionName) - result = KnownUser.resolveQueueRequestByLocalConfig("targetUrl", "token", queueConfig, "customerId", "secretKey") + result = QueueIt::KnownUser.resolveQueueRequestByLocalConfig("targetUrl", "token", queueConfig, "customerId", "secretKey", httpContextProvider) assert(userInQueueService.validateQueueRequestCalls[0]["targetUrl"] == "http://url") assert(userInQueueService.validateQueueRequestCalls[0]["config"] == queueConfig) @@ -544,9 +560,11 @@ def test_resolveQueueRequestByLocalConfig_AjaxCall def test_validateRequestByIntegrationConfig_empty_currentUrlWithoutQueueITToken errorThrown = false + httpContextMock = HttpContextMock.new + httpContextProvider = QueueIt::HttpContextProvider.new(httpContextMock) begin - KnownUser.validateRequestByIntegrationConfig("", "queueIttoken", "{}", "customerId", "secretKey") + QueueIt::KnownUser.validateRequestByIntegrationConfig("", "queueIttoken", "{}", "customerId", "secretKey", httpContextProvider) rescue KnownUserError => err errorThrown = err.message.start_with? "currentUrlWithoutQueueITToken can not be nil or empty" end @@ -556,7 +574,6 @@ def test_validateRequestByIntegrationConfig_empty_currentUrlWithoutQueueITToken def test_validateRequestByIntegrationConfig userInQueueService = UserInQueueServiceMock.new - KnownUser.class_variable_set(:@@userInQueueService, userInQueueService) integrationConfig = { @@ -609,10 +626,10 @@ def test_validateRequestByIntegrationConfig httpContextMock = HttpContextMock.new httpContextMock.userAgent = 'googlebot' httpContextMock.cookieManager = CookieManagerMock.new - HttpContextProvider.setHttpContext(httpContextMock) + httpContextProvider = QueueIt::HttpContextProvider.new(httpContextMock, userInQueueService) integrationConfigJson = JSON.generate(integrationConfig) - result = KnownUser.validateRequestByIntegrationConfig("http://test.com?event1=true", "token", integrationConfigJson, "id", "key") + result = QueueIt::KnownUser.validateRequestByIntegrationConfig("http://test.com?event1=true", "token", integrationConfigJson, "id", "key", httpContextProvider) assert(userInQueueService.validateQueueRequestCalls[0]["targetUrl"] == "http://test.com?event1=true") assert(userInQueueService.validateQueueRequestCalls[0]["queueitToken"] == "token") @@ -633,7 +650,6 @@ def test_validateRequestByIntegrationConfig def test_validateRequestByIntegrationConfig_AjaxCall userInQueueService = UserInQueueServiceMock.new - KnownUser.class_variable_set(:@@userInQueueService, userInQueueService) integrationConfig = { @@ -687,13 +703,13 @@ def test_validateRequestByIntegrationConfig_AjaxCall httpContextMock.userAgent = 'googlebot' httpContextMock.headers = { "x-queueit-ajaxpageurl" => "http%3a%2f%2furl" } httpContextMock.cookieManager = CookieManagerMock.new - HttpContextProvider.setHttpContext(httpContextMock) + httpContextProvider = QueueIt::HttpContextProvider.new(httpContextMock, userInQueueService) integrationConfigJson = JSON.generate(integrationConfig) userInQueueService.validateQueueRequestResult = RequestValidationResult.new(ActionTypes::QUEUE, "eventId", nil, "http://q.qeuue-it.com", nil, integrationConfig[:Integrations][0][:Name]) - result = KnownUser.validateRequestByIntegrationConfig("http://test.com?event1=true", "token", integrationConfigJson, "id", "key") + result = QueueIt::KnownUser.validateRequestByIntegrationConfig("http://test.com?event1=true", "token", integrationConfigJson, "id", "key", httpContextProvider) assert(userInQueueService.validateQueueRequestCalls[0]["targetUrl"] == "http://url") assert(userInQueueService.validateQueueRequestCalls[0]["queueitToken"] == "token") @@ -715,7 +731,6 @@ def test_validateRequestByIntegrationConfig_AjaxCall def test_validateRequestByIntegrationConfig_NotMatch userInQueueService = UserInQueueServiceMock.new - KnownUser.class_variable_set(:@@userInQueueService, userInQueueService) integrationConfig = { @@ -729,8 +744,11 @@ def test_validateRequestByIntegrationConfig_NotMatch :ConfigDataVersion => "1.0.0.1" } + httpContextMock = HttpContextMock.new + httpContextProvider = QueueIt::HttpContextProvider.new(httpContextMock, userInQueueService) + integrationConfigJson = JSON.generate(integrationConfig) - result = KnownUser.validateRequestByIntegrationConfig("http://test.com?event1=true", "queueIttoken", integrationConfigJson, "customerid", "secretkey") + result = QueueIt::KnownUser.validateRequestByIntegrationConfig("http://test.com?event1=true", "queueIttoken", integrationConfigJson, "customerid", "secretkey", httpContextProvider) assert(userInQueueService.validateQueueRequestCalls.length == 0) assert(!result.doRedirect) @@ -738,9 +756,9 @@ def test_validateRequestByIntegrationConfig_NotMatch def test_validateRequestByIntegrationConfig_ForcedTargetUrl - HttpContextProvider.setHttpContext(HttpContextMock.new) userInQueueService = UserInQueueServiceMock.new - KnownUser.class_variable_set(:@@userInQueueService, userInQueueService) + httpContextMock = HttpContextMock.new + httpContextProvider = QueueIt::HttpContextProvider.new(httpContextMock, userInQueueService) integrationConfig = { @@ -786,7 +804,7 @@ def test_validateRequestByIntegrationConfig_ForcedTargetUrl } integrationConfigJson = JSON.generate(integrationConfig) - result = KnownUser.validateRequestByIntegrationConfig("http://test.com?event1=true", "queueIttoken", integrationConfigJson, "customerid", "secretkey") + result = QueueIt::KnownUser.validateRequestByIntegrationConfig("http://test.com?event1=true", "queueIttoken", integrationConfigJson, "customerid", "secretkey", httpContextProvider) assert(userInQueueService.validateQueueRequestCalls[0]['targetUrl'] == "http://test.com") assert(!result.isAjaxResult) @@ -794,7 +812,6 @@ def test_validateRequestByIntegrationConfig_ForcedTargetUrl def test_validateRequestByIntegrationConfig_ForcedTargetUrl_AjaxCall userInQueueService = UserInQueueServiceMock.new - KnownUser.class_variable_set(:@@userInQueueService, userInQueueService) integrationConfig = { @@ -841,12 +858,12 @@ def test_validateRequestByIntegrationConfig_ForcedTargetUrl_AjaxCall httpContextMock = HttpContextMock.new httpContextMock.headers = { "x-queueit-ajaxpageurl" => "http%3a%2f%2furl" } - HttpContextProvider.setHttpContext(httpContextMock) + httpContextProvider = QueueIt::HttpContextProvider.new(httpContextMock, userInQueueService) userInQueueService.validateQueueRequestResult = RequestValidationResult.new(ActionTypes::QUEUE, "eventId", nil, "http://q.qeuue-it.com", nil, integrationConfig[:Integrations][0][:Name]) integrationConfigJson = JSON.generate(integrationConfig) - result = KnownUser.validateRequestByIntegrationConfig("http://test.com?event1=true", "queueIttoken", integrationConfigJson, "customerid", "secretkey") + result = QueueIt::KnownUser.validateRequestByIntegrationConfig("http://test.com?event1=true", "queueIttoken", integrationConfigJson, "customerid", "secretkey", httpContextProvider) assert(userInQueueService.validateQueueRequestCalls[0]['targetUrl'] == "http://test.com") assert(result.isAjaxResult) @@ -854,9 +871,9 @@ def test_validateRequestByIntegrationConfig_ForcedTargetUrl_AjaxCall end def test_validateRequestByIntegrationConfig_EventTargetUrl - HttpContextProvider.setHttpContext(HttpContextMock.new) userInQueueService = UserInQueueServiceMock.new - KnownUser.class_variable_set(:@@userInQueueService, userInQueueService) + httpContextMock = HttpContextMock.new + httpContextProvider = QueueIt::HttpContextProvider.new(httpContextMock, userInQueueService) integrationConfig = { @@ -901,7 +918,7 @@ def test_validateRequestByIntegrationConfig_EventTargetUrl } integrationConfigJson = JSON.generate(integrationConfig) - result = KnownUser.validateRequestByIntegrationConfig("http://test.com?event1=true", "queueIttoken", integrationConfigJson, "customerid", "secretkey") + result = QueueIt::KnownUser.validateRequestByIntegrationConfig("http://test.com?event1=true", "queueIttoken", integrationConfigJson, "customerid", "secretkey", httpContextProvider) assert(userInQueueService.validateQueueRequestCalls[0]['targetUrl'] == "") assert(!result.isAjaxResult) @@ -909,7 +926,6 @@ def test_validateRequestByIntegrationConfig_EventTargetUrl def test_validateRequestByIntegrationConfig_EventTargetUrl_AjaxCall userInQueueService = UserInQueueServiceMock.new - KnownUser.class_variable_set(:@@userInQueueService, userInQueueService) integrationConfig = { @@ -955,12 +971,12 @@ def test_validateRequestByIntegrationConfig_EventTargetUrl_AjaxCall httpContextMock = HttpContextMock.new httpContextMock.headers = { "x-queueit-ajaxpageurl" => "http%3a%2f%2furl" } - HttpContextProvider.setHttpContext(httpContextMock) + httpContextProvider = QueueIt::HttpContextProvider.new(httpContextMock, userInQueueService) userInQueueService.validateQueueRequestResult = RequestValidationResult.new(ActionTypes::QUEUE, "eventId", nil, "http://q.qeuue-it.com", nil, integrationConfig[:Integrations][0][:Name]) integrationConfigJson = JSON.generate(integrationConfig) - result = KnownUser.validateRequestByIntegrationConfig("http://test.com?event1=true", "queueIttoken", integrationConfigJson, "customerid", "secretkey") + result = QueueIt::KnownUser.validateRequestByIntegrationConfig("http://test.com?event1=true", "queueIttoken", integrationConfigJson, "customerid", "secretkey", httpContextProvider) assert(userInQueueService.validateQueueRequestCalls[0]['targetUrl'] == "") assert(result.isAjaxResult) @@ -968,9 +984,9 @@ def test_validateRequestByIntegrationConfig_EventTargetUrl_AjaxCall end def test_validateRequestByIntegrationConfig_CancelAction - HttpContextProvider.setHttpContext(HttpContextMock.new) userInQueueService = UserInQueueServiceMock.new - KnownUser.class_variable_set(:@@userInQueueService, userInQueueService) + httpContextMock = HttpContextMock.new + httpContextProvider = QueueIt::HttpContextProvider.new(httpContextMock, userInQueueService) integrationConfig = { @@ -1010,7 +1026,7 @@ def test_validateRequestByIntegrationConfig_CancelAction } integrationConfigJson = JSON.generate(integrationConfig) - result = KnownUser.validateRequestByIntegrationConfig("http://test.com?event1=true", "queueIttoken", integrationConfigJson, "customerid", "secretkey") + result = QueueIt::KnownUser.validateRequestByIntegrationConfig("http://test.com?event1=true", "queueIttoken", integrationConfigJson, "customerid", "secretkey", httpContextProvider) assert(userInQueueService.validateCancelRequestCalls[0]["targetUrl"] == "http://test.com?event1=true") assert(userInQueueService.validateCancelRequestCalls[0]["customerId"] == "customerid") @@ -1026,7 +1042,6 @@ def test_validateRequestByIntegrationConfig_CancelAction def test_validateRequestByIntegrationConfig_CancelAction_AjaxCall userInQueueService = UserInQueueServiceMock.new - KnownUser.class_variable_set(:@@userInQueueService, userInQueueService) integrationConfig = { @@ -1067,12 +1082,12 @@ def test_validateRequestByIntegrationConfig_CancelAction_AjaxCall httpContextMock = HttpContextMock.new httpContextMock.headers = { "x-queueit-ajaxpageurl" => "http%3a%2f%2furl" } - HttpContextProvider.setHttpContext(httpContextMock) + httpContextProvider = QueueIt::HttpContextProvider.new(httpContextMock, userInQueueService) userInQueueService.validateCancelRequestResult = RequestValidationResult.new(ActionTypes::CANCEL, "eventId", nil, "http://q.qeuue-it.com", nil, integrationConfig[:Integrations][0][:Name]) integrationConfigJson = JSON.generate(integrationConfig) - result = KnownUser.validateRequestByIntegrationConfig("http://test.com?event1=true", "queueIttoken", integrationConfigJson, "customerid", "secretkey") + result = QueueIt::KnownUser.validateRequestByIntegrationConfig("http://test.com?event1=true", "queueIttoken", integrationConfigJson, "customerid", "secretkey", httpContextProvider) assert(userInQueueService.validateCancelRequestCalls[0]["targetUrl"] == "http://url") assert(userInQueueService.validateCancelRequestCalls[0]["customerId"] == "customerid") @@ -1089,7 +1104,6 @@ def test_validateRequestByIntegrationConfig_CancelAction_AjaxCall def test_validateRequestByIntegrationConfig_ignoreAction userInQueueService = UserInQueueServiceMock.new - KnownUser.class_variable_set(:@@userInQueueService, userInQueueService) integrationConfig = { @@ -1128,8 +1142,11 @@ def test_validateRequestByIntegrationConfig_ignoreAction :ConfigDataVersion => "1.0.0.1" } + httpContextMock = HttpContextMock.new + httpContextProvider = QueueIt::HttpContextProvider.new(httpContextMock, userInQueueService) + integrationConfigJson = JSON.generate(integrationConfig) - result = KnownUser.validateRequestByIntegrationConfig("http://test.com?event1=true", "queueIttoken", integrationConfigJson, "customerid", "secretkey") + result = QueueIt::KnownUser.validateRequestByIntegrationConfig("http://test.com?event1=true", "queueIttoken", integrationConfigJson, "customerid", "secretkey", httpContextProvider) assert(userInQueueService.getIgnoreActionResultCalls.length.eql? 1) assert(userInQueueService.getIgnoreActionResultCalls[0]["actionName"] == integrationConfig[:Integrations][0][:Name]) @@ -1138,7 +1155,6 @@ def test_validateRequestByIntegrationConfig_ignoreAction def test_validateRequestByIntegrationConfig_ignoreAction_AjaxCall userInQueueService = UserInQueueServiceMock.new - KnownUser.class_variable_set(:@@userInQueueService, userInQueueService) integrationConfig = { @@ -1179,10 +1195,10 @@ def test_validateRequestByIntegrationConfig_ignoreAction_AjaxCall httpContextMock = HttpContextMock.new httpContextMock.headers = { "x-queueit-ajaxpageurl" => "http%3a%2f%2furl" } - HttpContextProvider.setHttpContext(httpContextMock) + httpContextProvider = QueueIt::HttpContextProvider.new(httpContextMock, userInQueueService) integrationConfigJson = JSON.generate(integrationConfig) - result = KnownUser.validateRequestByIntegrationConfig("http://test.com?event1=true", "queueIttoken", integrationConfigJson, "customerid", "secretkey") + result = QueueIt::KnownUser.validateRequestByIntegrationConfig("http://test.com?event1=true", "queueIttoken", integrationConfigJson, "customerid", "secretkey", httpContextProvider) assert(userInQueueService.getIgnoreActionResultCalls.length.eql? 1) assert(userInQueueService.getIgnoreActionResultCalls[0]["actionName"] == integrationConfig[:Integrations][0][:Name]) @@ -1191,7 +1207,6 @@ def test_validateRequestByIntegrationConfig_ignoreAction_AjaxCall def test_validateRequestByIntegrationConfig_defaultsTo_ignoreAction userInQueueService = UserInQueueServiceMock.new - KnownUser.class_variable_set(:@@userInQueueService, userInQueueService) integrationConfig = { @@ -1230,8 +1245,11 @@ def test_validateRequestByIntegrationConfig_defaultsTo_ignoreAction :ConfigDataVersion => "1.0.0.1" } + httpContextMock = HttpContextMock.new + httpContextProvider = QueueIt::HttpContextProvider.new(httpContextMock, userInQueueService) + integrationConfigJson = JSON.generate(integrationConfig) - KnownUser.validateRequestByIntegrationConfig("http://test.com?event1=true", "queueIttoken", integrationConfigJson, "customerid", "secretkey") + QueueIt::KnownUser.validateRequestByIntegrationConfig("http://test.com?event1=true", "queueIttoken", integrationConfigJson, "customerid", "secretkey", httpContextProvider) assert(userInQueueService.getIgnoreActionResultCalls.length.eql? 1) assert(userInQueueService.getIgnoreActionResultCalls[0]["actionName"] == integrationConfig[:Integrations][0][:Name]) @@ -1239,7 +1257,6 @@ def test_validateRequestByIntegrationConfig_defaultsTo_ignoreAction def test_ValidateRequestByIntegrationConfig_Debug userInQueueService = UserInQueueServiceMock.new - KnownUser.class_variable_set(:@@userInQueueService, userInQueueService) integrationConfig = { @@ -1304,7 +1321,7 @@ def test_ValidateRequestByIntegrationConfig_Debug "x-forwarded-host" => "xfh", "x-forwarded-proto" => "xfp" } - HttpContextProvider.setHttpContext(httpContextMock) + httpContextProvider = QueueIt::HttpContextProvider.new(httpContextMock, userInQueueService) integrationConfigJson = JSON.generate(integrationConfig) @@ -1312,7 +1329,7 @@ def test_ValidateRequestByIntegrationConfig_Debug queueitToken = QueueITTokenGenerator::generateDebugToken("eventId", secretKey, false) expectedServerTime = Time.now.utc.iso8601 - KnownUser.validateRequestByIntegrationConfig("http://test.com?event1=true", queueitToken, integrationConfigJson, "customerId", secretKey) + QueueIt::KnownUser.validateRequestByIntegrationConfig("http://test.com?event1=true", queueitToken, integrationConfigJson, "customerId", secretKey, httpContextProvider) expectedCookieValue = "SdkVersion=" + UserInQueueService::SDK_VERSION + @@ -1347,7 +1364,6 @@ def test_ValidateRequestByIntegrationConfig_Debug def test_ValidateRequestByIntegrationConfig_Debug_WithoutMatch userInQueueService = UserInQueueServiceMock.new - KnownUser.class_variable_set(:@@userInQueueService, userInQueueService) httpContextMock = HttpContextMock.new httpContextMock.url = "http://localhost/original_url" @@ -1360,7 +1376,7 @@ def test_ValidateRequestByIntegrationConfig_Debug_WithoutMatch "x-forwarded-host" => "xfh", "x-forwarded-proto" => "xfp" } - HttpContextProvider.setHttpContext(httpContextMock) + httpContextProvider = QueueIt::HttpContextProvider.new(httpContextMock, userInQueueService) integrationConfig = { @@ -1379,7 +1395,7 @@ def test_ValidateRequestByIntegrationConfig_Debug_WithoutMatch integrationConfigJson = JSON.generate(integrationConfig) expectedServerTime = Time.now.utc.iso8601 - KnownUser.validateRequestByIntegrationConfig("http://test.com?event1=true", queueitToken, integrationConfigJson, "customerId", secretKey) + QueueIt::KnownUser.validateRequestByIntegrationConfig("http://test.com?event1=true", queueitToken, integrationConfigJson, "customerId", secretKey, httpContextProvider) expectedCookieValue = "SdkVersion=" + UserInQueueService::SDK_VERSION + @@ -1402,7 +1418,6 @@ def test_ValidateRequestByIntegrationConfig_Debug_WithoutMatch def test_validateRequestByIntegrationConfig_debug_invalid_config_json userInQueueService = UserInQueueServiceMock.new - KnownUser.class_variable_set(:@@userInQueueService, userInQueueService) httpContextMock = HttpContextMock.new httpContextMock.url = "http://localhost/original_url" @@ -1414,8 +1429,7 @@ def test_validateRequestByIntegrationConfig_debug_invalid_config_json "x-forwarded-for" => "xff", "x-forwarded-host" => "xfh", "x-forwarded-proto" => "xfp" } - - HttpContextProvider.setHttpContext(httpContextMock) + httpContextProvider = QueueIt::HttpContextProvider.new(httpContextMock, userInQueueService) integrationConfigJson = "{}" queueitToken = QueueITTokenGenerator::generateDebugToken("eventId", "secretKey", false) @@ -1424,7 +1438,7 @@ def test_validateRequestByIntegrationConfig_debug_invalid_config_json errorThrown = false begin - KnownUser.validateRequestByIntegrationConfig("http://test.com?event1=true", queueitToken, integrationConfigJson, "customerId", "secretKey") + QueueIt::KnownUser.validateRequestByIntegrationConfig("http://test.com?event1=true", queueitToken, integrationConfigJson, "customerId", "secretKey", httpContextProvider) rescue KnownUserError => err errorThrown = err.message.start_with? "integrationConfigJson is not valid json." end @@ -1455,10 +1469,11 @@ def test_validateRequestByIntegrationConfig_debug_invalid_config_json def test_ValidateRequestByIntegrationConfig_Debug_Missing_CustomerId httpContextMock = HttpContextMock.new httpContextMock.cookieManager = CookieManagerMock.new + httpContextProvider = QueueIt::HttpContextProvider.new(httpContextMock) expiredDebugToken = QueueITTokenGenerator::generateDebugToken("eventId", "secretKey", true) - result = KnownUser.validateRequestByIntegrationConfig("http://test.com?event1=true", expiredDebugToken, "{}", nil, "secretKey") + result = QueueIt::KnownUser.validateRequestByIntegrationConfig("http://test.com?event1=true", expiredDebugToken, "{}", nil, "secretKey", httpContextProvider) assert("https://api2.queue-it.net/diagnostics/connector/error/?code=setup" == result.redirectUrl) assert(httpContextMock.cookieManager.cookieList.length == 0) @@ -1467,10 +1482,11 @@ def test_ValidateRequestByIntegrationConfig_Debug_Missing_CustomerId def test_ValidateRequestByIntegrationConfig_Debug_Missing_Secretkey httpContextMock = HttpContextMock.new httpContextMock.cookieManager = CookieManagerMock.new + httpContextProvider = QueueIt::HttpContextProvider.new(httpContextMock) expiredDebugToken = QueueITTokenGenerator::generateDebugToken("eventId", "secretKey", true) - result = KnownUser.validateRequestByIntegrationConfig("http://test.com?event1=true", expiredDebugToken, "{}", "customerId", nil) + result = QueueIt::KnownUser.validateRequestByIntegrationConfig("http://test.com?event1=true", expiredDebugToken, "{}", "customerId", nil, httpContextProvider) assert("https://api2.queue-it.net/diagnostics/connector/error/?code=setup" == result.redirectUrl) assert(httpContextMock.cookieManager.cookieList.length == 0) @@ -1479,10 +1495,11 @@ def test_ValidateRequestByIntegrationConfig_Debug_Missing_Secretkey def test_ValidateRequestByIntegrationConfig_Debug_ExpiredToken httpContextMock = HttpContextMock.new httpContextMock.cookieManager = CookieManagerMock.new + httpContextProvider = QueueIt::HttpContextProvider.new(httpContextMock) expiredDebugToken = QueueITTokenGenerator::generateDebugToken("eventId", "secretKey", true) - result = KnownUser.validateRequestByIntegrationConfig("http://test.com?event1=true", expiredDebugToken, "{}", "customerId", "secretKey") + result = QueueIt::KnownUser.validateRequestByIntegrationConfig("http://test.com?event1=true", expiredDebugToken, "{}", "customerId", "secretKey", httpContextProvider) assert("https://customerId.api2.queue-it.net/customerId/diagnostics/connector/error/?code=timestamp" == result.redirectUrl) assert(httpContextMock.cookieManager.cookieList.length == 0) @@ -1491,10 +1508,11 @@ def test_ValidateRequestByIntegrationConfig_Debug_ExpiredToken def test_ValidateRequestByIntegrationConfig_Debug_ModifiedToken httpContextMock = HttpContextMock.new httpContextMock.cookieManager = CookieManagerMock.new + httpContextProvider = QueueIt::HttpContextProvider.new(httpContextMock) invalidDebugToken = QueueITTokenGenerator::generateDebugToken("eventId", "secretKey", false) + "invalid-hash" - result = KnownUser.validateRequestByIntegrationConfig("http://test.com?event1=true", invalidDebugToken, "{}", "customerId", "secretKey") + result = QueueIt::KnownUser.validateRequestByIntegrationConfig("http://test.com?event1=true", invalidDebugToken, "{}", "customerId", "secretKey", httpContextProvider) assert("https://customerId.api2.queue-it.net/customerId/diagnostics/connector/error/?code=hash" == result.redirectUrl) assert(httpContextMock.cookieManager.cookieList.length == 0) @@ -1502,7 +1520,6 @@ def test_ValidateRequestByIntegrationConfig_Debug_ModifiedToken def test_ResolveQueueRequestByLocalConfig_Debug userInQueueService = UserInQueueServiceMock.new - KnownUser.class_variable_set(:@@userInQueueService, userInQueueService) queueConfig = QueueEventConfig.new queueConfig.eventId = "eventId" @@ -1528,13 +1545,13 @@ def test_ResolveQueueRequestByLocalConfig_Debug "x-forwarded-host" => "xfh", "x-forwarded-proto" => "xfp" } - HttpContextProvider.setHttpContext(httpContextMock) + httpContextProvider = QueueIt::HttpContextProvider.new(httpContextMock, userInQueueService) secretKey = "secretKey" queueitToken = QueueITTokenGenerator::generateDebugToken("eventId", secretKey, false) expectedServerTime = Time.now.utc.iso8601 - KnownUser.resolveQueueRequestByLocalConfig("url", queueitToken, queueConfig, "customerId", secretKey) + QueueIt::KnownUser.resolveQueueRequestByLocalConfig("url", queueitToken, queueConfig, "customerId", secretKey, httpContextProvider) expectedCookieValue = "SdkVersion=" + UserInQueueService::SDK_VERSION + @@ -1567,7 +1584,6 @@ def test_ResolveQueueRequestByLocalConfig_Debug def test_ResolveQueueRequestByLocalConfig_Debug_NullConfig userInQueueService = UserInQueueServiceMock.new - KnownUser.class_variable_set(:@@userInQueueService, userInQueueService) httpContextMock = HttpContextMock.new httpContextMock.url = "http://localhost/original_url" @@ -1580,14 +1596,14 @@ def test_ResolveQueueRequestByLocalConfig_Debug_NullConfig "x-forwarded-host" => "xfh", "x-forwarded-proto" => "xfp" } - HttpContextProvider.setHttpContext(httpContextMock) + httpContextProvider = QueueIt::HttpContextProvider.new(httpContextMock, userInQueueService) queueitToken = QueueITTokenGenerator::generateDebugToken("eventId", "secretKey", false) expectedServerTime = Time.now.utc.iso8601 errorThrown = false begin - KnownUser.resolveQueueRequestByLocalConfig("http://test.com?event1=true", queueitToken, nil, "customerId", "secretKey") + QueueIt::KnownUser.resolveQueueRequestByLocalConfig("http://test.com?event1=true", queueitToken, nil, "customerId", "secretKey", httpContextProvider) rescue KnownUserError => err errmsg = err.message errorThrown = err.message.start_with? "queueConfig can not be nil." @@ -1619,11 +1635,12 @@ def test_ResolveQueueRequestByLocalConfig_Debug_NullConfig def test_ResolveQueueRequestByLocalConfig_Debug_Missing_CustomerId httpContextMock = HttpContextMock.new httpContextMock.cookieManager = CookieManagerMock.new + httpContextProvider = QueueIt::HttpContextProvider.new(httpContextMock) queueConfig = QueueEventConfig.new expiredDebugToken = QueueITTokenGenerator::generateDebugToken("eventId", "secretKey", true) - result = KnownUser.resolveQueueRequestByLocalConfig("http://test.com?event1=true", expiredDebugToken, queueConfig, nil, "secretKey") + result = QueueIt::KnownUser.resolveQueueRequestByLocalConfig("http://test.com?event1=true", expiredDebugToken, queueConfig, nil, "secretKey", httpContextProvider) assert("https://api2.queue-it.net/diagnostics/connector/error/?code=setup" == result.redirectUrl) assert(httpContextMock.cookieManager.cookieList.length == 0) @@ -1632,11 +1649,12 @@ def test_ResolveQueueRequestByLocalConfig_Debug_Missing_CustomerId def test_ResolveQueueRequestByLocalConfig_Debug_Missing_SecretKey httpContextMock = HttpContextMock.new httpContextMock.cookieManager = CookieManagerMock.new + httpContextProvider = QueueIt::HttpContextProvider.new(httpContextMock) queueConfig = QueueEventConfig.new expiredDebugToken = QueueITTokenGenerator::generateDebugToken("eventId", "secretKey", true) - result = KnownUser.resolveQueueRequestByLocalConfig("http://test.com?event1=true", expiredDebugToken, queueConfig, "customerId", nil) + result = QueueIt::KnownUser.resolveQueueRequestByLocalConfig("http://test.com?event1=true", expiredDebugToken, queueConfig, "customerId", nil, httpContextProvider) assert("https://api2.queue-it.net/diagnostics/connector/error/?code=setup" == result.redirectUrl) assert(httpContextMock.cookieManager.cookieList.length == 0) @@ -1645,11 +1663,12 @@ def test_ResolveQueueRequestByLocalConfig_Debug_Missing_SecretKey def test_ResolveQueueRequestByLocalConfig_Debug_ExpiredToken httpContextMock = HttpContextMock.new httpContextMock.cookieManager = CookieManagerMock.new + httpContextProvider = QueueIt::HttpContextProvider.new(httpContextMock) queueConfig = QueueEventConfig.new expiredDebugToken = QueueITTokenGenerator::generateDebugToken("eventId", "secretKey", true) - result = KnownUser.resolveQueueRequestByLocalConfig("http://test.com?event1=true", expiredDebugToken, queueConfig, "customerId", "secretKey") + result = QueueIt::KnownUser.resolveQueueRequestByLocalConfig("http://test.com?event1=true", expiredDebugToken, queueConfig, "customerId", "secretKey", httpContextProvider) assert("https://customerId.api2.queue-it.net/customerId/diagnostics/connector/error/?code=timestamp" == result.redirectUrl) assert(httpContextMock.cookieManager.cookieList.length == 0) @@ -1658,11 +1677,12 @@ def test_ResolveQueueRequestByLocalConfig_Debug_ExpiredToken def test_ResolveQueueRequestByLocalConfig_Debug_ModifiedToken httpContextMock = HttpContextMock.new httpContextMock.cookieManager = CookieManagerMock.new + httpContextProvider = QueueIt::HttpContextProvider.new(httpContextMock) queueConfig = QueueEventConfig.new invalidDebugToken = QueueITTokenGenerator::generateDebugToken("eventId", "secretKey", false) + "invalid-hash" - result = KnownUser.resolveQueueRequestByLocalConfig("http://test.com?event1=true", invalidDebugToken, queueConfig, "customerId", "secretKey") + result = QueueIt::KnownUser.resolveQueueRequestByLocalConfig("http://test.com?event1=true", invalidDebugToken, queueConfig, "customerId", "secretKey", httpContextProvider) assert("https://customerId.api2.queue-it.net/customerId/diagnostics/connector/error/?code=hash" == result.redirectUrl) assert(httpContextMock.cookieManager.cookieList.length == 0) @@ -1670,7 +1690,6 @@ def test_ResolveQueueRequestByLocalConfig_Debug_ModifiedToken def test_CancelRequestByLocalConfig_Debug userInQueueService = UserInQueueServiceMock.new - KnownUser.class_variable_set(:@@userInQueueService, userInQueueService) cancelConfig = CancelEventConfig.new cancelConfig.eventId = "eventId" @@ -1692,13 +1711,13 @@ def test_CancelRequestByLocalConfig_Debug "x-forwarded-host" => "xfh", "x-forwarded-proto" => "xfp" } - HttpContextProvider.setHttpContext(httpContextMock) + httpContextProvider = QueueIt::HttpContextProvider.new(httpContextMock, userInQueueService) secretKey = "secretKey" queueitToken = QueueITTokenGenerator::generateDebugToken("eventId", secretKey, false) expectedServerTime = Time.now.utc.iso8601 - KnownUser.cancelRequestByLocalConfig("url", queueitToken, cancelConfig, "customerId", secretKey) + QueueIt::KnownUser.cancelRequestByLocalConfig("url", queueitToken, cancelConfig, "customerId", secretKey, httpContextProvider) expectedCookieValue = "SdkVersion=" + UserInQueueService::SDK_VERSION + @@ -1727,7 +1746,6 @@ def test_CancelRequestByLocalConfig_Debug def test_CancelRequestByLocalConfig_Debug_NullConfig userInQueueService = UserInQueueServiceMock.new - KnownUser.class_variable_set(:@@userInQueueService, userInQueueService) httpContextMock = HttpContextMock.new httpContextMock.url = "http://localhost/original_url" @@ -1740,14 +1758,14 @@ def test_CancelRequestByLocalConfig_Debug_NullConfig "x-forwarded-host" => "xfh", "x-forwarded-proto" => "xfp" } - HttpContextProvider.setHttpContext(httpContextMock) + httpContextProvider = QueueIt::HttpContextProvider.new(httpContextMock, userInQueueService) queueitToken = QueueITTokenGenerator::generateDebugToken("eventId", "secretKey", false) expectedServerTime = Time.now.utc.iso8601 errorThrown = false begin - KnownUser.cancelRequestByLocalConfig("http://test.com?event1=true", queueitToken, nil, "customerId", "secretKey") + QueueIt::KnownUser.cancelRequestByLocalConfig("http://test.com?event1=true", queueitToken, nil, "customerId", "secretKey", httpContextProvider) rescue KnownUserError => err errmsg = err.message errorThrown = err.message.start_with? "cancelConfig can not be nil." @@ -1779,13 +1797,13 @@ def test_CancelRequestByLocalConfig_Debug_NullConfig def test_CancelRequestByLocalConfig_Debug_Missing_CustomerId httpContextMock = HttpContextMock.new httpContextMock.cookieManager = CookieManagerMock.new - HttpContextProvider.setHttpContext(httpContextMock) + httpContextProvider = QueueIt::HttpContextProvider.new(httpContextMock) cancelConfig = CancelEventConfig.new expiredDebugToken = QueueITTokenGenerator::generateDebugToken("eventId", "secretKey", true) - result = KnownUser.cancelRequestByLocalConfig( - "http://test.com?event1=true", expiredDebugToken, cancelConfig, nil, "secretKey") + result = QueueIt::KnownUser.cancelRequestByLocalConfig( + "http://test.com?event1=true", expiredDebugToken, cancelConfig, nil, "secretKey", httpContextProvider) assert("https://api2.queue-it.net/diagnostics/connector/error/?code=setup" == result.redirectUrl) assert(httpContextMock.cookieManager.cookieList.length == 0) @@ -1794,13 +1812,13 @@ def test_CancelRequestByLocalConfig_Debug_Missing_CustomerId def test_CancelRequestByLocalConfig_Debug_Missing_SecretKey httpContextMock = HttpContextMock.new httpContextMock.cookieManager = CookieManagerMock.new - HttpContextProvider.setHttpContext(httpContextMock) + httpContextProvider = QueueIt::HttpContextProvider.new(httpContextMock) cancelConfig = CancelEventConfig.new expiredDebugToken = QueueITTokenGenerator::generateDebugToken("eventId", "secretKey", true) - result = KnownUser.cancelRequestByLocalConfig( - "http://test.com?event1=true", expiredDebugToken, cancelConfig, "customerId", nil) + result = QueueIt::KnownUser.cancelRequestByLocalConfig( + "http://test.com?event1=true", expiredDebugToken, cancelConfig, "customerId", nil, httpContextProvider) assert("https://api2.queue-it.net/diagnostics/connector/error/?code=setup" == result.redirectUrl) assert(httpContextMock.cookieManager.cookieList.length == 0) @@ -1809,13 +1827,13 @@ def test_CancelRequestByLocalConfig_Debug_Missing_SecretKey def test_CancelRequestByLocalConfig_Debug_ExpiredToken httpContextMock = HttpContextMock.new httpContextMock.cookieManager = CookieManagerMock.new - HttpContextProvider.setHttpContext(httpContextMock) + httpContextProvider = QueueIt::HttpContextProvider.new(httpContextMock) cancelConfig = CancelEventConfig.new expiredDebugToken = QueueITTokenGenerator::generateDebugToken("eventId", "secretKey", true) - result = KnownUser.cancelRequestByLocalConfig( - "http://test.com?event1=true", expiredDebugToken, cancelConfig, "customerId", "secretKey") + result = QueueIt::KnownUser.cancelRequestByLocalConfig( + "http://test.com?event1=true", expiredDebugToken, cancelConfig, "customerId", "secretKey", httpContextProvider) assert("https://customerId.api2.queue-it.net/customerId/diagnostics/connector/error/?code=timestamp" == result.redirectUrl) assert(httpContextMock.cookieManager.cookieList.length == 0) @@ -1824,13 +1842,13 @@ def test_CancelRequestByLocalConfig_Debug_ExpiredToken def test_CancelRequestByLocalConfig_Debug_ModifiedToken httpContextMock = HttpContextMock.new httpContextMock.cookieManager = CookieManagerMock.new - HttpContextProvider.setHttpContext(httpContextMock) + httpContextProvider = QueueIt::HttpContextProvider.new(httpContextMock) cancelConfig = CancelEventConfig.new invalidDebugToken = QueueITTokenGenerator::generateDebugToken("eventId", "secretKey", false) + "invalid-hash" - result = KnownUser.cancelRequestByLocalConfig( - "http://test.com?event1=true", invalidDebugToken, cancelConfig, "customerId", "secretKey") + result = QueueIt::KnownUser.cancelRequestByLocalConfig( + "http://test.com?event1=true", invalidDebugToken, cancelConfig, "customerId", "secretKey", httpContextProvider) assert("https://customerId.api2.queue-it.net/customerId/diagnostics/connector/error/?code=hash" == result.redirectUrl) assert(httpContextMock.cookieManager.cookieList.length == 0) @@ -1838,7 +1856,6 @@ def test_CancelRequestByLocalConfig_Debug_ModifiedToken def test_CancelRequestByLocalConfig_Exception_NoDebugToken_NoDebugCookie userInQueueService = UserInQueueServiceMock.new - KnownUser.class_variable_set(:@@userInQueueService, userInQueueService) cancelConfig = CancelEventConfig.new cancelConfig.eventId = "eventId" @@ -1858,11 +1875,12 @@ def test_CancelRequestByLocalConfig_Exception_NoDebugToken_NoDebugCookie "x-forwarded-host" => "xfh", "x-forwarded-proto" => "xfp" } - HttpContextProvider.setHttpContext(httpContextMock) + httpContextMock.cookieManager = CookieManagerMock.new + httpContextProvider = QueueIt::HttpContextProvider.new(httpContextMock, userInQueueService) userInQueueService.validateCancelRequestRaiseException = true begin - result = KnownUser.cancelRequestByLocalConfig("targetUrl", "token", cancelConfig, "customerId", "secretKey") + result = QueueIt::KnownUser.cancelRequestByLocalConfig("targetUrl", "token", cancelConfig, "customerId", "secretKey", httpContextProvider) rescue Exception => e assert(e.message == "Exception") end @@ -1872,7 +1890,6 @@ def test_CancelRequestByLocalConfig_Exception_NoDebugToken_NoDebugCookie def test_ValidateRequestByIntegrationConfig_Exception_NoDebugToken_NoDebugCookie userInQueueService = UserInQueueServiceMock.new - KnownUser.class_variable_set(:@@userInQueueService, userInQueueService) integrationConfig = { :Description => "test", @@ -1923,11 +1940,11 @@ def test_ValidateRequestByIntegrationConfig_Exception_NoDebugToken_NoDebugCookie "x-forwarded-host" => "xfh", "x-forwarded-proto" => "xfp" } - HttpContextProvider.setHttpContext(httpContextMock) + httpContextProvider = QueueIt::HttpContextProvider.new(httpContextMock, userInQueueService) userInQueueService.validateCancelRequestRaiseException = true begin - result = KnownUser.validateRequestByIntegrationConfig("http://test.com?event1=true", "queueIttoken", integrationConfigJson, "customerid", "secretkey") + result = QueueIt::KnownUser.validateRequestByIntegrationConfig("http://test.com?event1=true", "queueIttoken", integrationConfigJson, "customerid", "secretkey", httpContextProvider) rescue Exception => e assert(e.message == "Exception") end @@ -1937,7 +1954,6 @@ def test_ValidateRequestByIntegrationConfig_Exception_NoDebugToken_NoDebugCookie def test_ResolveQueueRequestByLocalConfig_Exception_NoDebugToken_NoDebugCookie userInQueueService = UserInQueueServiceMock.new - KnownUser.class_variable_set(:@@userInQueueService, userInQueueService) queueConfig = QueueEventConfig.new queueConfig.cookieDomain = "cookieDomain" @@ -1961,11 +1977,11 @@ def test_ResolveQueueRequestByLocalConfig_Exception_NoDebugToken_NoDebugCookie "x-forwarded-host" => "xfh", "x-forwarded-proto" => "xfp" } - HttpContextProvider.setHttpContext(httpContextMock) + httpContextProvider = QueueIt::HttpContextProvider.new(httpContextMock, userInQueueService) userInQueueService.validateQueueRequestRaiseException = true begin - result = KnownUser.resolveQueueRequestByLocalConfig("target", "token", queueConfig, "id", "key") + result = QueueIt::KnownUser.resolveQueueRequestByLocalConfig("target", "token", queueConfig, "id", "key", httpContextProvider) rescue Exception => e assert(e.message == "Exception") end diff --git a/test/queueit_knownuserv3/test_user_in_queue_service.rb b/test/queueit_knownuserv3/test_user_in_queue_service.rb index d5b1b89..078e64c 100644 --- a/test/queueit_knownuserv3/test_user_in_queue_service.rb +++ b/test/queueit_knownuserv3/test_user_in_queue_service.rb @@ -82,6 +82,12 @@ def expectCallAny(functionName) end end + class UserInQueueServiceTestable < UserInQueueService + def validateToken(config, queueParams, secretKey) + return nil + end + end + class TestUserInQueueService < Test::Unit::TestCase def test_ValidateQueueRequest_ValidState_ExtendableCookie_NoCookieExtensionFromConfig_DoNotRedirectDoNotStoreCookieWithExtension queueConfig = QueueEventConfig.new @@ -309,6 +315,29 @@ def test_ValidateQueueRequest_NoCookie_ValidToken_CookieValidityMinuteFromToken_ assert(!cookieProviderMock.expectCallAny('cancelQueueCookie')) end + def test_ValidateQueueRequest_InvalidToken_validateTokenReturnsNull_DoRedirect + key = "4e1db821-a825-49da-acd0-5d376f2068db" + queueConfig = QueueEventConfig.new + queueConfig.eventId = "e1" + queueConfig.queueDomain = "testDomain.com" + queueConfig.cookieValidityMinute = 30 + queueConfig.cookieDomain = "testDomain" + queueConfig.isCookieHttpOnly = false + queueConfig.isCookieSecure = false + queueConfig.extendCookieValidity = true + queueConfig.version = 11 + queueConfig.actionName = "QueueAction" + url = "http://test.test.com?b=h" + cookieProviderMock = UserInQueueStateRepositoryMockClass.new() + cookieProviderMock.arrayReturns['getState'].push(StateInfo.new(false, false, nil, nil, nil)) + token = generateHash('e1', 'queueId',(Time.now.getutc.to_i + (3 * 60)).to_s, 'false', 3, 'DirectLink', key) + testObject = UserInQueueServiceTestable.new(cookieProviderMock) + result = testObject.validateQueueRequest(url, token, queueConfig, "testCustomer", key) + assert(result.doRedirect()) + assert(result.eventId == 'e1') + assert(result.queueId == nil) + end + def test_ValidateQueueRequest_NoCookie_WithoutToken_RedirectToQueue() key = "4e1db821-a825-49da-acd0-5d376f2068db" queueConfig = QueueEventConfig.new