From bcd2a9a55b7602d676201c0492fe83d77e0b7e45 Mon Sep 17 00:00:00 2001 From: Frederik Williams Date: Tue, 8 Dec 2020 13:48:29 +0100 Subject: [PATCH] Release 3.6.4 --- Examples/ApacheHandlerUsingConfigFromFile.lua | 35 +- Handlers/KnownUserApacheHandler.lua | 93 +- SDK/ComparisonOperatorHelper.lua | 72 +- SDK/IntegrationEvaluator.lua | 52 +- SDK/KnownUser.lua | 178 ++-- SDK/KnownUserImplementationHelpers.lua | 45 +- SDK/Models.lua | 50 +- SDK/QueueITHelpers.lua | 56 +- SDK/Tests/ComparisonOperatorHelperTest.lua | 2 +- SDK/Tests/IntegrationEvaluatorTest.lua | 126 +-- .../KnownUserImplementationHelpersTest.lua | 490 +++++++++- SDK/Tests/KnownUserTest.lua | 867 ++++++++++-------- SDK/Tests/QueueUrlParamsTest.lua | 30 +- SDK/Tests/UserInQueueServiceTest.lua | 283 +++--- .../UserInQueueStateCookieRepositoryTest.lua | 331 +++---- SDK/Tests/ValidationHelpersTest.lua | 173 ++-- SDK/Tests/_RUNALL.lua | 2 +- SDK/UserInQueueService.lua | 64 +- SDK/UserInQueueStateCookieRepository.lua | 61 +- SDK/Utils.lua | 12 +- SDK/ValidatorHelpers.lua | 87 +- 21 files changed, 1849 insertions(+), 1260 deletions(-) diff --git a/Examples/ApacheHandlerUsingConfigFromFile.lua b/Examples/ApacheHandlerUsingConfigFromFile.lua index ddde5cc..8b31911 100644 --- a/Examples/ApacheHandlerUsingConfigFromFile.lua +++ b/Examples/ApacheHandlerUsingConfigFromFile.lua @@ -14,14 +14,11 @@ --... * QUEUEIT_INT_CONF_FILE: The local JSON file containing the integration configuration -- * QUEUEIT_ERROR_CODE: (optional) The response code to use instead of declining to act -- if request handling fails --- * QUEUEIT_COOKIE_OPTIONS_HTTPONLY: (optional) Set to "true" if you want cookies with httponly --- flag set. Only enable if this you use pure server-side integration +-- * QUEUEIT_COOKIE_OPTIONS_HTTPONLY: (optional) Set to "true" if you want cookies with httponly +-- flag set. Only enable if this you use pure server-side integration -- e.g. not JS Hybrid. --- * QUEUEIT_COOKIE_OPTIONS_SECURE: (optional) Set to "true" if you want cookies with secure +-- * QUEUEIT_COOKIE_OPTIONS_SECURE: (optional) Set to "true" if you want cookies with secure -- flag set. Only enable if your website runs purely on https. --- * QUEUEIT_COOKIE_OPTIONS_SAMESITE: (optional) set to any of these values --- "none", "strict" or "lax" if response cookies should have samesite flag set. --- only use 'strict' if your queue protected site stays on same domain (no navigation to subdomains). -- Note that the integration configuration is read on every request. The JSON file containing -- The integration configuration should, for performance reasons, be available locally. -- @@ -35,7 +32,6 @@ -- SetEnv QUEUEIT_ERROR_CODE "400" -- SetEnv QUEUEIT_COOKIE_OPTIONS_HTTPONLY "false" -- SetEnv QUEUEIT_COOKIE_OPTIONS_SECURE "false" --- SetEnv QUEUEIT_COOKIE_OPTIONS_SAMESITE "none" -- LuaMapHandler "{URI_PATTERN}" "{APP_FOLDER}/Handlers/ApacheHandlerUsingConfigFromFile.lua" -- LuaPackagePath "{APP_FOLDER}/SDK/?.lua" -- LuaPackagePath "{APP_FOLDER}/Helpers/?/?.lua" @@ -58,10 +54,9 @@ local function initRequiredHelpers(r, cookieOptions) local iHelpers = require("KnownUserImplementationHelpers") iHelpers.request.getAbsoluteUri = function() - local fullUrl = string.format("%s://%s:%s%s", + local fullUrl = string.format("%s://%s%s", r.is_https and "https" or "http", r.hostname, - r.port, r.unparsed_uri) r:debug(string.format("[%s] Rebuilt request URL as: %s", DEBUG_TAG, fullUrl)) return fullUrl @@ -78,23 +73,21 @@ function handle(r) -- catch errors if any occur local success, result = pcall(function() - -- get configuration from environment variables + -- get configuration from environment variables local customerId = r.subprocess_env["QUEUEIT_CUSTOMER_ID"] local secretKey = r.subprocess_env["QUEUEIT_SECRET_KEY"] local intConfFile = r.subprocess_env["QUEUEIT_INT_CONF_FILE"] - local errorCode = r.subprocess_env["QUEUEIT_ERROR_CODE"] + local errorCode = r.subprocess_env["QUEUEIT_ERROR_CODE"] local co_httpOnly = r.subprocess_env["QUEUEIT_COOKIE_OPTIONS_HTTPONLY"] local co_secure = r.subprocess_env["QUEUEIT_COOKIE_OPTIONS_SECURE"] - local co_sameSite = r.subprocess_env["QUEUEIT_COOKIE_OPTIONS_SAMESITE"] - + r:debug(string.format("[%s] Environment variable QUEUEIT_CUSTOMER_ID: %s", DEBUG_TAG, customerId)) r:debug(string.format("[%s] Environment variable QUEUEIT_SECRET_KEY: %s", DEBUG_TAG, secretKey)) r:debug(string.format("[%s] Environment variable QUEUEIT_INT_CONF_FILE: %s", DEBUG_TAG, intConfFile)) r:debug(string.format("[%s] Environment variable QUEUEIT_ERROR_CODE: %s", DEBUG_TAG, errorCode)) r:debug(string.format("[%s] Environment variable QUEUEIT_COOKIE_OPTIONS_HTTPONLY: %s", DEBUG_TAG, co_httpOnly)) r:debug(string.format("[%s] Environment variable QUEUEIT_COOKIE_OPTIONS_SECURE: %s", DEBUG_TAG, co_secure)) - r:debug(string.format("[%s] Environment variable QUEUEIT_COOKIE_OPTIONS_SAMESITE: %s", DEBUG_TAG, co_sameSite)) - + assert(customerId ~= nil, "customerId invalid") assert(secretKey ~= nil, "secretKey invalid") assert(intConfFile ~= nil, "config invalid") @@ -103,7 +96,9 @@ function handle(r) if (errorCode ~= nil) then errorCode = tonumber(errorCode) if (errorCode == nil) then - r:warn(string.format("[%s] Value of QUEUEIT_ERROR_CODE is not a valid HTTP status code: %s", DEBUG_TAG, r.subprocess_env["QUEUEIT_ERROR_CODE"])) + r:warn(string.format( + "[%s] Value of QUEUEIT_ERROR_CODE is not a valid HTTP status code: %s", + DEBUG_TAG, r.subprocess_env["QUEUEIT_ERROR_CODE"])) elseif (errorCode >= 100) and (errorCode < 600) then errorResult = errorCode end @@ -111,16 +106,14 @@ function handle(r) r:debug(string.format("[%s] Value of variable errorCode: %s", DEBUG_TAG, errorCode)) -- configure cookie options - local cookieOptions = + local cookieOptions = { httpOnly = false, - secure = false, - sameSite = nil + secure = false } - + if (co_httpOnly ~= nil and co_httpOnly == 'true') then cookieOptions.httpOnly = true end if (co_secure ~= nil and co_secure == 'true') then cookieOptions.secure = true end - if (co_sameSite ~= nil and (co_sameSite == 'none' or co_sameSite == 'lax' or co_sameSite == 'strict' )) then cookieOptions.sameSite = co_sameSite end -- initialize helper functions initRequiredHelpers(r, cookieOptions) diff --git a/Handlers/KnownUserApacheHandler.lua b/Handlers/KnownUserApacheHandler.lua index d272c48..c205970 100644 --- a/Handlers/KnownUserApacheHandler.lua +++ b/Handlers/KnownUserApacheHandler.lua @@ -1,6 +1,6 @@ -iHelpers = require("KnownUserImplementationHelpers") -knownUser = require("KnownUser") -utils = require("Utils") +local iHelpers = require("KnownUserImplementationHelpers") +local knownUser = require("KnownUser") +local utils = require("Utils") local aHandler = {} @@ -9,10 +9,10 @@ local function handle(customerId, secretKey, config, isIntegrationConfig, reques assert(secretKey ~= nil, "secretKey invalid") assert(config ~= nil, "config invalid") assert(isIntegrationConfig ~= nil, "isIntegrationConfig invalid") - assert(request_rec ~= nil, "request_rec invalid") - + assert(request_rec ~= nil, "request_rec invalid") + -- Implement required helpers - -- ******************************************************************************** + -- ******************************************************************************** iHelpers.system.getConnectorName = function() return apache2.version end @@ -21,72 +21,72 @@ local function handle(customerId, secretKey, config, isIntegrationConfig, reques local json = require("json") return json.parse(jsonStr) end - + iHelpers.hash.hmac_sha256_encode = function(message, key) local sha2 = require("sha2") return sha2.hmac(sha2.sha256, key, message) end - + iHelpers.request.getHeader = function(name) return request_rec.headers_in[name] end - + iHelpers.request.getUnescapedCookieValue = function(name) - -- Alternative to request_rec:getcookie method, + -- Alternative to request_rec:getcookie method, -- which fails if client sends a Cookie header with multiple entries with same name/key. - local function getCookieValue(name) - local function split(inputstr, sep) - sep=sep or '%s' local t={} - for field,s in string.gmatch(inputstr, "([^"..sep.."]*)("..sep.."?)") do - table.insert(t,field) - if s=="" then - return t - end - end + local function getCookieValue(_name) + local function split(inputstr, sep) + sep=sep or '%s' local t={} + for field,s in string.gmatch(inputstr, "([^"..sep.."]*)("..sep.."?)") do + table.insert(t,field) + if s=="" then + return t + end + end end - - if (name == nil) then + + if (_name == nil) then return nil end local cookieHeader = request_rec.headers_in["Cookie"] - + if(cookieHeader == nil) then return nil end - + local cookieHeaderParts = split(cookieHeader, ";") - + if (cookieHeaderParts == nil) then return nil end - + -- Translate name to pattern so it will work correctly in string.find - -- ex. translate 'QueueITAccepted-SDFrts345E-V3_event1' to 'QueueITAccepted--SDFrts345E--V3_event1=' - name = name:gsub("-", "--") .. "=" - - for k, v in pairs(cookieHeaderParts) do - startIndex, endIndex = string.find(v, name) - + -- ex. translate 'QueueITAccepted-SDFrts345E-V3_event1' to 'QueueITAccepted--SDFrts345E--V3_event1=' + _name = _name:gsub("-", "--") .. "=" + + for _, v in pairs(cookieHeaderParts) do + local _, endIndex = string.find(v, _name) + if(endIndex ~= nil) then return v:sub(endIndex + 1) end end end - + local cookieValue = getCookieValue(name) - + if (cookieValue ~= nil) then cookieValue = utils.urlDecode(cookieValue) end return cookieValue end - + iHelpers.request.getUserHostAddress = function() return request_rec.useragent_ip end - + -- Implementation is not using built in r:setcookie method -- because we want to support Apache version < 2.4.12 -- where there is bug in that specific method @@ -98,11 +98,11 @@ local function handle(customerId, secretKey, config, isIntegrationConfig, reques if (domain == nil) then domain = "" end - + if (value == nil) then value = "" end - + value = utils.urlEncode(value) local expire_text = '' @@ -110,39 +110,38 @@ local function handle(customerId, secretKey, config, isIntegrationConfig, reques expire_text = '; Expires=' .. os.date("!%a, %d %b %Y %H:%M:%S GMT", expire) end - request_rec.err_headers_out["Set-Cookie"] = name .. '=' .. value + request_rec.err_headers_out["Set-Cookie"] = name .. '=' .. value .. expire_text - .. (domain ~= "" and '; Domain=' .. domain or '') + .. (domain ~= "" and '; Domain=' .. domain or '') .. (iHelpers.response.cookieOptions.httpOnly and '; HttpOnly' or '') .. (iHelpers.response.cookieOptions.secure and '; Secure' or '') - .. (iHelpers.response.cookieOptions.sameSite and '; SameSite=' .. iHelpers.response.cookieOptions.sameSite or '') .. '; Path=/;' - + end -- ******************************************************************************** -- END Implement required helpers local queueitToken = request_rec:parseargs()["queueittoken"] local fullUrl = iHelpers.request.getAbsoluteUri() - local currentUrlWithoutQueueitToken = fullUrl:gsub("([\\%?%&])(" .. knownUser.QUEUEIT_TOKEN_KEY .. "=[^&]*)", "") + local currentUrlWithoutQueueitToken = fullUrl:gsub("([\\%?%&])(" .. knownUser.QUEUEIT_TOKEN_KEY .. "=[^&]*)", "") - local validationResult = nil + local validationResult if (isIntegrationConfig) then validationResult = knownUser.validateRequestByIntegrationConfig(currentUrlWithoutQueueitToken, queueitToken, config, customerId, secretKey) else validationResult = knownUser.resolveQueueRequestByLocalConfig(currentUrlWithoutQueueitToken, queueitToken, config, customerId, secretKey) end - + if (validationResult:doRedirect()) then --Adding no cache headers to prevent browsers to cache requests request_rec.err_headers_out["Cache-Control"] = "no-cache, no-store, must-revalidate, max-age=0" request_rec.err_headers_out["Pragma"] = "no-cache" request_rec.err_headers_out["Expires"] = "Fri, 01 Jan 1990 00:00:00 GMT" --end - + if (validationResult.isAjaxResult) then request_rec.err_headers_out[validationResult.getAjaxQueueRedirectHeaderKey()] = validationResult:getAjaxRedirectUrl() - else + else request_rec.err_headers_out["Location"] = validationResult.redirectUrl return apache2.HTTP_MOVED_TEMPORARILY end @@ -153,7 +152,7 @@ local function handle(customerId, secretKey, config, isIntegrationConfig, reques return apache2.HTTP_MOVED_TEMPORARILY end end - + return apache2.DECLINED end diff --git a/SDK/ComparisonOperatorHelper.lua b/SDK/ComparisonOperatorHelper.lua index a03e306..1a20ef4 100644 --- a/SDK/ComparisonOperatorHelper.lua +++ b/SDK/ComparisonOperatorHelper.lua @@ -3,65 +3,65 @@ local utils = require("Utils") local model = { evaluate = function(opt, isNegative, isIgnoreCase, value, valueToCompare, valuesToCompare) -- Private functions - local function contains(value, valueToCompare, isNegative, ignoreCase) - if (valueToCompare == "*" and (not utils.isNilOrEmpty(value))) then + local function contains(_value, _valueToCompare, _isNegative, _isIgnoreCase) + if (_valueToCompare == "*" and (not utils.isNilOrEmpty(_value))) then return true end - if (ignoreCase) then - value = string.upper(value) - valueToCompare = string.upper(valueToCompare) + if (_isIgnoreCase) then + _value = string.upper(_value) + _valueToCompare = string.upper(_valueToCompare) end - - local evaluation = utils:contains(value, valueToCompare) - - if (isNegative) then + + local evaluation = utils:contains(_value, _valueToCompare) + + if (_isNegative) then return not evaluation - else + else return evaluation end end - - local function equals(value, valueToCompare, isNegative, ignoreCase) - if (ignoreCase) then - value = string.upper(value) - valueToCompare = string.upper(valueToCompare) + + local function equals(_value, _valueToCompare, _isNegative, _isIgnoreCase) + if (_isIgnoreCase) then + _value = string.upper(_value) + _valueToCompare = string.upper(_valueToCompare) end - local evaluation = value == valueToCompare + local evaluation = _value == _valueToCompare - if (isNegative) then + if (_isNegative) then return not evaluation else return evaluation end end - - local function equalsAny(value, valuesToCompare, isNegative, ignoreCase) - for i, vToCompare in pairs(valuesToCompare) do - if(equals(value, vToCompare, false, ignoreCase)) then - return not isNegative + + local function equalsAny(_value, _valuesToCompare, _isNegative, _isIgnoreCase) + for _, vToCompare in pairs(_valuesToCompare) do + if(equals(_value, vToCompare, false, _isIgnoreCase)) then + return not _isNegative end end - return isNegative + return _isNegative end - local function containsAny(value, valuesToCompare, isNegative, ignoreCase) - for i, vToCompare in pairs(valuesToCompare) do - if(contains(value, vToCompare, false, ignoreCase)) then - return not isNegative + local function containsAny(_value, _valuesToCompare, _isNegative, _isIgnoreCase) + for _, vToCompare in pairs(_valuesToCompare) do + if(contains(_value, vToCompare, false, _isIgnoreCase)) then + return not _isNegative end end - - return isNegative + + return _isNegative end - if (value == nil) then - value = "" + if (value == nil) then + value = "" end - if (valueToCompare == nil) then - valueToCompare = "" + if (valueToCompare == nil) then + valueToCompare = "" end - if (utils.isTable(valuesToCompare) == false) then + if (utils.isTable(valuesToCompare) == false) then valuesToCompare = {} end @@ -69,7 +69,7 @@ local model = { return equals(value, valueToCompare, isNegative, isIgnoreCase) end if (opt == "Contains") then - return contains(value, valueToCompare, isNegative, isIgnoreCase) + return contains(value, valueToCompare, isNegative, isIgnoreCase) end if (opt == "EqualsAny") then return equalsAny(value, valuesToCompare, isNegative, isIgnoreCase) @@ -79,7 +79,7 @@ local model = { end return false - end + end } return model \ No newline at end of file diff --git a/SDK/IntegrationEvaluator.lua b/SDK/IntegrationEvaluator.lua index 4934a6c..3a59186 100644 --- a/SDK/IntegrationEvaluator.lua +++ b/SDK/IntegrationEvaluator.lua @@ -2,52 +2,52 @@ local utils = require("Utils") local validatorHelpers = require("ValidatorHelpers") local model = { - getMatchedIntegrationConfig = function(customerIntegration, currentPageUrl, request) + getMatchedIntegrationConfig = function(customerIntegration, currentPageUrl, request) -- Private functions - local function evaluateTriggerPart(triggerPart, currentPageUrl, request) - if (triggerPart["ValidatorType"] == nil) then + local function evaluateTriggerPart(_triggerPart, _currentPageUrl, _request) + if (_triggerPart["ValidatorType"] == nil) then return false end - if (triggerPart["ValidatorType"] == "UrlValidator") then - return validatorHelpers.UrlValidatorHelper.evaluate(triggerPart, currentPageUrl) + if (_triggerPart["ValidatorType"] == "UrlValidator") then + return validatorHelpers.UrlValidatorHelper.evaluate(_triggerPart, _currentPageUrl) end - if (triggerPart["ValidatorType"] == "CookieValidator") then - return validatorHelpers.CookieValidatorHelper.evaluate(triggerPart, request) + if (_triggerPart["ValidatorType"] == "CookieValidator") then + return validatorHelpers.CookieValidatorHelper.evaluate(_triggerPart, _request) end - if (triggerPart["ValidatorType"] == "UserAgentValidator") then - return validatorHelpers.UserAgentValidatorHelper.evaluate(triggerPart, request) + if (_triggerPart["ValidatorType"] == "UserAgentValidator") then + return validatorHelpers.UserAgentValidatorHelper.evaluate(_triggerPart, _request) end - if (triggerPart["ValidatorType"] == "HttpHeaderValidator") then - return validatorHelpers.HttpHeaderValidatorHelper.evaluate(triggerPart, request) + if (_triggerPart["ValidatorType"] == "HttpHeaderValidator") then + return validatorHelpers.HttpHeaderValidatorHelper.evaluate(_triggerPart, _request) end return false end - - local function evaluateTrigger(trigger, currentPageUrl, request) - if (trigger["LogicalOperator"] == nil or - trigger["TriggerParts"] == nil or - trigger["TriggerParts"] == nil) then + + local function evaluateTrigger(_trigger, _currentPageUrl, _request) + if (_trigger["LogicalOperator"] == nil or + _trigger["TriggerParts"] == nil or + _trigger["TriggerParts"] == nil) then return false end - if (trigger["LogicalOperator"] == 'Or') then - for i, triggerPart in pairs(trigger["TriggerParts"]) do + if (_trigger["LogicalOperator"] == 'Or') then + for _, triggerPart in pairs(_trigger["TriggerParts"]) do if (utils.isTable(triggerPart) == false) then return false end - if (evaluateTriggerPart(triggerPart, currentPageUrl, request)) then + if (evaluateTriggerPart(triggerPart, _currentPageUrl, _request)) then return true end end return false else - for i, triggerPart in pairs(trigger["TriggerParts"]) do + for _, triggerPart in pairs(_trigger["TriggerParts"]) do if (utils.isTable(triggerPart) == false) then return false end - if (evaluateTriggerPart(triggerPart, currentPageUrl, request) == false) then + if (evaluateTriggerPart(triggerPart, _currentPageUrl, _request) == false) then return false end end @@ -55,19 +55,19 @@ local model = { end end -- END Private functions - - if (utils.isTable(customerIntegration["Integrations"]) == false) then + + if (utils.isTable(customerIntegration["Integrations"]) == false) then return nil end - for i, integrationConfig in pairs(customerIntegration["Integrations"]) do + for _, integrationConfig in pairs(customerIntegration["Integrations"]) do if (utils.isTable(integrationConfig)) then if (utils.isTable(integrationConfig["Triggers"])) then - for y, trigger in pairs(integrationConfig["Triggers"]) do + for _, trigger in pairs(integrationConfig["Triggers"]) do if (utils.isTable(trigger) == false) then return false end - if (evaluateTrigger(trigger, currentPageUrl, request)) then + if (evaluateTrigger(trigger, currentPageUrl, request)) then return integrationConfig end end diff --git a/SDK/KnownUser.lua b/SDK/KnownUser.lua index b9f59c3..56551d0 100644 --- a/SDK/KnownUser.lua +++ b/SDK/KnownUser.lua @@ -6,18 +6,18 @@ local utils = require("Utils") local iHelpers = require("KnownUserImplementationHelpers") local ku = { - QUEUEIT_TOKEN_KEY = "queueittoken" + QUEUEIT_TOKEN_KEY = "queueittoken" } local QUEUEIT_DEBUG_KEY = "queueitdebug" local QUEUEIT_AJAX_HEADER_KEY = "x-queueit-ajaxpageurl" -- Private functions -local function isQueueAjaxCall() +local function isQueueAjaxCall() return iHelpers.request.getHeader(QUEUEIT_AJAX_HEADER_KEY) ~= nil end -local function logMoreRequestDetails(debugEntries) +local function logMoreRequestDetails(debugEntries) debugEntries["ServerUtcTime"] = os.date("!%Y-%m-%dT%H:%M:%SZ") debugEntries["RequestIP"] = iHelpers.request.getUserHostAddress() debugEntries["RequestHttpHeader_Via"] = utils.toString(iHelpers.request.getHeader('via')) @@ -31,7 +31,7 @@ local function setDebugCookie(debugEntries) if(utils.tableLength(debugEntries) == 0) then return end - + local cookieValue = "" for key, value in pairs(debugEntries) do cookieValue = cookieValue .. (key .. "=" .. value .. "|") @@ -53,14 +53,15 @@ local function getRuntime() return _VERSION end -local function resolveQueueRequestByLocalConfig(targetUrl, queueitToken, queueConfig, customerId, secretKey, debugEntries, isDebug) +local function resolveQueueRequestByLocalConfig( + targetUrl, queueitToken, queueConfig,customerId, secretKey, debugEntries, isDebug) - if (isDebug) then + if (isDebug) then local queueConfigValue = "NULL" if (queueConfig ~= nil) then queueConfigValue = queueConfig:getString() end - + debugEntries["SdkVersion"] = userInQueueService.SDK_VERSION debugEntries["Connector"] = iHelpers.system.getConnectorName() debugEntries["Runtime"] = getRuntime() @@ -68,32 +69,37 @@ local function resolveQueueRequestByLocalConfig(targetUrl, queueitToken, queueCo debugEntries["QueueitToken"] = queueitToken debugEntries["QueueConfig"] = queueConfigValue debugEntries["OriginalUrl"] = iHelpers.request.getAbsoluteUri() - + logMoreRequestDetails(debugEntries) - end - + end + assert(utils.toString(customerId) ~= "", "customerId can not be nil or empty.") assert(utils.toString(secretKey) ~= "", "secretKey can not be nil or empty.") assert(queueConfig ~= nil, "queueConfig can not be nil.") assert(utils.toString(queueConfig.eventId) ~= "", "eventId from queueConfig can not be nil or empty.") assert(utils.toString(queueConfig.queueDomain) ~= "", "queueDomain from queueConfig can not be nil or empty.") - assert(type(queueConfig.cookieValidityMinute) == "number" and queueConfig.cookieValidityMinute > 0, "cookieValidityMinute from queueConfig should be a number greater than 0.") - assert(type(queueConfig.extendCookieValidity) == "boolean", "extendCookieValidity from queueConfig should be valid boolean.") - + assert( + type(queueConfig.cookieValidityMinute) == "number" + and queueConfig.cookieValidityMinute > 0, "cookieValidityMinute from queueConfig should be a number greater than 0.") + assert( + type(queueConfig.extendCookieValidity) == "boolean", "extendCookieValidity from queueConfig should be valid boolean.") + local result = userInQueueService.validateQueueRequest(targetUrl, queueitToken, queueConfig, customerId, secretKey) result.isAjaxResult = isQueueAjaxCall() - return result + return result end -local function cancelRequestByLocalConfig(targetUrl, queueitToken, cancelConfig, customerId, secretKey, debugEntries, isDebug) - targetUrl = generateTargetUrl(targetUrl) +local function cancelRequestByLocalConfig( + targetUrl, queueitToken, cancelConfig, customerId, secretKey, debugEntries, isDebug) + + targetUrl = generateTargetUrl(targetUrl) if (isDebug) then local cancelConfigValue = "NULL" if (cancelConfig ~= nil) then cancelConfigValue = cancelConfig:getString() end - + debugEntries["SdkVersion"] = userInQueueService.SDK_VERSION debugEntries["Connector"] = iHelpers.system.getConnectorName() debugEntries["Runtime"] = getRuntime() @@ -121,7 +127,7 @@ end ku.extendQueueCookie = function(eventId, cookieValidityMinute, cookieDomain, secretKey) assert(utils.toString(eventId) ~= "", "eventId can not be nil or empty.") assert(utils.toString(secretKey) ~= "", "secretKey can not be nil or empty.") - + cookieValidityMinute = tonumber(cookieValidityMinute) if (cookieValidityMinute == nil or cookieValidityMinute <= 0) then error("cookieValidityMinute should be a number greater than 0.") @@ -131,14 +137,15 @@ ku.extendQueueCookie = function(eventId, cookieValidityMinute, cookieDomain, sec end ku.cancelRequestByLocalConfig = function(targetUrl, queueitToken, cancelConfig, customerId, secretKey) - debugEntries = { } + local debugEntries = { } local connectorDiagnostics = qitHelpers.ConnectorDiagnostics.verify(customerId, secretKey, queueitToken) if (connectorDiagnostics.hasError) then return connectorDiagnostics.validationResult; end local pcall_status, pcall_result = pcall(function() - return cancelRequestByLocalConfig(targetUrl, queueitToken, cancelConfig, customerId, secretKey, debugEntries, connectorDiagnostics.isEnabled) + return cancelRequestByLocalConfig( + targetUrl, queueitToken, cancelConfig, customerId, secretKey, debugEntries, connectorDiagnostics.isEnabled) end) if (pcall_status == false and connectorDiagnostics.isEnabled) then @@ -154,70 +161,81 @@ ku.cancelRequestByLocalConfig = function(targetUrl, queueitToken, cancelConfig, end end -ku.validateRequestByIntegrationConfig = function(currentUrlWithoutQueueITToken, queueitToken, integrationConfigJson, customerId, secretKey) +ku.validateRequestByIntegrationConfig = function( + currentUrlWithoutQueueITToken, queueitToken, integrationConfigJson, customerId, secretKey) -- Private functions - local function handleQueueAction(currentUrlWithoutQueueITToken, queueitToken, customerIntegration, customerId, secretKey, matchedConfig, debugEntries, isDebug) - local eventConfig = models.QueueEventConfig.create() - local targetUrl = "" - eventConfig.eventId = matchedConfig["EventId"] - eventConfig.queueDomain = matchedConfig["QueueDomain"] - eventConfig.layoutName = matchedConfig["LayoutName"] - eventConfig.culture = matchedConfig["Culture"] - eventConfig.cookieDomain = matchedConfig["CookieDomain"] - eventConfig.extendCookieValidity = matchedConfig["ExtendCookieValidity"] - eventConfig.cookieValidityMinute = matchedConfig["CookieValidityMinute"] - eventConfig.version = customerIntegration["Version"] - eventConfig.actionName = matchedConfig["Name"] - - if (matchedConfig["RedirectLogic"] == "ForcedTargetUrl" or matchedConfig["RedirectLogic"] == "ForecedTargetUrl") then - targetUrl = matchedConfig["ForcedTargetUrl"] + local function handleQueueAction( + _currentUrlWithoutQueueITToken, _queueitToken, _customerIntegration, + _customerId, _secretKey, _matchedConfig, _debugEntries, _isDebug) + + local eventConfig = models.QueueEventConfig.create() + local targetUrl + eventConfig.eventId = _matchedConfig["EventId"] + eventConfig.queueDomain = _matchedConfig["QueueDomain"] + eventConfig.layoutName = _matchedConfig["LayoutName"] + eventConfig.culture = _matchedConfig["Culture"] + eventConfig.cookieDomain = _matchedConfig["CookieDomain"] + eventConfig.extendCookieValidity = _matchedConfig["ExtendCookieValidity"] + eventConfig.cookieValidityMinute = _matchedConfig["CookieValidityMinute"] + eventConfig.version = _customerIntegration["Version"] + eventConfig.actionName = _matchedConfig["Name"] + + if (_matchedConfig["RedirectLogic"] == "ForcedTargetUrl" + or _matchedConfig["RedirectLogic"] == "ForecedTargetUrl") then + targetUrl = _matchedConfig["ForcedTargetUrl"] else - if (matchedConfig["RedirectLogic"] == "EventTargetUrl") then + if (_matchedConfig["RedirectLogic"] == "EventTargetUrl") then targetUrl = "" else - targetUrl = generateTargetUrl(currentUrlWithoutQueueITToken) + targetUrl = generateTargetUrl(_currentUrlWithoutQueueITToken) end end - return resolveQueueRequestByLocalConfig(targetUrl, queueitToken, eventConfig, customerId, secretKey, debugEntries, isDebug) - end - - local function handleCancelAction(currentUrlWithoutQueueITToken, queueitToken, customerIntegration, customerId, secretKey, matchedConfig, debugEntries, isDebug) - local cancelEventConfig = models.CancelEventConfig.create() - cancelEventConfig.eventId = matchedConfig["EventId"] - cancelEventConfig.queueDomain = matchedConfig["QueueDomain"] - cancelEventConfig.cookieDomain = matchedConfig["CookieDomain"] - cancelEventConfig.version = customerIntegration["Version"] - cancelEventConfig.actionName = matchedConfig["Name"] - return cancelRequestByLocalConfig(currentUrlWithoutQueueITToken, queueitToken, cancelEventConfig, customerId, secretKey, debugEntries, isDebug) + return resolveQueueRequestByLocalConfig( + targetUrl, _queueitToken, eventConfig, _customerId, _secretKey, _debugEntries, _isDebug) + end + + local function handleCancelAction( + _currentUrlWithoutQueueITToken, _queueitToken, _customerIntegration, + _customerId, _secretKey, _matchedConfig, _debugEntries, _isDebug) + + local cancelEventConfig = models.CancelEventConfig.create() + cancelEventConfig.eventId = _matchedConfig["EventId"] + cancelEventConfig.queueDomain = _matchedConfig["QueueDomain"] + cancelEventConfig.cookieDomain = _matchedConfig["CookieDomain"] + cancelEventConfig.version = _customerIntegration["Version"] + cancelEventConfig.actionName = _matchedConfig["Name"] + + return cancelRequestByLocalConfig( + _currentUrlWithoutQueueITToken, _queueitToken, cancelEventConfig, _customerId, _secretKey, _debugEntries, _isDebug) end -- END Private functions - - debugEntries = {} + + local debugEntries = {} local connectorDiagnostics = qitHelpers.ConnectorDiagnostics.verify(customerId, secretKey, queueitToken) - + if (connectorDiagnostics.hasError) then return connectorDiagnostics.validationResult; end - - local customerIntegration = nil - + + local customerIntegration = nil + local pcall_status, pcall_result = pcall(function() - + if (connectorDiagnostics.isEnabled) then debugEntries["SdkVersion"] = userInQueueService.SDK_VERSION debugEntries["Connector"] = iHelpers.system.getConnectorName() debugEntries["Runtime"] = getRuntime() - + debugEntries["PureUrl"] = currentUrlWithoutQueueITToken debugEntries["QueueitToken"] = queueitToken debugEntries["OriginalUrl"] = iHelpers.request.getAbsoluteUri() - - logMoreRequestDetails(debugEntries) + + logMoreRequestDetails(debugEntries) end - + customerIntegration = iHelpers.json.parse(integrationConfigJson) - + if (connectorDiagnostics.isEnabled) then if (customerIntegration ~= nil and customerIntegration["Version"] ~= nil) then debugEntries["ConfigVersion"] = customerIntegration["Version"] @@ -230,13 +248,14 @@ ku.validateRequestByIntegrationConfig = function(currentUrlWithoutQueueITToken, error("currentUrlWithoutQueueITToken can not be nil or empty.") end - if (utils.tableLength(customerIntegration) == 0 or customerIntegration == nil or + if (utils.tableLength(customerIntegration) == 0 or customerIntegration == nil or customerIntegration["Version"] == nil) then error("integrationConfigJson was not valid json.") end - - local matchedConfig = integrationEvaluator.getMatchedIntegrationConfig(customerIntegration, currentUrlWithoutQueueITToken, iHelpers.request) - + + local matchedConfig = integrationEvaluator.getMatchedIntegrationConfig( + customerIntegration, currentUrlWithoutQueueITToken, iHelpers.request) + if (connectorDiagnostics.isEnabled) then local matchedConfigValue = "NULL" if (matchedConfig ~= nil and matchedConfig["Name"] ~= nil) then @@ -244,25 +263,25 @@ ku.validateRequestByIntegrationConfig = function(currentUrlWithoutQueueITToken, end debugEntries["MatchedConfig"] = matchedConfigValue end - + if (matchedConfig == nil) then return models.RequestValidationResult.create(nil, nil, nil, nil, nil) end - + if (matchedConfig["ActionType"] == models.ActionTypes.QueueAction) then - return handleQueueAction(currentUrlWithoutQueueITToken, queueitToken, customerIntegration, - customerId, secretKey, matchedConfig, debugEntries, connectorDiagnostics.isEnabled) + return handleQueueAction(currentUrlWithoutQueueITToken, queueitToken, customerIntegration, + customerId, secretKey, matchedConfig, debugEntries, connectorDiagnostics.isEnabled) end - + if (matchedConfig["ActionType"] == models.ActionTypes.CancelAction) then return handleCancelAction(currentUrlWithoutQueueITToken, queueitToken, customerIntegration, customerId, secretKey, matchedConfig, debugEntries, connectorDiagnostics.isEnabled) end - + -- IgnoreAction local result = userInQueueService.getIgnoreActionResult(matchedConfig["Name"]) result.isAjaxResult = isQueueAjaxCall() - return result + return result end) if (pcall_status == false and connectorDiagnostics.isEnabled) then @@ -270,7 +289,7 @@ ku.validateRequestByIntegrationConfig = function(currentUrlWithoutQueueITToken, end setDebugCookie(debugEntries) - + if (pcall_status) then return pcall_result else @@ -278,16 +297,17 @@ ku.validateRequestByIntegrationConfig = function(currentUrlWithoutQueueITToken, end end -ku.resolveQueueRequestByLocalConfig = function(targetUrl, queueitToken, queueConfig, customerId, secretKey) - debugEntries = {} +ku.resolveQueueRequestByLocalConfig = function(targetUrl, queueitToken, queueConfig, customerId, secretKey) + local debugEntries = {} local connectorDiagnostics = qitHelpers.ConnectorDiagnostics.verify(customerId, secretKey, queueitToken) - + if (connectorDiagnostics.hasError) then return connectorDiagnostics.validationResult; end local pcall_status, pcall_result = pcall(function() - local targetUrl = generateTargetUrl(targetUrl) - return resolveQueueRequestByLocalConfig(targetUrl, queueitToken, queueConfig, customerId, secretKey, debugEntries, connectorDiagnostics.isEnabled) + local generatedTargetUrl = generateTargetUrl(targetUrl) + return resolveQueueRequestByLocalConfig( + generatedTargetUrl, queueitToken, queueConfig, customerId, secretKey, debugEntries, connectorDiagnostics.isEnabled) end) if (pcall_status == false and connectorDiagnostics.isEnabled) then @@ -295,7 +315,7 @@ ku.resolveQueueRequestByLocalConfig = function(targetUrl, queueitToken, queueCon end setDebugCookie(debugEntries) - + if (pcall_status) then return pcall_result else diff --git a/SDK/KnownUserImplementationHelpers.lua b/SDK/KnownUserImplementationHelpers.lua index 4ee1882..822e571 100644 --- a/SDK/KnownUserImplementationHelpers.lua +++ b/SDK/KnownUserImplementationHelpers.lua @@ -1,33 +1,35 @@ ---[[ +--[[ The KnownUser lib is implemented using only Lua base functionality; compatible with v.5.1. All those non-standard Lua function calls, needed by KnownUser, are exposed as helper methods below. - So, to make KnownUser functionality work correctly, these methods would need to implemented + So, to make KnownUser functionality work correctly, these methods would need to implemented using whatever libs are available on the executing environment. ]]-- -local iHelpers = +local iHelpers = { - request = + request = { + -- arguments: name -> name of header -- returns: string | nil - getHeader = function(name) - error("request.getHeader - not implemented") + getHeader = function(_) + error("Not implemented : request.getHeader(name)") end, + -- arguments: name -> name of cookie -- returns: the unescaped (url decoded) value ( string | nil ) in the cookie found by name - getUnescapedCookieValue = function(name) - error("request.getUnescapedCookieValue - not implemented") + getUnescapedCookieValue = function(_) + error("Not implemented : request.getUnescapedCookieValue(name)") end, -- returns the url (string) user requested getAbsoluteUri = function() - error("request.getAbsoluteUri - not implemented") + error("Not implemented : request.getAbsoluteUri()") end, -- returns the IP (string) of the user (host) getUserHostAddress = function() - error("request.getUserHostAddress - not implemented") + error("Not implemented : request.getUserHostAddress()") end }, - response = + response = { - cookieOptions = + cookieOptions = { -- true if response cookies should have httponly flag set -- only enable if you use pure server-side integration e.g. not JS Hybrid @@ -39,26 +41,29 @@ local iHelpers = -- only use 'strict' if your queue protected site stays on same domain (no navigation to subdomains) sameSite = nil }, + -- arguments: name, value, expire, domain -- returns: void - setCookie = function(name, value, expire, domain) - error("response.setCookie - not implemented") + setCookie = function(_, _, _, _) + error("Not implemented : response.setCookie(name, value, expire, domain)") end }, - hash = + hash = { + -- arguments: value, key -- returns: string - hmac_sha256_encode = function(value, key) - error("hash.hmac_sha256_encode - not implemented") + hmac_sha256_encode = function(_, _) + error("Not implemented : hash.hmac_sha256_encode(value, key") end }, json = { + -- arguments: jsonStr -- returns: string - parse = function(jsonStr) - error("json.encode - not implemented") + parse = function(_) + error("Not implemented : json.encode(jsonStr)") end }, - system = + system = { getConnectorName = function() return "unspecified" diff --git a/SDK/Models.lua b/SDK/Models.lua index 47c0616..4d3bfbe 100644 --- a/SDK/Models.lua +++ b/SDK/Models.lua @@ -4,50 +4,50 @@ local models = { QueueEventConfig = { create = function() local model = { - eventId, - layoutName, - culture, - queueDomain, - extendCookieValidity, - cookieValidityMinute, - cookieDomain, - version, + eventId = nil, + layoutName = nil, + culture = nil, + queueDomain = nil, + extendCookieValidity = nil, + cookieValidityMinute = nil, + cookieDomain = nil, + version = nil, actionName = "unspecified", getString = function(self) return - "EventId:" .. utils.toString(self.eventId) .. - "&Version:" .. utils.toString(self.version) .. + "EventId:" .. utils.toString(self.eventId) .. + "&Version:" .. utils.toString(self.version) .. "&QueueDomain:" .. utils.toString(self.queueDomain) .. - "&CookieDomain:" .. utils.toString(self.cookieDomain) .. - "&ExtendCookieValidity:" .. utils.toString(self.extendCookieValidity) .. - "&CookieValidityMinute:" .. utils.toString(self.cookieValidityMinute) .. - "&LayoutName:" .. utils.toString(self.layoutName) .. + "&CookieDomain:" .. utils.toString(self.cookieDomain) .. + "&ExtendCookieValidity:" .. utils.toString(self.extendCookieValidity) .. + "&CookieValidityMinute:" .. utils.toString(self.cookieValidityMinute) .. + "&LayoutName:" .. utils.toString(self.layoutName) .. "&Culture:" .. utils.toString(self.culture) .. "&ActionName:" .. utils.toString(self.actionName) end } - - return model + + return model end }, CancelEventConfig = { create = function() local model = { - eventId, - queueDomain, - cookieDomain, - version, + eventId = nil, + queueDomain = nil, + cookieDomain = nil, + version = nil, actionName = "unspecified", getString = function(self) return - "EventId:" .. utils.toString(self.eventId) .. - "&Version:" .. utils.toString(self.version) .. + "EventId:" .. utils.toString(self.eventId) .. + "&Version:" .. utils.toString(self.version) .. "&QueueDomain:" .. utils.toString(self.queueDomain) .. "&CookieDomain:" .. utils.toString(self.cookieDomain) .. "&ActionName:" .. utils.toString(self.actionName) end } - + return model end }, @@ -59,7 +59,7 @@ local models = { queueId = queueId, actionType = actionType, redirectType = redirectType, - isAjaxResult, + isAjaxResult = false, actionName = actionName, doRedirect = function(self) return utils.toString(self.redirectUrl) ~= '' @@ -72,7 +72,7 @@ local models = { end } - return model + return model end }, ActionTypes = { diff --git a/SDK/QueueITHelpers.lua b/SDK/QueueITHelpers.lua index fce8215..6921e70 100644 --- a/SDK/QueueITHelpers.lua +++ b/SDK/QueueITHelpers.lua @@ -4,7 +4,7 @@ local iHelpers = require("KnownUserImplementationHelpers") local queueUrlParams = { extractQueueParams = function(queueitToken) - + if (utils.toString(queueitToken) == "") then return nil end @@ -17,20 +17,20 @@ local queueUrlParams = { local RedirectTypeKey = "rt" local KeyValueSeparatorChar = "_" local KeyValueSeparatorGroupChar = "~" - + -- Private functions local function updateResult(paramNameValueArr, result) if(paramNameValueArr[1] == TimeStampKey) then local tsn = tonumber(paramNameValueArr[2]) - if(tsn ~= nil) then - result.timeStamp = tsn + if(tsn ~= nil) then + result.timeStamp = tsn end return end if(paramNameValueArr[1] == CookieValidityMinutesKey) then local cvn = tonumber(paramNameValueArr[2]) - if(cvn ~= nil) then - result.cookieValidityMinutes = cvn + if(cvn ~= nil) then + result.cookieValidityMinutes = cvn end return end @@ -40,7 +40,7 @@ local queueUrlParams = { end if(paramNameValueArr[1] == ExtendableCookieKey) then if(paramNameValueArr[2] ~= nil) then - result.extendableCookie = string.lower(paramNameValueArr[2]) == "true" + result.extendableCookie = string.lower(paramNameValueArr[2]) == "true" else result.extendableCookie = false end @@ -75,39 +75,43 @@ local queueUrlParams = { local paramsNameValueList = utils.explode(KeyValueSeparatorGroupChar, result.queueITToken) - for i,pNameValue in pairs(paramsNameValueList) do + for _,pNameValue in pairs(paramsNameValueList) do local paramNameValueArr = utils.explode(KeyValueSeparatorChar, pNameValue) - c = utils.tableLength(paramNameValueArr) - if ( c == 2) then + local c = utils.tableLength(paramNameValueArr) + if (c == 2) then updateResult(paramNameValueArr, result) end end - local replacingHash = KeyValueSeparatorGroupChar .. HashCodeKey .. KeyValueSeparatorChar .. utils.escapeMagicChars(result.hashCode) - result.queueITTokenWithoutHash = result.queueITToken:gsub(replacingHash, "") + local replacingHash = + KeyValueSeparatorGroupChar .. HashCodeKey .. + KeyValueSeparatorChar .. utils.escapeMagicChars(result.hashCode) + result.queueITTokenWithoutHash = result.queueITToken:gsub(replacingHash, "") return result end } local connectorDiagnostics = { verify = function(customerId, secretKey, queueitToken) - local function setStateWithTokenError(diagnostics, customerId, errorCode) - diagnostics.hasError = true - diagnostics.validationResult = models.RequestValidationResult.create( - "ConnectorDiagnosticsRedirect", - nil, nil, - "https://" .. customerId .. ".api2.queue-it.net/" .. customerId .. "/diagnostics/connector/error/?code=" .. errorCode, + local function setStateWithTokenError(_diagnostics, _customerId, _errorCode) + _diagnostics.hasError = true + _diagnostics.validationResult = models.RequestValidationResult.create( + "ConnectorDiagnosticsRedirect", + nil, nil, + "https://" .. _customerId .. + ".api2.queue-it.net/" .. _customerId .. + "/diagnostics/connector/error/?code=" .. _errorCode, nil, nil) end - local function setStateWithSetupError(diagnostics) - diagnostics.hasError = true - diagnostics.validationResult = models.RequestValidationResult.create( - "ConnectorDiagnosticsRedirect", - nil, nil, - "https://api2.queue-it.net/diagnostics/connector/error/?code=setup", + local function setStateWithSetupError(_diagnostics) + _diagnostics.hasError = true + _diagnostics.validationResult = models.RequestValidationResult.create( + "ConnectorDiagnosticsRedirect", + nil, nil, + "https://api2.queue-it.net/diagnostics/connector/error/?code=setup", nil, nil) end - + local diagnostics = { isEnabled = false, hasError = false, @@ -135,7 +139,7 @@ local connectorDiagnostics = { local calculatedHash = iHelpers.hash.hmac_sha256_encode(qParams.queueITTokenWithoutHash, secretKey) if (string.upper(calculatedHash) ~= string.upper(qParams.hashCode)) then - setStateWithTokenError(diagnostics, customerId, "hash") + setStateWithTokenError(diagnostics, customerId, "hash") return diagnostics end diff --git a/SDK/Tests/ComparisonOperatorHelperTest.lua b/SDK/Tests/ComparisonOperatorHelperTest.lua index 8803fd2..c54a07c 100644 --- a/SDK/Tests/ComparisonOperatorHelperTest.lua +++ b/SDK/Tests/ComparisonOperatorHelperTest.lua @@ -1,6 +1,6 @@ local comparisonOperatorHelper = require("ComparisonOperatorHelper") -function ComparisonOperatorHelperTest_evaluate() +local function ComparisonOperatorHelperTest_evaluate() assert( comparisonOperatorHelper.evaluate("Equals", false, false, "test1", "test1",nil) ) assert( comparisonOperatorHelper.evaluate("Equals", false, false, "test1", "Test1",nil) == false ) assert( comparisonOperatorHelper.evaluate("Equals", false, true, "test1", "Test1",nil) ) diff --git a/SDK/Tests/IntegrationEvaluatorTest.lua b/SDK/Tests/IntegrationEvaluatorTest.lua index f279dcc..7527da0 100644 --- a/SDK/Tests/IntegrationEvaluatorTest.lua +++ b/SDK/Tests/IntegrationEvaluatorTest.lua @@ -1,10 +1,10 @@ local integrationEvaluator = require("IntegrationEvaluator") local iHelpers = require("KnownUserImplementationHelpers") -function IntegrationEvaluatorTest() - local function test_getMatchedIntegrationConfig_OneTrigger_And_NotMatched() - integrationConfig = - { +local function IntegrationEvaluatorTest() + local function test_getMatchedIntegrationConfig_OneTrigger_And_NotMatched() + local integrationConfig = + { Integrations = { { @@ -36,24 +36,24 @@ function IntegrationEvaluatorTest() } } } - - url = "http://test.tesdomain.com:8080/test?q=2" - assert( integrationEvaluator.getMatchedIntegrationConfig(integrationConfig, url, iHelpers.request) == nil ) + + local url = "http://test.tesdomain.com:8080/test?q=2" + assert( integrationEvaluator.getMatchedIntegrationConfig(integrationConfig, url, iHelpers.request) == nil ) end test_getMatchedIntegrationConfig_OneTrigger_And_NotMatched() - + local function test_getMatchedIntegrationConfig_OneTrigger_And_Matched() - iHelpers.request.getUnescapedCookieValue = function(name) - if (name=="c2") then - return "ddd" + iHelpers.request.getUnescapedCookieValue = function(name) + if (name=="c2") then + return "ddd" end - if (name=="c1") then - return "Value1" + if (name=="c1") then + return "Value1" end end - - integrationConfig = - { + + local integrationConfig = + { Integrations = { { @@ -87,24 +87,27 @@ function IntegrationEvaluatorTest() } } - url = "http://test.tesdomain.com:8080/test?q=2" - assert( integrationEvaluator.getMatchedIntegrationConfig(integrationConfig, url, iHelpers.request)["Name"] == "integration1" ) + local url = "http://test.tesdomain.com:8080/test?q=2" + assert( integrationEvaluator.getMatchedIntegrationConfig( + integrationConfig, url, iHelpers.request)["Name"] == "integration1" ) end test_getMatchedIntegrationConfig_OneTrigger_And_Matched() - + local function test_getMatchedIntegrationConfig_OneTrigger_And_NotMatched_UserAgent() - iHelpers.request.getUnescapedCookieValue = function(name) - if (name=="c2") then - return "ddd" + iHelpers.request.getUnescapedCookieValue = function(name) + if (name=="c2") then + return "ddd" end - if (name=="c1") then - return "Value1" + if (name=="c1") then + return "Value1" end end - iHelpers.request.getHeader = function(name) if (name == "user-agent") then return "bot.html google.com googlebot test" end end - - integrationConfig = - { + iHelpers.request.getHeader = function(name) + if (name == "user-agent") then return "bot.html google.com googlebot test" end + end + + local integrationConfig = + { Integrations = { { @@ -145,24 +148,24 @@ function IntegrationEvaluatorTest() } } - url = "http://test.tesdomain.com:8080/test?q=2" + local url = "http://test.tesdomain.com:8080/test?q=2" assert( integrationEvaluator.getMatchedIntegrationConfig(integrationConfig, url, iHelpers.request) == nil ) end test_getMatchedIntegrationConfig_OneTrigger_And_NotMatched_UserAgent() - + local function test_getMatchedIntegrationConfig_OneTrigger_And_NotMatched_HttpHeader() - iHelpers.request.getUnescapedCookieValue = function(name) - if (name=="c2") then - return "ddd" + iHelpers.request.getUnescapedCookieValue = function(name) + if (name=="c2") then + return "ddd" end - if (name=="c1") then - return "Value1" + if (name=="c1") then + return "Value1" end end iHelpers.request.getHeader = function(name) if (name == "headertest") then return "abcd efg test gklm" end end - integrationConfig = - { + local integrationConfig = + { Integrations = { { @@ -204,16 +207,16 @@ function IntegrationEvaluatorTest() } } - url = "http://test.tesdomain.com:8080/test?q=2" + local url = "http://test.tesdomain.com:8080/test?q=2" assert(integrationEvaluator.getMatchedIntegrationConfig(integrationConfig, url, iHelpers.request) == nil ) end test_getMatchedIntegrationConfig_OneTrigger_And_NotMatched_HttpHeader() local function test_getMatchedIntegrationConfig_OneTrigger_Or_NotMatched() - iHelpers.request.getUnescapedCookieValue = function(name) return nil end - - integrationConfig = - { + iHelpers.request.getUnescapedCookieValue = function(_) return nil end + + local integrationConfig = + { Integrations = { { @@ -247,16 +250,16 @@ function IntegrationEvaluatorTest() } } - url = "http://test.tesdomain.com:8080/test?q=2" + local url = "http://test.tesdomain.com:8080/test?q=2" assert(integrationEvaluator.getMatchedIntegrationConfig(integrationConfig, url, iHelpers.request) == nil ) end test_getMatchedIntegrationConfig_OneTrigger_Or_NotMatched() local function test_getMatchedIntegrationConfig_OneTrigger_Or_Matched() - iHelpers.request.getUnescapedCookieValue = function(name) return nil end + iHelpers.request.getUnescapedCookieValue = function(_) return nil end - integrationConfig = - { + local integrationConfig = + { Integrations = { { @@ -289,17 +292,18 @@ function IntegrationEvaluatorTest() } } } - - url = "http://test.tesdomain.com:8080/test?q=2" - assert( integrationEvaluator.getMatchedIntegrationConfig(integrationConfig, url, iHelpers.request)["Name"] == "integration1" ) + + local url = "http://test.tesdomain.com:8080/test?q=2" + assert( integrationEvaluator.getMatchedIntegrationConfig( + integrationConfig, url, iHelpers.request)["Name"] == "integration1" ) end test_getMatchedIntegrationConfig_OneTrigger_Or_Matched() local function test_getMatchedIntegrationConfig_TwoTriggers_Matched() - iHelpers.request.getUnescapedCookieValue = function(name) return nil end + iHelpers.request.getUnescapedCookieValue = function(_) return nil end - integrationConfig = - { + local integrationConfig = + { Integrations = { { @@ -346,17 +350,18 @@ function IntegrationEvaluatorTest() } } } - - url = "http://test.tesdomain.com:8080/test?q=2" - assert( integrationEvaluator.getMatchedIntegrationConfig(integrationConfig, url, iHelpers.request)["Name"] == "integration1" ) + + local url = "http://test.tesdomain.com:8080/test?q=2" + assert( integrationEvaluator.getMatchedIntegrationConfig( + integrationConfig, url, iHelpers.request)["Name"] == "integration1" ) end test_getMatchedIntegrationConfig_TwoTriggers_Matched() local function test_getMatchedIntegrationConfig_ThreeIntegrationsInOrder_SecondMatched() - iHelpers.request.getUnescapedCookieValue = function(name) return nil end + iHelpers.request.getUnescapedCookieValue = function(_) return nil end - integrationConfig = - { + local integrationConfig = + { Integrations = { { @@ -422,8 +427,9 @@ function IntegrationEvaluatorTest() } } - url = "http://test.tesdomain.com:8080/test?q=2" - assert( integrationEvaluator.getMatchedIntegrationConfig(integrationConfig, url,iHelpers.request)["Name"] == "integration1" ) + local url = "http://test.tesdomain.com:8080/test?q=2" + assert( integrationEvaluator.getMatchedIntegrationConfig( + integrationConfig, url,iHelpers.request)["Name"] == "integration1" ) end test_getMatchedIntegrationConfig_ThreeIntegrationsInOrder_SecondMatched() end diff --git a/SDK/Tests/KnownUserImplementationHelpersTest.lua b/SDK/Tests/KnownUserImplementationHelpersTest.lua index b4ac786..70ea50a 100644 --- a/SDK/Tests/KnownUserImplementationHelpersTest.lua +++ b/SDK/Tests/KnownUserImplementationHelpersTest.lua @@ -1,47 +1,483 @@ -function test_hash_hmac_sha256_encode_correct() +local function test_hash_hmac_sha256_encode_correct() local stringToHash = "event1f8757c2d-34c2-4639-bef2-1736cdd30bbb3idle1530257694" local secretKey = "4e1db821-a825-49da-acd0-5d376f2068db" local expectedResult = "e6913f0e5dd63a266a52542e5df30ec18ee9f259153c55ea30db217e20798e85" - - iHelpers = require("KnownUserImplementationHelpers") + + local iHelpers = require("KnownUserImplementationHelpers") local actualResult = iHelpers.hash.hmac_sha256_encode(stringToHash, secretKey) assert( actualResult == expectedResult ) end test_hash_hmac_sha256_encode_correct() -function test_jsonHelper_correctNullHandling() - integrationConfigJson = +local function test_jsonHelper_correctNullHandling() + local integrationConfigJson = [[ { - "Description":"changed not extend cookie action and trigger to use event disabled", - "Integrations": - [ - {"Name":"event1 ignore action (default)","ActionType":"Ignore","EventId":null,"CookieDomain":null,"LayoutName":null,"Culture":null,"ExtendCookieValidity":null,"CookieValidityMinute":0,"Triggers":[{"TriggerParts":[{"Operator":"Contains","ValueToCompare":"ignore-queue-event1-nodomain","ValuesToCompare":null,"UrlPart":"PageUrl","VariableName":null,"CookieName":null,"HttpHeaderName":null,"ValidatorType":"UrlValidator","IsNegative":false,"IsIgnoreCase":true},{"Operator":"ContainsAny","ValueToCompare":"","ValuesToCompare":["ignore-that-queue-event1-nodomain","ignore-this-queue-event1-nodomain"],"UrlPart":"PageUrl","VariableName":null,"CookieName":null,"HttpHeaderName":null,"ValidatorType":"UrlValidator","IsNegative":false,"IsIgnoreCase":true}],"LogicalOperator":"Or"}],"QueueDomain":null,"RedirectLogic":null,"ForcedTargetUrl":null}, - {"Name":"event1 queue action (default)","ActionType":"Queue","EventId":"event1","CookieDomain":"","LayoutName":null,"Culture":"","ExtendCookieValidity":true,"CookieValidityMinute":20,"Triggers":[{"TriggerParts":[{"Operator":"Contains","ValueToCompare":"queue-event1-nodomain","ValuesToCompare":null,"UrlPart":"PageUrl","VariableName":null,"CookieName":null,"HttpHeaderName":null,"ValidatorType":"UrlValidator","IsNegative":false,"IsIgnoreCase":true},{"Operator":"Contains","ValueToCompare":"bot","ValuesToCompare":null,"UrlPart":null,"VariableName":null,"CookieName":"Akamai-bot","HttpHeaderName":null,"ValidatorType":"CookieValidator","IsNegative":true,"IsIgnoreCase":true},{"Operator":"Contains","ValueToCompare":"bot","ValuesToCompare":null,"UrlPart":null,"VariableName":null,"CookieName":null,"HttpHeaderName":null,"ValidatorType":"UserAgentValidator","IsNegative":true,"IsIgnoreCase":true},{"Operator":"Contains","ValueToCompare":"bot","ValuesToCompare":null,"UrlPart":null,"VariableName":null,"CookieName":null,"HttpHeaderName":"Akamai-bot","ValidatorType":"HttpHeaderValidator","IsNegative":true,"IsIgnoreCase":true}],"LogicalOperator":"And"}],"QueueDomain":"queueitknownusertst.test.queue-it.net","RedirectLogic":"AllowTParameter","ForcedTargetUrl":""}, - {"Name":"event1 cancel action (default)","ActionType":"Cancel","EventId":"event1","CookieDomain":"","LayoutName":null,"Culture":null,"ExtendCookieValidity":null,"CookieValidityMinute":0,"Triggers":[{"TriggerParts":[{"Operator":"Contains","ValueToCompare":"cancel-event1-nodomain","ValuesToCompare":null,"UrlPart":"PageUrl","VariableName":null,"CookieName":null,"HttpHeaderName":null,"ValidatorType":"UrlValidator","IsNegative":false,"IsIgnoreCase":true}],"LogicalOperator":"And"}],"QueueDomain":"queueitknownusertst.test.queue-it.net","RedirectLogic":null,"ForcedTargetUrl":null}, - {"Name":"event1 ignore action (ticketania)","ActionType":"Ignore","EventId":null,"CookieDomain":null,"LayoutName":null,"Culture":null,"ExtendCookieValidity":null,"CookieValidityMinute":0,"Triggers":[{"TriggerParts":[{"Operator":"Contains","ValueToCompare":"ignore-queue-event1","ValuesToCompare":null,"UrlPart":"PageUrl","VariableName":null,"CookieName":null,"HttpHeaderName":null,"ValidatorType":"UrlValidator","IsNegative":false,"IsIgnoreCase":true},{"Operator":"ContainsAny","ValueToCompare":"","ValuesToCompare":["ignore-this-queue-event1","ignore-that-queue-event1"],"UrlPart":"PageUrl","VariableName":null,"CookieName":null,"HttpHeaderName":null,"ValidatorType":"UrlValidator","IsNegative":false,"IsIgnoreCase":true}],"LogicalOperator":"Or"}],"QueueDomain":null,"RedirectLogic":null,"ForcedTargetUrl":null}, - {"Name":"event1 queue action (ticketania)","ActionType":"Queue","EventId":"event1","CookieDomain":".ticketania.com","LayoutName":"Christmas Layout by Queue-it","Culture":"","ExtendCookieValidity":true,"CookieValidityMinute":20,"Triggers":[{"TriggerParts":[{"Operator":"Contains","ValueToCompare":"queue-event1","ValuesToCompare":null,"UrlPart":"PageUrl","VariableName":null,"CookieName":null,"HttpHeaderName":null,"ValidatorType":"UrlValidator","IsNegative":false,"IsIgnoreCase":true},{"Operator":"Contains","ValueToCompare":"bot","ValuesToCompare":null,"UrlPart":null,"VariableName":null,"CookieName":"Akamai-bot","HttpHeaderName":null,"ValidatorType":"CookieValidator","IsNegative":true,"IsIgnoreCase":true},{"Operator":"Contains","ValueToCompare":"bot","ValuesToCompare":null,"UrlPart":null,"VariableName":null,"CookieName":null,"HttpHeaderName":null,"ValidatorType":"UserAgentValidator","IsNegative":true,"IsIgnoreCase":true},{"Operator":"Contains","ValueToCompare":"bot","ValuesToCompare":null,"UrlPart":null,"VariableName":null,"CookieName":null,"HttpHeaderName":"Akamai-bot","ValidatorType":"HttpHeaderValidator","IsNegative":true,"IsIgnoreCase":true}],"LogicalOperator":"And"}],"QueueDomain":"queueitknownusertst.test.queue-it.net","RedirectLogic":"AllowTParameter","ForcedTargetUrl":""}, - {"Name":"event1 cancel action (ticketania)","ActionType":"Cancel","EventId":"event1","CookieDomain":".ticketania.com","LayoutName":null,"Culture":null,"ExtendCookieValidity":null,"CookieValidityMinute":0,"Triggers":[{"TriggerParts":[{"Operator":"Contains","ValueToCompare":"cancel-event1","ValuesToCompare":null,"UrlPart":"PageUrl","VariableName":null,"CookieName":null,"HttpHeaderName":null,"ValidatorType":"UrlValidator","IsNegative":false,"IsIgnoreCase":true}],"LogicalOperator":"And"}],"QueueDomain":"queueitknownusertst.test.queue-it.net","RedirectLogic":null,"ForcedTargetUrl":null}, - {"Name":"future queue action (default)","ActionType":"Queue","EventId":"future","CookieDomain":"","LayoutName":null,"Culture":"","ExtendCookieValidity":true,"CookieValidityMinute":20,"Triggers":[{"TriggerParts":[{"Operator":"Contains","ValueToCompare":"idle-future-nodomain","ValuesToCompare":null,"UrlPart":"PageUrl","VariableName":null,"CookieName":null,"HttpHeaderName":null,"ValidatorType":"UrlValidator","IsNegative":false,"IsIgnoreCase":true}],"LogicalOperator":"And"}],"QueueDomain":"queueitknownusertst.test.queue-it.net","RedirectLogic":"AllowTParameter","ForcedTargetUrl":""}, - {"Name":"future queue action (ticketania)","ActionType":"Queue","EventId":"future","CookieDomain":".ticketania.com","LayoutName":null,"Culture":"","ExtendCookieValidity":true,"CookieValidityMinute":20,"Triggers":[{"TriggerParts":[{"Operator":"Contains","ValueToCompare":"idle-future","ValuesToCompare":null,"UrlPart":"PageUrl","VariableName":null,"CookieName":null,"HttpHeaderName":null,"ValidatorType":"UrlValidator","IsNegative":false,"IsIgnoreCase":true}],"LogicalOperator":"And"}],"QueueDomain":"queueitknownusertst.test.queue-it.net","RedirectLogic":"AllowTParameter","ForcedTargetUrl":""}, - {"Name":"disabled queue action (default)","ActionType":"Queue","EventId":"disabled","CookieDomain":"","LayoutName":null,"Culture":"","ExtendCookieValidity":true,"CookieValidityMinute":20,"Triggers":[{"TriggerParts":[{"Operator":"Contains","ValueToCompare":"queue-disabled-nodomain","ValuesToCompare":null,"UrlPart":"PageUrl","VariableName":null,"CookieName":null,"HttpHeaderName":null,"ValidatorType":"UrlValidator","IsNegative":false,"IsIgnoreCase":true}],"LogicalOperator":"And"}],"QueueDomain":"queueitknownusertst.test.queue-it.net","RedirectLogic":"AllowTParameter","ForcedTargetUrl":""}, - {"Name":"disabled [not extend cookie] queue action (default)","ActionType":"Queue","EventId":"disabled","CookieDomain":"","LayoutName":null,"Culture":"","ExtendCookieValidity":false,"CookieValidityMinute":20,"Triggers":[{"TriggerParts":[{"Operator":"Contains","ValueToCompare":"queue-disabled-notextendcookie-nodomain","ValuesToCompare":null,"UrlPart":"PageUrl","VariableName":null,"CookieName":null,"HttpHeaderName":null,"ValidatorType":"UrlValidator","IsNegative":false,"IsIgnoreCase":true}],"LogicalOperator":"And"}],"QueueDomain":"queueitknownusertst.test.queue-it.net","RedirectLogic":"AllowTParameter","ForcedTargetUrl":""}, - {"Name":"disabled queue action (ticketania)","ActionType":"Queue","EventId":"disabled","CookieDomain":".ticketania.com","LayoutName":null,"Culture":"","ExtendCookieValidity":true,"CookieValidityMinute":20,"Triggers":[{"TriggerParts":[{"Operator":"Contains","ValueToCompare":"queue-disabled","ValuesToCompare":null,"UrlPart":"PageUrl","VariableName":null,"CookieName":null,"HttpHeaderName":null,"ValidatorType":"UrlValidator","IsNegative":false,"IsIgnoreCase":true}],"LogicalOperator":"And"}],"QueueDomain":"queueitknownusertst.test.queue-it.net","RedirectLogic":"AllowTParameter","ForcedTargetUrl":""} + "Description": "changed not extend cookie action and trigger to use event disabled", + "Integrations": [ + { + "Name": "event1 ignore action (default)", + "ActionType": "Ignore", + "EventId": null, + "CookieDomain": null, + "LayoutName": null, + "Culture": null, + "ExtendCookieValidity": null, + "CookieValidityMinute": 0, + "Triggers": [ + { + "TriggerParts": [ + { + "Operator": "Contains", + "ValueToCompare": "ignore-queue-event1-nodomain", + "ValuesToCompare": null, + "UrlPart": "PageUrl", + "VariableName": null, + "CookieName": null, + "HttpHeaderName": null, + "ValidatorType": "UrlValidator", + "IsNegative": false, + "IsIgnoreCase": true + }, + { + "Operator": "ContainsAny", + "ValueToCompare": "", + "ValuesToCompare": [ "ignore-that-queue-event1-nodomain", "ignore-this-queue-event1-nodomain" ], + "UrlPart": "PageUrl", + "VariableName": null, + "CookieName": null, + "HttpHeaderName": null, + "ValidatorType": "UrlValidator", + "IsNegative": false, + "IsIgnoreCase": true + } + ], + "LogicalOperator": "Or" + } + ], + "QueueDomain": null, + "RedirectLogic": null, + "ForcedTargetUrl": null + }, + { + "Name": "event1 queue action (default)", + "ActionType": "Queue", + "EventId": "event1", + "CookieDomain": "", + "LayoutName": null, + "Culture": "", + "ExtendCookieValidity": true, + "CookieValidityMinute": 20, + "Triggers": [ + { + "TriggerParts": [ + { + "Operator": "Contains", + "ValueToCompare": "queue-event1-nodomain", + "ValuesToCompare": null, + "UrlPart": "PageUrl", + "VariableName": null, + "CookieName": null, + "HttpHeaderName": null, + "ValidatorType": "UrlValidator", + "IsNegative": false, + "IsIgnoreCase": true + }, + { + "Operator": "Contains", + "ValueToCompare": "bot", + "ValuesToCompare": null, + "UrlPart": null, + "VariableName": null, + "CookieName": "Akamai-bot", + "HttpHeaderName": null, + "ValidatorType": "CookieValidator", + "IsNegative": true, + "IsIgnoreCase": true + }, + { + "Operator": "Contains", + "ValueToCompare": "bot", + "ValuesToCompare": null, + "UrlPart": null, + "VariableName": null, + "CookieName": null, + "HttpHeaderName": null, + "ValidatorType": "UserAgentValidator", + "IsNegative": true, + "IsIgnoreCase": true + }, + { + "Operator": "Contains", + "ValueToCompare": "bot", + "ValuesToCompare": null, + "UrlPart": null, + "VariableName": null, + "CookieName": null, + "HttpHeaderName": "Akamai-bot", + "ValidatorType": "HttpHeaderValidator", + "IsNegative": true, + "IsIgnoreCase": true + } + ], + "LogicalOperator": "And" + } + ], + "QueueDomain": "queueitknownusertst.test.queue-it.net", + "RedirectLogic": "AllowTParameter", + "ForcedTargetUrl": "" + }, + { + "Name": "event1 cancel action (default)", + "ActionType": "Cancel", + "EventId": "event1", + "CookieDomain": "", + "LayoutName": null, + "Culture": null, + "ExtendCookieValidity": null, + "CookieValidityMinute": 0, + "Triggers": [ + { + "TriggerParts": [ + { + "Operator": "Contains", + "ValueToCompare": "cancel-event1-nodomain", + "ValuesToCompare": null, + "UrlPart": "PageUrl", + "VariableName": null, + "CookieName": null, + "HttpHeaderName": null, + "ValidatorType": "UrlValidator", + "IsNegative": false, + "IsIgnoreCase": true + } + ], + "LogicalOperator": "And" + } + ], + "QueueDomain": "queueitknownusertst.test.queue-it.net", + "RedirectLogic": null, + "ForcedTargetUrl": null + }, + { + "Name": "event1 ignore action (ticketania)", + "ActionType": "Ignore", + "EventId": null, + "CookieDomain": null, + "LayoutName": null, + "Culture": null, + "ExtendCookieValidity": null, + "CookieValidityMinute": 0, + "Triggers": [ + { + "TriggerParts": [ + { + "Operator": "Contains", + "ValueToCompare": "ignore-queue-event1", + "ValuesToCompare": null, + "UrlPart": "PageUrl", + "VariableName": null, + "CookieName": null, + "HttpHeaderName": null, + "ValidatorType": "UrlValidator", + "IsNegative": false, + "IsIgnoreCase": true + }, + { + "Operator": "ContainsAny", + "ValueToCompare": "", + "ValuesToCompare": [ "ignore-this-queue-event1", "ignore-that-queue-event1" ], + "UrlPart": "PageUrl", + "VariableName": null, + "CookieName": null, + "HttpHeaderName": null, + "ValidatorType": "UrlValidator", + "IsNegative": false, + "IsIgnoreCase": true + } + ], + "LogicalOperator": "Or" + } + ], + "QueueDomain": null, + "RedirectLogic": null, + "ForcedTargetUrl": null + }, + { + "Name": "event1 queue action (ticketania)", + "ActionType": "Queue", + "EventId": "event1", + "CookieDomain": ".ticketania.com", + "LayoutName": "Christmas Layout by Queue-it", + "Culture": "", + "ExtendCookieValidity": true, + "CookieValidityMinute": 20, + "Triggers": [ + { + "TriggerParts": [ + { + "Operator": "Contains", + "ValueToCompare": "queue-event1", + "ValuesToCompare": null, + "UrlPart": "PageUrl", + "VariableName": null, + "CookieName": null, + "HttpHeaderName": null, + "ValidatorType": "UrlValidator", + "IsNegative": false, + "IsIgnoreCase": true + }, + { + "Operator": "Contains", + "ValueToCompare": "bot", + "ValuesToCompare": null, + "UrlPart": null, + "VariableName": null, + "CookieName": "Akamai-bot", + "HttpHeaderName": null, + "ValidatorType": "CookieValidator", + "IsNegative": true, + "IsIgnoreCase": true + }, + { + "Operator": "Contains", + "ValueToCompare": "bot", + "ValuesToCompare": null, + "UrlPart": null, + "VariableName": null, + "CookieName": null, + "HttpHeaderName": null, + "ValidatorType": "UserAgentValidator", + "IsNegative": true, + "IsIgnoreCase": true + }, + { + "Operator": "Contains", + "ValueToCompare": "bot", + "ValuesToCompare": null, + "UrlPart": null, + "VariableName": null, + "CookieName": null, + "HttpHeaderName": "Akamai-bot", + "ValidatorType": "HttpHeaderValidator", + "IsNegative": true, + "IsIgnoreCase": true + } + ], + "LogicalOperator": "And" + } + ], + "QueueDomain": "queueitknownusertst.test.queue-it.net", + "RedirectLogic": "AllowTParameter", + "ForcedTargetUrl": "" + }, + { + "Name": "event1 cancel action (ticketania)", + "ActionType": "Cancel", + "EventId": "event1", + "CookieDomain": ".ticketania.com", + "LayoutName": null, + "Culture": null, + "ExtendCookieValidity": null, + "CookieValidityMinute": 0, + "Triggers": [ + { + "TriggerParts": [ + { + "Operator": "Contains", + "ValueToCompare": "cancel-event1", + "ValuesToCompare": null, + "UrlPart": "PageUrl", + "VariableName": null, + "CookieName": null, + "HttpHeaderName": null, + "ValidatorType": "UrlValidator", + "IsNegative": false, + "IsIgnoreCase": true + } + ], + "LogicalOperator": "And" + } + ], + "QueueDomain": "queueitknownusertst.test.queue-it.net", + "RedirectLogic": null, + "ForcedTargetUrl": null + }, + { + "Name": "future queue action (default)", + "ActionType": "Queue", + "EventId": "future", + "CookieDomain": "", + "LayoutName": null, + "Culture": "", + "ExtendCookieValidity": true, + "CookieValidityMinute": 20, + "Triggers": [ + { + "TriggerParts": [ + { + "Operator": "Contains", + "ValueToCompare": "idle-future-nodomain", + "ValuesToCompare": null, + "UrlPart": "PageUrl", + "VariableName": null, + "CookieName": null, + "HttpHeaderName": null, + "ValidatorType": "UrlValidator", + "IsNegative": false, + "IsIgnoreCase": true + } + ], + "LogicalOperator": "And" + } + ], + "QueueDomain": "queueitknownusertst.test.queue-it.net", + "RedirectLogic": "AllowTParameter", + "ForcedTargetUrl": "" + }, + { + "Name": "future queue action (ticketania)", + "ActionType": "Queue", + "EventId": "future", + "CookieDomain": ".ticketania.com", + "LayoutName": null, + "Culture": "", + "ExtendCookieValidity": true, + "CookieValidityMinute": 20, + "Triggers": [ + { + "TriggerParts": [ + { + "Operator": "Contains", + "ValueToCompare": "idle-future", + "ValuesToCompare": null, + "UrlPart": "PageUrl", + "VariableName": null, + "CookieName": null, + "HttpHeaderName": null, + "ValidatorType": "UrlValidator", + "IsNegative": false, + "IsIgnoreCase": true + } + ], + "LogicalOperator": "And" + } + ], + "QueueDomain": "queueitknownusertst.test.queue-it.net", + "RedirectLogic": "AllowTParameter", + "ForcedTargetUrl": "" + }, + { + "Name": "disabled queue action (default)", + "ActionType": "Queue", + "EventId": "disabled", + "CookieDomain": "", + "LayoutName": null, + "Culture": "", + "ExtendCookieValidity": true, + "CookieValidityMinute": 20, + "Triggers": [ + { + "TriggerParts": [ + { + "Operator": "Contains", + "ValueToCompare": "queue-disabled-nodomain", + "ValuesToCompare": null, + "UrlPart": "PageUrl", + "VariableName": null, + "CookieName": null, + "HttpHeaderName": null, + "ValidatorType": "UrlValidator", + "IsNegative": false, + "IsIgnoreCase": true + } + ], + "LogicalOperator": "And" + } + ], + "QueueDomain": "queueitknownusertst.test.queue-it.net", + "RedirectLogic": "AllowTParameter", + "ForcedTargetUrl": "" + }, + { + "Name": "disabled [not extend cookie] queue action (default)", + "ActionType": "Queue", + "EventId": "disabled", + "CookieDomain": "", + "LayoutName": null, + "Culture": "", + "ExtendCookieValidity": false, + "CookieValidityMinute": 20, + "Triggers": [ + { + "TriggerParts": [ + { + "Operator": "Contains", + "ValueToCompare": "queue-disabled-notextendcookie-nodomain", + "ValuesToCompare": null, + "UrlPart": "PageUrl", + "VariableName": null, + "CookieName": null, + "HttpHeaderName": null, + "ValidatorType": "UrlValidator", + "IsNegative": false, + "IsIgnoreCase": true + } + ], + "LogicalOperator": "And" + } + ], + "QueueDomain": "queueitknownusertst.test.queue-it.net", + "RedirectLogic": "AllowTParameter", + "ForcedTargetUrl": "" + }, + { + "Name": "disabled queue action (ticketania)", + "ActionType": "Queue", + "EventId": "disabled", + "CookieDomain": ".ticketania.com", + "LayoutName": null, + "Culture": "", + "ExtendCookieValidity": true, + "CookieValidityMinute": 20, + "Triggers": [ + { + "TriggerParts": [ + { + "Operator": "Contains", + "ValueToCompare": "queue-disabled", + "ValuesToCompare": null, + "UrlPart": "PageUrl", + "VariableName": null, + "CookieName": null, + "HttpHeaderName": null, + "ValidatorType": "UrlValidator", + "IsNegative": false, + "IsIgnoreCase": true + } + ], + "LogicalOperator": "And" + } + ], + "QueueDomain": "queueitknownusertst.test.queue-it.net", + "RedirectLogic": "AllowTParameter", + "ForcedTargetUrl": "" + } ], - "CustomerId":"queueitknownusertst", - "AccountId":"queueitknownusertst", - "Version":11, - "PublishDate":"2018-01-25T10:08:33.2825373Z", - "ConfigDataVersion":"1.0.0.3" - } + "CustomerId": "queueitknownusertst", + "AccountId": "queueitknownusertst", + "Version": 11, + "PublishDate": "2018-01-25T10:08:33.2825373Z", + "ConfigDataVersion": "1.0.0.3" + } ]] local json = require("json") local cfg = json.parse(integrationConfigJson) - for i, v in pairs(cfg.Integrations) do - assert( "should be a valid string -> " .. v.LayoutName ) -- this should not raise exception + for _, v in pairs(cfg.Integrations) do + assert( "should be a valid string -> " .. v.LayoutName ) -- this should not raise exception end end test_jsonHelper_correctNullHandling() \ No newline at end of file diff --git a/SDK/Tests/KnownUserTest.lua b/SDK/Tests/KnownUserTest.lua index f38ef63..d6226bd 100644 --- a/SDK/Tests/KnownUserTest.lua +++ b/SDK/Tests/KnownUserTest.lua @@ -3,21 +3,21 @@ local utils = require("Utils") local knownUser = require("KnownUser") -- Mocks -iHelpers = require("KnownUserImplementationHelpers") +local iHelpers = require("KnownUserImplementationHelpers") iHelpers.reset = function() iHelpers.system.getConnectorName = function() return "mock-connector" - end - iHelpers.request.getHeader = function(name) - return nil end - iHelpers.request.getAbsoluteUri = function() - return nil + iHelpers.request.getHeader = function(_) + return nil end - iHelpers.request.getUserHostAddress = function() - return nil + iHelpers.request.getAbsoluteUri = function() + return nil end - iHelpers.response.setCookie = function(name, value, expire, domain) + iHelpers.request.getUserHostAddress = function() + return nil + end + iHelpers.response.setCookie = function(name, value, _, _) if(name=="queueitdebug") then iHelpers.response.debugCookieSet = value end @@ -25,11 +25,14 @@ iHelpers.reset = function() iHelpers.response.debugCookieSet = nil end -userInQueueServiceMock = require("UserInQueueService") +local userInQueueServiceMock = require("UserInQueueService") userInQueueServiceMock.validateQueueRequestResult = { } userInQueueServiceMock.validateQueueRequestRaiseException = false userInQueueServiceMock.validateQueueRequest = function(targetUrl, queueitToken, queueConfig, customerId, secretKey) - userInQueueServiceMock.methodInvokations = { method="validateQueueRequest", targetUrl=targetUrl, queueitToken=queueitToken, queueConfig=queueConfig, customerId=customerId, secretKey=secretKey } + userInQueueServiceMock.methodInvokations = { + method="validateQueueRequest", targetUrl=targetUrl, queueitToken=queueitToken, + queueConfig=queueConfig, customerId=customerId, secretKey=secretKey + } if(userInQueueServiceMock.validateQueueRequestRaiseException) then assert(false,"exception") else @@ -39,7 +42,10 @@ end userInQueueServiceMock.validateCancelRequestResult = { } userInQueueServiceMock.validateCancelRequestRaiseException = false userInQueueServiceMock.validateCancelRequest = function(targetUrl, cancelConfig, customerId, secretKey) - userInQueueServiceMock.methodInvokations = { method="validateCancelRequest", targetUrl=targetUrl, cancelConfig=cancelConfig, customerId=customerId, secretKey=secretKey } + userInQueueServiceMock.methodInvokations = { + method="validateCancelRequest", targetUrl=targetUrl, + cancelConfig=cancelConfig, customerId=customerId, secretKey=secretKey + } if(userInQueueServiceMock.validateCancelRequestRaiseException) then assert(false,"exception") else @@ -48,7 +54,10 @@ userInQueueServiceMock.validateCancelRequest = function(targetUrl, cancelConfig, end userInQueueServiceMock.extendQueueCookieResult = { } userInQueueServiceMock.extendQueueCookie = function(eventId, cookieValidityMinute, cookieDomain, secretKey) - userInQueueServiceMock.methodInvokations = { method="extendQueueCookie", eventId=eventId, cookieValidityMinute=cookieValidityMinute, cookieDomain=cookieDomain, secretKey=secretKey } + userInQueueServiceMock.methodInvokations = { + method="extendQueueCookie", eventId=eventId, cookieValidityMinute=cookieValidityMinute, + cookieDomain=cookieDomain, secretKey=secretKey + } return userInQueueServiceMock.validateQueueRequestResult end userInQueueServiceMock.getIgnoreActionResult = function (actionName) @@ -65,38 +74,40 @@ userInQueueServiceMock.reset = function() userInQueueServiceMock.validateQueueRequestRaiseException = false end -function resetAllMocks() +local function resetAllMocks() iHelpers.reset() userInQueueServiceMock.reset() end -- END Mocks -function generateHashDebugValidHash(secretKey, expiredToken) +local function generateHashDebugValidHash(secretKey, expiredToken) local ts = os.time() + 1000 if (expiredToken) then ts = os.time() - 1000 end local t = 'e_eventId' .. '~rt_debug' .. '~ts_' .. ts local h = iHelpers.hash.hmac_sha256_encode(t, secretKey) - + return t .. '~h_' .. h end -function KnownUserTest() - +local function KnownUserTest() + local function test_cancelRequestByLocalConfig() resetAllMocks() - - userInQueueServiceMock.validateCancelRequestResult = models.RequestValidationResult.create("Cancel", "eventid", "queueid", "http://q.queue-it.net", nil, "CancelAction") - cancelEventconfig = models.CancelEventConfig.create() + userInQueueServiceMock.validateCancelRequestResult = models.RequestValidationResult.create( + "Cancel", "eventid", "queueid", "http://q.queue-it.net", nil, "CancelAction") + + local cancelEventconfig = models.CancelEventConfig.create() cancelEventconfig.cookieDomain = "cookiedomain" cancelEventconfig.eventId = "eventid" cancelEventconfig.queueDomain = "queuedomain" cancelEventconfig.version = 1 cancelEventconfig.actionName = "CancelAction" - result = knownUser.cancelRequestByLocalConfig("url", "queueittoken", cancelEventconfig, "customerid", "secretkey") + local result = knownUser.cancelRequestByLocalConfig( + "url", "queueittoken", cancelEventconfig, "customerid", "secretkey") assert( userInQueueServiceMock.methodInvokations.method == "validateCancelRequest" ) assert( userInQueueServiceMock.methodInvokations.targetUrl == "url" ) @@ -106,15 +117,16 @@ function KnownUserTest() assert( userInQueueServiceMock.methodInvokations.cancelConfig["queueDomain"] == "queuedomain" ) assert( userInQueueServiceMock.methodInvokations.cancelConfig["cookieDomain"] == "cookiedomain" ) assert( userInQueueServiceMock.methodInvokations.cancelConfig["version"] == 1 ) - assert( userInQueueServiceMock.methodInvokations.cancelConfig["actionName"] == cancelEventconfig.actionName ) + assert( userInQueueServiceMock.methodInvokations.cancelConfig["actionName"] == cancelEventconfig.actionName ) assert( result.isAjaxResult == false ) end test_cancelRequestByLocalConfig() local function test_cancelRequestByLocalConfig_AjaxCall() resetAllMocks() - - userInQueueServiceMock.validateCancelRequestResult = models.RequestValidationResult.create("Cancel", "eventid", "queueid", "http://q.queue-it.net", nil, "CancelAction") + + userInQueueServiceMock.validateCancelRequestResult = models.RequestValidationResult.create( + "Cancel", "eventid", "queueid", "http://q.queue-it.net", nil, "CancelAction") iHelpers.request.getHeader = function(name) if (name == "x-queueit-ajaxpageurl") then @@ -124,14 +136,15 @@ function KnownUserTest() end end - cancelEventconfig = models.CancelEventConfig.create() + local cancelEventconfig = models.CancelEventConfig.create() cancelEventconfig.cookieDomain = "cookiedomain" cancelEventconfig.eventId = "eventid" cancelEventconfig.queueDomain = "queuedomain" cancelEventconfig.version = 1 cancelEventconfig.actionName = "CancelAction" - result = knownUser.cancelRequestByLocalConfig("url", "queueittoken", cancelEventconfig, "customerid", "secretkey") + local result = knownUser.cancelRequestByLocalConfig( + "url", "queueittoken", cancelEventconfig, "customerid", "secretkey") assert( userInQueueServiceMock.methodInvokations.method == "validateCancelRequest" ) assert( userInQueueServiceMock.methodInvokations.targetUrl == "http://url" ) @@ -143,118 +156,125 @@ function KnownUserTest() assert( userInQueueServiceMock.methodInvokations.cancelConfig["version"] == 1 ) assert( userInQueueServiceMock.methodInvokations.cancelConfig["actionName"] == cancelEventconfig.actionName ) assert( result.isAjaxResult == true ) - assert( result:getAjaxRedirectUrl() == "http%3A%2F%2Fq.queue-it.net" ) + assert( result:getAjaxRedirectUrl() == "http%3A%2F%2Fq.queue-it.net" ) end test_cancelRequestByLocalConfig_AjaxCall() local function test_cancelRequestByLocalConfig_empty_eventId() - resetAllMocks() - - cancelconfig = models.CancelEventConfig.create() + resetAllMocks() + + local cancelconfig = models.CancelEventConfig.create() cancelconfig.cookieDomain = "cookieDomain" cancelconfig.queueDomain = "queueDomain" cancelconfig.version = 12 - - status = xpcall( + + local errorMsg + local status = xpcall( function() - knownUser.cancelRequestByLocalConfig("targeturl", "queueittoken", cancelconfig, "customerid", "secretkey") + knownUser.cancelRequestByLocalConfig( + "targeturl", "queueittoken", cancelconfig, "customerid", "secretkey") end, - function(err) - errorMsg = err + function(err) + errorMsg = err end ) - + assert( status == false ) assert( utils.endsWith(errorMsg, "eventId from cancelConfig can not be nil or empty.") ) end test_cancelRequestByLocalConfig_empty_eventId() local function test_cancelRequestByLocalConfig_empty_secreteKey() - resetAllMocks() - - cancelconfig = models.CancelEventConfig.create() + resetAllMocks() + + local cancelconfig = models.CancelEventConfig.create() cancelconfig.cookieDomain = "cookieDomain" cancelconfig.eventId = "eventId" cancelconfig.queueDomain = "queueDomain" cancelconfig.version = 12 - status = xpcall( + local errorMsg + local status = xpcall( function() knownUser.cancelRequestByLocalConfig("targeturl", "queueittoken", cancelconfig, "customerid", nil) end, - function(err) - errorMsg = err + function(err) + errorMsg = err end ) - + assert( status == false ) - assert( utils.endsWith(errorMsg, "secretKey can not be nil or empty.") ) + assert( utils.endsWith(errorMsg, "secretKey can not be nil or empty.") ) end test_cancelRequestByLocalConfig_empty_secreteKey() local function test_cancelRequestByLocalConfig_empty_queueDomain() - resetAllMocks() - - cancelconfig = models.CancelEventConfig.create() + resetAllMocks() + + local cancelconfig = models.CancelEventConfig.create() cancelconfig.cookieDomain = "cookieDomain" cancelconfig.eventId = "eventId" cancelconfig.version = 12 - - status = xpcall( + + local errorMsg + local status = xpcall( function() - knownUser.cancelRequestByLocalConfig("targeturl", "queueittoken", cancelconfig, "customerid", "secretkey") + knownUser.cancelRequestByLocalConfig( + "targeturl", "queueittoken", cancelconfig, "customerid", "secretkey") end, - function(err) - errorMsg = err + function(err) + errorMsg = err end ) - + assert( status == false ) - assert( utils.endsWith(errorMsg, "queueDomain from cancelConfig can not be nil or empty.") ) + assert( utils.endsWith(errorMsg, "queueDomain from cancelConfig can not be nil or empty.") ) end test_cancelRequestByLocalConfig_empty_queueDomain() local function test_cancelRequestByLocalConfig_empty_customerId() resetAllMocks() - - cancelconfig = models.CancelEventConfig.create() + + local cancelconfig = models.CancelEventConfig.create() cancelconfig.cookieDomain = "cookieDomain" cancelconfig.eventId = "eventId" cancelconfig.queueDomain = "queueDomain" cancelconfig.version = 12 - status = xpcall( + local errorMsg + local status = xpcall( function() knownUser.cancelRequestByLocalConfig("targeturl", "queueittoken", cancelconfig, nil, "secretkey") end, - function(err) - errorMsg = err + function(err) + errorMsg = err end ) - + assert( status == false ) - assert( utils.endsWith(errorMsg, "customerId can not be nil or empty.") ) + assert( utils.endsWith(errorMsg, "customerId can not be nil or empty.") ) end test_cancelRequestByLocalConfig_empty_customerId() local function test_cancelRequestByLocalConfig_empty_targeturl() - resetAllMocks() + resetAllMocks() - cancelconfig = models.CancelEventConfig.create() + local cancelconfig = models.CancelEventConfig.create() cancelconfig.cookieDomain = "cookieDomain" cancelconfig.eventId = "eventId" cancelconfig.queueDomain = "queueDomain" cancelconfig.version = 12 - status = xpcall( + local errorMsg + local status = xpcall( function() knownUser.cancelRequestByLocalConfig(nil, "queueittoken", cancelconfig, "customerId", "secretkey") end, - function(err) - errorMsg = err + function(err) + errorMsg = err end ) - + assert( status == false ) assert( utils.endsWith(errorMsg, "targetUrl can not be nil or empty.") ) end @@ -263,75 +283,78 @@ function KnownUserTest() local function test_extendQueueCookie_null_EventId() resetAllMocks() - status = xpcall( + local errorMsg + local status = xpcall( function() knownUser.extendQueueCookie(nil, 10, "cookieDomain", "secretkey") end, - function(err) - errorMsg = err + function(err) + errorMsg = err end ) assert( status == false ) - assert( utils.endsWith(errorMsg, "eventId can not be nil or empty.") ) + assert( utils.endsWith(errorMsg, "eventId can not be nil or empty.") ) end test_extendQueueCookie_null_EventId() local function test_extendQueueCookie_null_SecretKey() resetAllMocks() - status = xpcall( + local errorMsg + local status = xpcall( function() knownUser.extendQueueCookie("event1", 10, "cookieDomain", nil) end, - function(err) - errorMsg = err + function(err) + errorMsg = err end ) assert( status == false ) - assert( utils.endsWith(errorMsg, "secretKey can not be nil or empty.") ) - + assert( utils.endsWith(errorMsg, "secretKey can not be nil or empty.") ) end test_extendQueueCookie_null_SecretKey() local function test_extendQueueCookie_Invalid_CookieValidityMinute() resetAllMocks() - status = xpcall( + local errorMsg + local status = xpcall( function() knownUser.extendQueueCookie("event1", "notnumber", "cookieDomain", "secretKey") end, - function(err) - errorMsg = err + function(err) + errorMsg = err end ) assert( status == false ) - assert( utils.endsWith(errorMsg, "cookieValidityMinute should be a number greater than 0.") ) + assert( utils.endsWith(errorMsg, "cookieValidityMinute should be a number greater than 0.") ) end test_extendQueueCookie_Invalid_CookieValidityMinute() local function test_extendQueueCookie_Negative_CookieValidityMinute() resetAllMocks() - status = xpcall( + local errorMsg + local status = xpcall( function() knownUser.extendQueueCookie("event1", -1, "cookieDomain", "secretKey") end, - function(err) - errorMsg = err + function(err) + errorMsg = err end ) assert( status == false ) - assert( utils.endsWith(errorMsg, "cookieValidityMinute should be a number greater than 0.") ) + assert( utils.endsWith(errorMsg, "cookieValidityMinute should be a number greater than 0.") ) end test_extendQueueCookie_Negative_CookieValidityMinute() local function test_extendQueueCookie() resetAllMocks() - + knownUser.extendQueueCookie("eventid", 10, "cookieDomain", "secretkey") assert( userInQueueServiceMock.methodInvokations.method == "extendQueueCookie" ) @@ -344,8 +367,8 @@ function KnownUserTest() local function test_resolveQueueRequestByLocalConfig_empty_eventId() resetAllMocks() - - eventconfig = models.QueueEventConfig.create() + + local eventconfig = models.QueueEventConfig.create() eventconfig.cookieDomain = "cookieDomain" eventconfig.layoutName = "layoutName" eventconfig.culture = "culture" @@ -353,16 +376,18 @@ function KnownUserTest() eventconfig.extendCookieValidity = true eventconfig.cookieValidityMinute = 10 eventconfig.version = 12 - - status = xpcall( + + local errorMsg + local status = xpcall( function() - knownUser.resolveQueueRequestByLocalConfig("targeturl", "queueIttoken", eventconfig, "customerid", "secretkey") + knownUser.resolveQueueRequestByLocalConfig( + "targeturl", "queueIttoken", eventconfig, "customerid", "secretkey") end, - function(err) - errorMsg = err + function(err) + errorMsg = err end ) - + assert( status == false ) assert( utils.endsWith(errorMsg, "eventId from queueConfig can not be nil or empty.") ) end @@ -370,8 +395,8 @@ function KnownUserTest() local function test_resolveQueueRequestByLocalConfig_empty_secretKey() resetAllMocks() - - eventconfig = models.QueueEventConfig.create() + + local eventconfig = models.QueueEventConfig.create() eventconfig.cookieDomain = "cookieDomain" eventconfig.layoutName = "layoutName" eventconfig.culture = "culture" @@ -381,15 +406,16 @@ function KnownUserTest() eventconfig.cookieValidityMinute = 10 eventconfig.version = 12 - status = xpcall( + local errorMsg + local status = xpcall( function() knownUser.resolveQueueRequestByLocalConfig("targeturl", "queueIttoken", eventconfig, "customerid", nil) end, - function(err) - errorMsg = err + function(err) + errorMsg = err end ) - + assert( status == false ) assert( utils.endsWith(errorMsg, "secretKey can not be nil or empty.") ) end @@ -397,8 +423,8 @@ function KnownUserTest() local function test_resolveQueueRequestByLocalConfig_empty_queueDomain() resetAllMocks() - - eventconfig = models.QueueEventConfig.create() + + local eventconfig = models.QueueEventConfig.create() eventconfig.cookieDomain = "cookieDomain" eventconfig.layoutName = "layoutName" eventconfig.culture = "culture" @@ -407,15 +433,17 @@ function KnownUserTest() eventconfig.cookieValidityMinute = 10 eventconfig.version = 12 - status = xpcall( + local errorMsg + local status = xpcall( function() - knownUser.resolveQueueRequestByLocalConfig("targeturl", "queueIttoken", eventconfig, "customerid", "secretkey") + knownUser.resolveQueueRequestByLocalConfig( + "targeturl", "queueIttoken", eventconfig, "customerid", "secretkey") end, - function(err) - errorMsg = err + function(err) + errorMsg = err end ) - + assert( status == false ) assert( utils.endsWith(errorMsg, "queueDomain from queueConfig can not be nil or empty.") ) end @@ -423,8 +451,8 @@ function KnownUserTest() local function test_resolveQueueRequestByLocalConfig_empty_customerId() resetAllMocks() - - eventconfig = models.QueueEventConfig.create() + + local eventconfig = models.QueueEventConfig.create() eventconfig.cookieDomain = "cookieDomain" eventconfig.layoutName = "layoutName" eventconfig.culture = "culture" @@ -434,15 +462,16 @@ function KnownUserTest() eventconfig.cookieValidityMinute = 10 eventconfig.version = 12 - status = xpcall( + local errorMsg + local status = xpcall( function() knownUser.resolveQueueRequestByLocalConfig("targeturl", "queueIttoken", eventconfig, nil, "secretkey") end, - function(err) - errorMsg = err + function(err) + errorMsg = err end ) - + assert( status == false ) assert( utils.endsWith(errorMsg, "customerId can not be nil or empty.") ) end @@ -450,8 +479,8 @@ function KnownUserTest() local function test_resolveQueueRequestByLocalConfig_Invalid_extendCookieValidity() resetAllMocks() - - eventconfig = models.QueueEventConfig.create() + + local eventconfig = models.QueueEventConfig.create() eventconfig.cookieDomain = "cookieDomain" eventconfig.layoutName = "layoutName" eventconfig.culture = "culture" @@ -461,15 +490,17 @@ function KnownUserTest() eventconfig.cookieValidityMinute = 10 eventconfig.version = 12 - status = xpcall( + local errorMsg + local status = xpcall( function() - knownUser.resolveQueueRequestByLocalConfig("targeturl", "queueIttoken", eventconfig, "customerId", "secretkey") + knownUser.resolveQueueRequestByLocalConfig( + "targeturl", "queueIttoken", eventconfig, "customerId", "secretkey") end, - function(err) - errorMsg = err + function(err) + errorMsg = err end ) - + assert( status == false ) assert( utils.endsWith(errorMsg, "extendCookieValidity from queueConfig should be valid boolean.") ) end @@ -477,8 +508,8 @@ function KnownUserTest() local function test_resolveQueueRequestByLocalConfig_Invalid_cookieValidityMinute() resetAllMocks() - - eventconfig = models.QueueEventConfig.create() + + local eventconfig = models.QueueEventConfig.create() eventconfig.cookieDomain = "cookieDomain" eventconfig.layoutName = "layoutName" eventconfig.culture = "culture" @@ -488,15 +519,17 @@ function KnownUserTest() eventconfig.cookieValidityMinute = 10 eventconfig.version = 12 - status = xpcall( + local errorMsg + local status = xpcall( function() - knownUser.resolveQueueRequestByLocalConfig("targeturl", "queueIttoken", eventconfig, "customerId", "secretkey") + knownUser.resolveQueueRequestByLocalConfig( + "targeturl", "queueIttoken", eventconfig, "customerId", "secretkey") end, - function(err) - errorMsg = err + function(err) + errorMsg = err end ) - + assert( status == false ) assert( utils.endsWith(errorMsg, "extendCookieValidity from queueConfig should be valid boolean.") ) end @@ -504,8 +537,8 @@ function KnownUserTest() local function test_resolveQueueRequestByLocalConfig_zero_cookieValidityMinute() resetAllMocks() - - eventconfig = models.QueueEventConfig.create() + + local eventconfig = models.QueueEventConfig.create() eventconfig.cookieDomain = "cookieDomain" eventconfig.layoutName = "layoutName" eventconfig.culture = "culture" @@ -515,24 +548,26 @@ function KnownUserTest() eventconfig.cookieValidityMinute = "test" eventconfig.version = 12 - status = xpcall( + local errorMsg + local status = xpcall( function() - knownUser.resolveQueueRequestByLocalConfig("targeturl", "queueIttoken", eventconfig, "customerId", "secretkey") + knownUser.resolveQueueRequestByLocalConfig( + "targeturl", "queueIttoken", eventconfig, "customerId", "secretkey") end, - function(err) - errorMsg = err + function(err) + errorMsg = err end ) - + assert( status == false ) assert( utils.endsWith(errorMsg, "cookieValidityMinute from queueConfig should be a number greater than 0.") ) end test_resolveQueueRequestByLocalConfig_zero_cookieValidityMinute() local function test_resolveQueueRequestByLocalConfig() - resetAllMocks() - - eventconfig = models.QueueEventConfig.create() + resetAllMocks() + + local eventconfig = models.QueueEventConfig.create() eventconfig.cookieDomain = "cookieDomain" eventconfig.layoutName = "layoutName" eventconfig.culture = "culture" @@ -543,7 +578,8 @@ function KnownUserTest() eventconfig.version = 12 eventconfig.actionName = "QueueAction" - result = knownUser.resolveQueueRequestByLocalConfig("targeturl", "queueIttoken", eventconfig, "customerid", "secretkey") + local result = knownUser.resolveQueueRequestByLocalConfig( + "targeturl", "queueIttoken", eventconfig, "customerid", "secretkey") assert( userInQueueServiceMock.methodInvokations.method == "validateQueueRequest" ) assert( userInQueueServiceMock.methodInvokations.targetUrl == "targeturl" ) @@ -551,14 +587,14 @@ function KnownUserTest() assert( userInQueueServiceMock.methodInvokations.queueConfig == eventconfig ) assert( userInQueueServiceMock.methodInvokations.customerId == "customerid" ) assert( userInQueueServiceMock.methodInvokations.secretKey == "secretkey" ) - + assert( result.isAjaxResult == false ) end test_resolveQueueRequestByLocalConfig() local function test_resolveQueueRequestByLocalConfig_AjaxCall() resetAllMocks() - + iHelpers.request.getHeader = function(name) if (name == "x-queueit-ajaxpageurl") then return "http%3a%2f%2furl" @@ -567,7 +603,7 @@ function KnownUserTest() end end - eventconfig = models.QueueEventConfig.create() + local eventconfig = models.QueueEventConfig.create() eventconfig.cookieDomain = "cookieDomain" eventconfig.layoutName = "layoutName" eventconfig.culture = "culture" @@ -578,9 +614,11 @@ function KnownUserTest() eventconfig.version = 12 eventconfig.actionName = "QueueAction" - userInQueueServiceMock.validateQueueRequestResult = models.RequestValidationResult.create("Queue","eventid","","http://q.queue-it.net","", eventconfig.actionName ); + userInQueueServiceMock.validateQueueRequestResult = models.RequestValidationResult.create( + "Queue","eventid","","http://q.queue-it.net","", eventconfig.actionName ); - result = knownUser.resolveQueueRequestByLocalConfig("targeturl", "queueIttoken", eventconfig, "customerid", "secretkey") + local result = knownUser.resolveQueueRequestByLocalConfig( + "targeturl", "queueIttoken", eventconfig, "customerid", "secretkey") assert( userInQueueServiceMock.methodInvokations.method == "validateQueueRequest" ) assert( userInQueueServiceMock.methodInvokations.targetUrl == "http://url" ) @@ -588,7 +626,7 @@ function KnownUserTest() assert( userInQueueServiceMock.methodInvokations.queueConfig == eventconfig ) assert( userInQueueServiceMock.methodInvokations.customerId == "customerid" ) assert( userInQueueServiceMock.methodInvokations.secretKey == "secretkey" ) - + assert( result.isAjaxResult == true ) assert( result:getAjaxRedirectUrl() == "http%3A%2F%2Fq.queue-it.net" ) assert( result.actionName == eventconfig.actionName ) @@ -597,8 +635,9 @@ function KnownUserTest() local function test_validateRequestByIntegrationConfig() resetAllMocks() - - userInQueueServiceMock.validateQueueRequestResult = models.RequestValidationResult.create("Queue", "eventid", "", "http://q.queue-it.net", "", "event1action") + + userInQueueServiceMock.validateQueueRequestResult = models.RequestValidationResult.create( + "Queue", "eventid", "", "http://q.queue-it.net", "", "event1action") iHelpers.request.getHeader = function(name) if (name == "user-agent") then @@ -607,8 +646,8 @@ function KnownUserTest() return nil end end - - integrationConfigString = + + local integrationConfigString = [[ { "Description": "test", @@ -657,7 +696,8 @@ function KnownUserTest() } ]] - result = knownUser.validateRequestByIntegrationConfig("http://test.com?event1=true", "queueIttoken", integrationConfigString, "customerid", "secretkey") + local result = knownUser.validateRequestByIntegrationConfig( + "http://test.com?event1=true", "queueIttoken", integrationConfigString, "customerid", "secretkey") assert( userInQueueServiceMock.methodInvokations.method == "validateQueueRequest" ) assert( userInQueueServiceMock.methodInvokations.targetUrl == "http://test.com?event1=true" ) @@ -672,7 +712,7 @@ function KnownUserTest() assert( userInQueueServiceMock.methodInvokations.queueConfig["version"] == 3 ) assert( userInQueueServiceMock.methodInvokations.customerId == "customerid" ) assert( userInQueueServiceMock.methodInvokations.secretKey == "secretkey" ) - assert( result.isAjaxResult == false ) + assert( result.isAjaxResult == false ) assert( userInQueueServiceMock.methodInvokations.queueConfig["actionName"] == "event1action") end test_validateRequestByIntegrationConfig() @@ -684,7 +724,7 @@ function KnownUserTest() local function test_validateRequestByIntegrationConfig_NotMatch() resetAllMocks() - integrationConfigString = + local integrationConfigString = [[ { "Description": "test", @@ -698,17 +738,18 @@ function KnownUserTest() } ]] - result = knownUser.validateRequestByIntegrationConfig("http://test.com?event1=true", "queueIttoken", integrationConfigString, "customerid", "secretkey") - + local result = knownUser.validateRequestByIntegrationConfig( + "http://test.com?event1=true", "queueIttoken", integrationConfigString, "customerid", "secretkey") + assert( next(userInQueueServiceMock.methodInvokations) == nil ) - assert( result:doRedirect() == false ) + assert( result:doRedirect() == false ) end test_validateRequestByIntegrationConfig_NotMatch() local function test_validateRequestByIntegrationConfig_ForcedTargeturl() resetAllMocks() - - integrationConfigString = + + local integrationConfigString = [[ { "Description": "test", @@ -749,19 +790,21 @@ function KnownUserTest() "ConfigDataVersion": "1.0.0.1" } ]] - - result = knownUser.validateRequestByIntegrationConfig("http://test.com?event1=true", "queueIttoken", integrationConfigString, "customerid", "secretkey") - + + knownUser.validateRequestByIntegrationConfig( + "http://test.com?event1=true", "queueIttoken", integrationConfigString, "customerid", "secretkey") + assert( userInQueueServiceMock.methodInvokations.method == "validateQueueRequest" ) assert( userInQueueServiceMock.methodInvokations.targetUrl == "http://test.com" ) - assert( userInQueueServiceMock.methodInvokations.queueConfig["actionName"] == "event1action") + assert( userInQueueServiceMock.methodInvokations.queueConfig["actionName"] == "event1action") end test_validateRequestByIntegrationConfig_ForcedTargeturl() local function test_validateRequestByIntegrationConfig_ForcedTargeturl_AjaxCall() resetAllMocks() - - userInQueueServiceMock.validateQueueRequestResult = models.RequestValidationResult.create("Queue", "eventid", "", "http://q.queue-it.net", "") + + userInQueueServiceMock.validateQueueRequestResult = models.RequestValidationResult.create( + "Queue", "eventid", "", "http://q.queue-it.net", "") iHelpers.request.getHeader = function(name) if (name == "x-queueit-ajaxpageurl") then @@ -771,7 +814,7 @@ function KnownUserTest() end end - integrationConfigString = + local integrationConfigString = [[ { "Description": "test", @@ -812,21 +855,22 @@ function KnownUserTest() "ConfigDataVersion": "1.0.0.1" } ]] - - result = knownUser.validateRequestByIntegrationConfig("http://test.com?event1=true", "queueIttoken", integrationConfigString, "customerid", "secretkey") - + + local result = knownUser.validateRequestByIntegrationConfig( + "http://test.com?event1=true", "queueIttoken", integrationConfigString, "customerid", "secretkey") + assert( userInQueueServiceMock.methodInvokations.method == "validateQueueRequest" ) - assert( userInQueueServiceMock.methodInvokations.targetUrl == "http://test.com" ) - assert( userInQueueServiceMock.methodInvokations.queueConfig["actionName"] == "event1action") + assert( userInQueueServiceMock.methodInvokations.targetUrl == "http://test.com" ) + assert( userInQueueServiceMock.methodInvokations.queueConfig["actionName"] == "event1action") assert( result.isAjaxResult == true ) - assert( result:getAjaxRedirectUrl() == "http%3A%2F%2Fq.queue-it.net" ) + assert( result:getAjaxRedirectUrl() == "http%3A%2F%2Fq.queue-it.net" ) end test_validateRequestByIntegrationConfig_ForcedTargeturl_AjaxCall() - + local function test_validateRequestByIntegrationConfig_EventTargetUrl() resetAllMocks() - - integrationConfigString = + + local integrationConfigString = [[ { "Description": "test", @@ -867,18 +911,19 @@ function KnownUserTest() "ConfigDataVersion": "1.0.0.1" } ]] - - result = knownUser.validateRequestByIntegrationConfig("http://test.com?event1=true", "queueIttoken", integrationConfigString, "customerid", "secretkey") - + + knownUser.validateRequestByIntegrationConfig( + "http://test.com?event1=true", "queueIttoken", integrationConfigString, "customerid", "secretkey") + assert( userInQueueServiceMock.methodInvokations.method == "validateQueueRequest" ) assert( userInQueueServiceMock.methodInvokations.targetUrl == "" ) - assert( userInQueueServiceMock.methodInvokations.queueConfig["actionName"] == "event1action") + assert( userInQueueServiceMock.methodInvokations.queueConfig["actionName"] == "event1action") end test_validateRequestByIntegrationConfig_EventTargetUrl() local function test_validateRequestByIntegrationConfig_EventTargetUrl_AjaxCall() resetAllMocks() - + iHelpers.request.getHeader = function(name) if (name == "x-queueit-ajaxpageurl") then return "http%3a%2f%2furl" @@ -887,7 +932,7 @@ function KnownUserTest() end end - integrationConfigString = + local integrationConfigString = [[ { "Description": "test", @@ -928,9 +973,10 @@ function KnownUserTest() "ConfigDataVersion": "1.0.0.1" } ]] - - result = knownUser.validateRequestByIntegrationConfig("http://test.com?event1=true", "queueIttoken", integrationConfigString, "customerid", "secretkey") - + + local result = knownUser.validateRequestByIntegrationConfig( + "http://test.com?event1=true", "queueIttoken", integrationConfigString, "customerid", "secretkey") + assert( userInQueueServiceMock.methodInvokations.method == "validateQueueRequest" ) assert( userInQueueServiceMock.methodInvokations.targetUrl == "" ) assert( userInQueueServiceMock.methodInvokations.queueConfig["actionName"] == "event1action") @@ -940,8 +986,8 @@ function KnownUserTest() local function test_validateRequestByIntegrationConfig_CancelAction() resetAllMocks() - - integrationConfigString = + + local integrationConfigString = [[ { "Description": "test", @@ -977,9 +1023,11 @@ function KnownUserTest() } ]] - userInQueueServiceMock.validateCancelRequestResult = models.RequestValidationResult.create("Cancel", "event1", "queueid", "redirectUrl", nil, "event1action") + userInQueueServiceMock.validateCancelRequestResult = models.RequestValidationResult.create( + "Cancel", "event1", "queueid", "redirectUrl", nil, "event1action") - result = knownUser.validateRequestByIntegrationConfig("http://test.com?event1=true", "queueIttoken", integrationConfigString, "customerid", "secretkey") + local result = knownUser.validateRequestByIntegrationConfig( + "http://test.com?event1=true", "queueIttoken", integrationConfigString, "customerid", "secretkey") assert( result.redirectUrl == "redirectUrl" ) assert( userInQueueServiceMock.methodInvokations.method == "validateCancelRequest" ) @@ -997,7 +1045,7 @@ function KnownUserTest() local function test_validateRequestByIntegrationConfig_CancelAction_AjaxCall() resetAllMocks() - + iHelpers.request.getHeader = function(name) if (name == "x-queueit-ajaxpageurl") then return "http%3a%2f%2furl" @@ -1006,7 +1054,7 @@ function KnownUserTest() end end - integrationConfigString = + local integrationConfigString = [[ { "Description": "test", @@ -1042,9 +1090,11 @@ function KnownUserTest() } ]] - userInQueueServiceMock.validateCancelRequestResult = models.RequestValidationResult.create("Cancel", "event1", "queueid", "redirectUrl", nil) + userInQueueServiceMock.validateCancelRequestResult = models.RequestValidationResult.create( + "Cancel", "event1", "queueid", "redirectUrl", nil) - result = knownUser.validateRequestByIntegrationConfig("http://test.com?event1=true", "queueIttoken", integrationConfigString, "customerid", "secretkey") + local result = knownUser.validateRequestByIntegrationConfig( + "http://test.com?event1=true", "queueIttoken", integrationConfigString, "customerid", "secretkey") assert( result.redirectUrl == "redirectUrl" ) assert( userInQueueServiceMock.methodInvokations.method == "validateCancelRequest" ) @@ -1062,8 +1112,8 @@ function KnownUserTest() local function test_validateRequestByIntegrationConfig_IgnoreAction() resetAllMocks() - - integrationConfigString = + + local integrationConfigString = [[ { "Description": "test", @@ -1099,7 +1149,8 @@ function KnownUserTest() } ]] - result = knownUser.validateRequestByIntegrationConfig("http://test.com?event1=true", "queueIttoken", integrationConfigString, "customerid", "secretkey") + local result = knownUser.validateRequestByIntegrationConfig( + "http://test.com?event1=true", "queueIttoken", integrationConfigString, "customerid", "secretkey") assert( userInQueueServiceMock.methodInvokations.method == "getIgnoreActionResult" ) assert( result.actionType == "Ignore" ) assert( result.isAjaxResult == false ) @@ -1109,7 +1160,7 @@ function KnownUserTest() local function test_validateRequestByIntegrationConfig_IgnoreAction_AjaxCall() resetAllMocks() - + iHelpers.request.getHeader = function(name) if (name == "x-queueit-ajaxpageurl") then return "http%3a%2f%2furl" @@ -1118,7 +1169,7 @@ function KnownUserTest() end end - integrationConfigString = + local integrationConfigString = [[ { "Description": "test", @@ -1154,7 +1205,8 @@ function KnownUserTest() } ]] - result = knownUser.validateRequestByIntegrationConfig("http://test.com?event1=true", "queueIttoken", integrationConfigString, "customerid", "secretkey") + local result = knownUser.validateRequestByIntegrationConfig( + "http://test.com?event1=true", "queueIttoken", integrationConfigString, "customerid", "secretkey") assert( userInQueueServiceMock.methodInvokations.method == "getIgnoreActionResult" ) assert( result.actionType == "Ignore" ) assert( result.isAjaxResult == true ) @@ -1164,19 +1216,19 @@ function KnownUserTest() local function test_validateRequestByIntegrationConfig_debug() resetAllMocks() - + iHelpers.request.getHeader = function(name) if(name == "via") then return "v" end if(name == "forwarded") then return "f" end if(name == "x-forwarded-for") then return "xff" end if(name == "x-forwarded-host") then return "xfh" end if(name == "x-forwarded-proto") then return "xfp" end - return nil + return nil end iHelpers.request.getAbsoluteUri = function() return "OriginalURL" end iHelpers.request.getUserHostAddress = function() return "userIP" end - - integrationConfigString = + + local integrationConfigString = [[ { "Description": "test", @@ -1211,13 +1263,13 @@ function KnownUserTest() "ConfigDataVersion": "1.0.0.1" } ]] - - token = generateHashDebugValidHash("secretkey") - timestamp = os.date("!%Y-%m-%dT%H:%M:%SZ") - url = "http://test.com?event1=true&queueittoken=" .. generateHashDebugValidHash("secretkey") - result = knownUser.validateRequestByIntegrationConfig(url, token, integrationConfigString, "customerid", "secretkey") - expectedCookie = + local token = generateHashDebugValidHash("secretkey") + local timestamp = os.date("!%Y-%m-%dT%H:%M:%SZ") + local url = "http://test.com?event1=true&queueittoken=" .. generateHashDebugValidHash("secretkey") + knownUser.validateRequestByIntegrationConfig(url, token, integrationConfigString, "customerid", "secretkey") + + local expectedCookie = "|SdkVersion=" .. userInQueueServiceMock.SDK_VERSION .. "|Connector=mock-connector" .. "|Runtime=" .. _VERSION .. @@ -1230,34 +1282,35 @@ function KnownUserTest() "|RequestIP=userIP" .. "|RequestHttpHeader_Via=v" .. "|MatchedConfig=event1action" .. - "|ConfigVersion=3" .. + "|ConfigVersion=3" .. "|RequestHttpHeader_XForwardedProto=xfp" .. - "|ServerUtcTime=" .. timestamp .. + "|ServerUtcTime=" .. timestamp .. "|QueueitToken=" .. token .. - "|CancelConfig=EventId:event1&Version:3&QueueDomain:knownusertest.queue-it.net&CookieDomain:.test.com&ActionName:event1action" + "|CancelConfig=EventId:event1&Version:3" .. + "&QueueDomain:knownusertest.queue-it.net&CookieDomain:.test.com&ActionName:event1action" local cookieArray = utils.explode("|", iHelpers.response.debugCookieSet ) - for key, value in pairs(cookieArray) do + for _, value in pairs(cookieArray) do assert(utils:contains(expectedCookie, value), value .. " not found in: " .. expectedCookie) - end + end end test_validateRequestByIntegrationConfig_debug() local function test_validateRequestByIntegrationConfig_debug_withoutmatch() resetAllMocks() - + iHelpers.request.getHeader = function(name) if(name == "via") then return "v" end if(name == "forwarded") then return "f" end if(name == "x-forwarded-for") then return "xff" end if(name == "x-forwarded-host") then return "xfh" end if(name == "x-forwarded-proto") then return "xfp" end - return nil + return nil end iHelpers.request.getAbsoluteUri = function() return "OriginalURL" end iHelpers.request.getUserHostAddress = function() return "userIP" end - - integrationConfigString = + + local integrationConfigString = [[ { "Description": "test", @@ -1292,21 +1345,21 @@ function KnownUserTest() "ConfigDataVersion": "1.0.0.1" } ]] - - token = generateHashDebugValidHash("secretkey") - timestamp = os.date("!%Y-%m-%dT%H:%M:%SZ") - url = "http://test.com?event1=true&queueittoken=" .. token - - result = knownUser.validateRequestByIntegrationConfig(url, token, integrationConfigString, "customerid", "secretkey") - - expectedCookie = + + local token = generateHashDebugValidHash("secretkey") + local timestamp = os.date("!%Y-%m-%dT%H:%M:%SZ") + local url = "http://test.com?event1=true&queueittoken=" .. token + + knownUser.validateRequestByIntegrationConfig(url, token, integrationConfigString, "customerid", "secretkey") + + local expectedCookie = "|SdkVersion=" .. userInQueueServiceMock.SDK_VERSION .. "|Connector=mock-connector" .. "|Runtime=" .. _VERSION .. "|MatchedConfig=NULL" .. "|ConfigVersion=3" .. "|PureUrl=http://test.com?event1=true&queueittoken=" .. token .. - "|ServerUtcTime=" .. timestamp .. + "|ServerUtcTime=" .. timestamp .. "|RequestHttpHeader_XForwardedProto=xfp" .. "|RequestHttpHeader_Via=v" .. "|RequestHttpHeader_XForwardedHost=xfh" .. @@ -1317,15 +1370,15 @@ function KnownUserTest() "|QueueitToken=" .. token local cookieArray = utils.explode("|", iHelpers.response.debugCookieSet ) - for key, value in pairs(cookieArray) do + for _, value in pairs(cookieArray) do assert( utils:contains(expectedCookie, value)) - end + end end test_validateRequestByIntegrationConfig_debug_withoutmatch() local function test_validateRequestByIntegrationConfig_debug_invalid_config_json() resetAllMocks() - + iHelpers.request.getHeader = function(name) if(name == "via") then return "v" end if(name == "forwarded") then return "f" end @@ -1336,25 +1389,26 @@ function KnownUserTest() end iHelpers.request.getAbsoluteUri = function() return "OriginalURL" end iHelpers.request.getUserHostAddress = function() return "userIP" end - - integrationConfigJson = "{}" - token = generateHashDebugValidHash("secretkey") - timestamp = os.date("!%Y-%m-%dT%H:%M:%SZ") - url = "http://test.com?event1=true&queueittoken=" .. generateHashDebugValidHash("secretkey") - - errorMsg = "unspecified" - status = xpcall( + + local integrationConfigJson = "{}" + local token = generateHashDebugValidHash("secretkey") + local timestamp = os.date("!%Y-%m-%dT%H:%M:%SZ") + local url = "http://test.com?event1=true&queueittoken=" .. generateHashDebugValidHash("secretkey") + + local errorMsg = "unspecified" + xpcall( function() - knownUser.validateRequestByIntegrationConfig(url, token, integrationConfigJson, "customerid", "secretkey") + knownUser.validateRequestByIntegrationConfig( + url, token, integrationConfigJson, "customerid", "secretkey") end, - function(err) + function(err) errorMsg = err end ) - + assert( utils.endsWith(errorMsg, "integrationConfigJson was not valid json.") ) - expectedCookie = + local expectedCookie = "|SdkVersion=" .. userInQueueServiceMock.SDK_VERSION .. "|Connector=mock-connector" .. "|Runtime=" .. _VERSION .. @@ -1369,10 +1423,10 @@ function KnownUserTest() "|integrationConfigJson was not valid json." .. "|RequestHttpHeader_XForwardedProto=xfp" .. "|ServerUtcTime=" .. timestamp .. - "|QueueitToken=" .. token - + "|QueueitToken=" .. token + local cookieArray = utils.explode("|", expectedCookie) - for key, value in pairs(cookieArray) do + for _, value in pairs(cookieArray) do assert( utils:contains(iHelpers.response.debugCookieSet, value)) end end @@ -1380,12 +1434,13 @@ function KnownUserTest() local function test_validateRequestByIntegrationConfig_debug_missing_customerid() resetAllMocks() - - integrationConfigString = [[{}]] - token = generateHashDebugValidHash("secretkey") - - result = knownUser.validateRequestByIntegrationConfig("http://test.com?event1=true", token, integrationConfigString, nil, "secretkey") - + + local integrationConfigString = [[{}]] + local token = generateHashDebugValidHash("secretkey") + + local result = knownUser.validateRequestByIntegrationConfig( + "http://test.com?event1=true", token, integrationConfigString, nil, "secretkey") + assert( result.redirectUrl == "https://api2.queue-it.net/diagnostics/connector/error/?code=setup" ) assert( iHelpers.response.debugCookieSet == nil ) end @@ -1393,47 +1448,52 @@ function KnownUserTest() local function test_validateRequestByIntegrationConfig_debug_missing_secretkey() resetAllMocks() - - integrationConfigString = [[{}]] - token = generateHashDebugValidHash("secretkey") - - result = knownUser.validateRequestByIntegrationConfig("http://test.com?event1=true", token, integrationConfigString, "customerid", nil) - + + local integrationConfigString = [[{}]] + local token = generateHashDebugValidHash("secretkey") + + local result = knownUser.validateRequestByIntegrationConfig( + "http://test.com?event1=true", token, integrationConfigString, "customerid", nil) + assert( result.redirectUrl == "https://api2.queue-it.net/diagnostics/connector/error/?code=setup" ) assert( iHelpers.response.debugCookieSet == nil ) end test_validateRequestByIntegrationConfig_debug_missing_secretkey() - local function test_validateRequestByIntegrationConfig_debug_expiredtoken() + local function test_validateRequestByIntegrationConfig_debug_expiredtoken() resetAllMocks() - - integrationConfigString = [[{}]] - invalidDebugToken = generateHashDebugValidHash("secretkey", true) - - result = knownUser.validateRequestByIntegrationConfig("http://test.com?event1=true", invalidDebugToken, integrationConfigString, "customerid", "secretkey") - - assert( result.redirectUrl == "https://customerid.api2.queue-it.net/customerid/diagnostics/connector/error/?code=timestamp" ) + + local integrationConfigString = [[{}]] + local invalidDebugToken = generateHashDebugValidHash("secretkey", true) + + local result = knownUser.validateRequestByIntegrationConfig( + "http://test.com?event1=true", invalidDebugToken, integrationConfigString, "customerid", "secretkey") + + assert( result.redirectUrl == + "https://customerid.api2.queue-it.net/customerid/diagnostics/connector/error/?code=timestamp" ) assert( iHelpers.response.debugCookieSet == nil ) end test_validateRequestByIntegrationConfig_debug_expiredtoken() local function test_validateRequestByIntegrationConfig_debug_modifiedtoken() resetAllMocks() - - integrationConfigString = [[{}]] - invalidDebugToken = generateHashDebugValidHash("secretkey") .. "invalid-hash" - - result = knownUser.validateRequestByIntegrationConfig("http://test.com?event1=true", invalidDebugToken, integrationConfigString, "customerid", "secretkey") - - assert( result.redirectUrl == "https://customerid.api2.queue-it.net/customerid/diagnostics/connector/error/?code=hash" ) + + local integrationConfigString = [[{}]] + local invalidDebugToken = generateHashDebugValidHash("secretkey") .. "invalid-hash" + + local result = knownUser.validateRequestByIntegrationConfig( + "http://test.com?event1=true", invalidDebugToken, integrationConfigString, "customerid", "secretkey") + + assert( result.redirectUrl == + "https://customerid.api2.queue-it.net/customerid/diagnostics/connector/error/?code=hash" ) assert( iHelpers.response.debugCookieSet == nil ) end test_validateRequestByIntegrationConfig_debug_modifiedtoken() local function test_validateRequestByIntegrationConfig__NoDebugToken_Exception_NoCookie() resetAllMocks() - - integrationConfigString = + + local integrationConfigString = [[ { "Description": "test", @@ -1470,30 +1530,31 @@ function KnownUserTest() ]] userInQueueServiceMock.validateCancelRequestRaiseException = true - + pcall(function() - knownUser.validateRequestByIntegrationConfig("http://test.com?event1=true", "queueitToken", integrationConfigString, "customerId", "secretKey") + knownUser.validateRequestByIntegrationConfig( + "http://test.com?event1=true", "queueitToken", integrationConfigString, "customerId", "secretKey") end) assert( iHelpers.response.debugCookieSet == nil ) - end + end test_validateRequestByIntegrationConfig__NoDebugToken_Exception_NoCookie() local function test_resolveQueueRequestByLocalConfig_debug() resetAllMocks() - + iHelpers.request.getHeader = function(name) if(name == "via") then return "v" end if(name == "forwarded") then return "f" end if(name == "x-forwarded-for") then return "xff" end if(name == "x-forwarded-host") then return "xfh" end if(name == "x-forwarded-proto") then return "xfp" end - return nil + return nil end iHelpers.request.getAbsoluteUri = function() return "OriginalURL" end - iHelpers.request.getUserHostAddress = function() return "userIP" end - - eventconfig = models.QueueEventConfig.create() + iHelpers.request.getUserHostAddress = function() return "userIP" end + + local eventconfig = models.QueueEventConfig.create() eventconfig.cookieDomain = "cookieDomain" eventconfig.layoutName = "layoutName" eventconfig.culture = "culture" @@ -1504,16 +1565,16 @@ function KnownUserTest() eventconfig.version = 12 eventconfig.actionName = "event1action" - token = generateHashDebugValidHash("secretkey") - timestamp = os.date("!%Y-%m-%dT%H:%M:%SZ") - result = knownUser.resolveQueueRequestByLocalConfig("targeturl", token, eventconfig, "customerid", "secretkey") + local token = generateHashDebugValidHash("secretkey") + local timestamp = os.date("!%Y-%m-%dT%H:%M:%SZ") + knownUser.resolveQueueRequestByLocalConfig("targeturl", token, eventconfig, "customerid", "secretkey") - expectedCookie = + local expectedCookie = "|SdkVersion=" .. userInQueueServiceMock.SDK_VERSION .. "|Connector=mock-connector" .. "|Runtime=" .. _VERSION .. "|RequestHttpHeader_Forwarded=f" .. - "|ServerUtcTime=" .. timestamp .. + "|ServerUtcTime=" .. timestamp .. "|RequestHttpHeader_XForwardedProto=xfp" .. "|RequestHttpHeader_Via=v" .. "|TargetUrl=targeturl" .. @@ -1522,50 +1583,52 @@ function KnownUserTest() "|RequestHttpHeader_XForwardedFor=xff" .. "|QueueitToken=" .. token .. "|RequestIP=userIP" .. - "|QueueConfig=EventId:eventId&Version:12&QueueDomain:queueDomain&CookieDomain:cookieDomain&ExtendCookieValidity:true&CookieValidityMinute:10&LayoutName:layoutName&Culture:culture&ActionName:event1action" + "|QueueConfig=EventId:eventId&Version:12" .. + "&QueueDomain:queueDomain&CookieDomain:cookieDomain&ExtendCookieValidity" .. + ":true&CookieValidityMinute:10&LayoutName:layoutName&Culture:culture&ActionName:event1action" local cookieArray = utils.explode("|", iHelpers.response.debugCookieSet ) - for key, value in pairs(cookieArray) do + for _, value in pairs(cookieArray) do assert( utils:contains(expectedCookie, value)) - end + end end test_resolveQueueRequestByLocalConfig_debug() local function test_ResolveQueueRequestByLocalConfig_debug_nullconfig() resetAllMocks() - + iHelpers.request.getHeader = function(name) if(name == "via") then return "v" end if(name == "forwarded") then return "f" end if(name == "x-forwarded-for") then return "xff" end if(name == "x-forwarded-host") then return "xfh" end if(name == "x-forwarded-proto") then return "xfp" end - return nil + return nil end iHelpers.request.getAbsoluteUri = function() return "OriginalURL" end - iHelpers.request.getUserHostAddress = function() return "userIP" end - - token = generateHashDebugValidHash("secretkey") - timestamp = os.date("!%Y-%m-%dT%H:%M:%SZ") - - errorMsg = "unspecified" - status = xpcall( + iHelpers.request.getUserHostAddress = function() return "userIP" end + + local token = generateHashDebugValidHash("secretkey") + local timestamp = os.date("!%Y-%m-%dT%H:%M:%SZ") + + local errorMsg = "unspecified" + xpcall( function() knownUser.resolveQueueRequestByLocalConfig("targeturl", token, nil, "customerid", "secretkey") end, - function(err) + function(err) errorMsg = err end ) - + assert( utils.endsWith(errorMsg, "queueConfig can not be nil.") ) - expectedCookie = + local expectedCookie = "|SdkVersion=" .. userInQueueServiceMock.SDK_VERSION .. "|Connector=mock-connector" .. "|Runtime=" .. _VERSION .. "|RequestHttpHeader_Forwarded=f" .. - "|ServerUtcTime=" .. timestamp .. + "|ServerUtcTime=" .. timestamp .. "|RequestHttpHeader_XForwardedProto=xfp" .. "|RequestHttpHeader_Via=v" .. "|TargetUrl=targeturl" .. @@ -1578,20 +1641,20 @@ function KnownUserTest() "|queueConfig can not be nil." local cookieArray = utils.explode("|", expectedCookie) - for key, value in pairs(cookieArray) do + for _, value in pairs(cookieArray) do assert( utils:contains(iHelpers.response.debugCookieSet, value)) - end + end end test_ResolveQueueRequestByLocalConfig_debug_nullconfig() - + local function test_ResolveQueueRequestByLocalConfig_debug_missing_customerid() resetAllMocks() - - eventconfig = models.QueueEventConfig.create() - token = generateHashDebugValidHash("secretkey", true) - - result = knownUser.resolveQueueRequestByLocalConfig("targeturl", token, eventconfig, nil, "secretkey") - + + local eventconfig = models.QueueEventConfig.create() + local token = generateHashDebugValidHash("secretkey", true) + + local result = knownUser.resolveQueueRequestByLocalConfig("targeturl", token, eventconfig, nil, "secretkey") + assert( result.redirectUrl == "https://api2.queue-it.net/diagnostics/connector/error/?code=setup" ) assert( iHelpers.response.debugCookieSet == nil ) end @@ -1599,12 +1662,12 @@ function KnownUserTest() local function test_ResolveQueueRequestByLocalConfig_debug_missing_secretkey() resetAllMocks() - - eventconfig = models.QueueEventConfig.create() - token = generateHashDebugValidHash("secretkey", true) - - result = knownUser.resolveQueueRequestByLocalConfig("targeturl", token, eventconfig, "customerid", nil) - + + local eventconfig = models.QueueEventConfig.create() + local token = generateHashDebugValidHash("secretkey", true) + + local result = knownUser.resolveQueueRequestByLocalConfig("targeturl", token, eventconfig, "customerid", nil) + assert( result.redirectUrl == "https://api2.queue-it.net/diagnostics/connector/error/?code=setup" ) assert( iHelpers.response.debugCookieSet == nil ) end @@ -1612,34 +1675,38 @@ function KnownUserTest() local function test_ResolveQueueRequestByLocalConfig_debug_expiredtoken() resetAllMocks() - - eventconfig = models.QueueEventConfig.create() - token = generateHashDebugValidHash("secretkey", true) - - result = knownUser.resolveQueueRequestByLocalConfig("targeturl", token, eventconfig, "customerid", "secretkey") - - assert( result.redirectUrl == "https://customerid.api2.queue-it.net/customerid/diagnostics/connector/error/?code=timestamp" ) + + local eventconfig = models.QueueEventConfig.create() + local token = generateHashDebugValidHash("secretkey", true) + + local result = knownUser.resolveQueueRequestByLocalConfig( + "targeturl", token, eventconfig, "customerid", "secretkey") + + assert( result.redirectUrl == + "https://customerid.api2.queue-it.net/customerid/diagnostics/connector/error/?code=timestamp" ) assert( iHelpers.response.debugCookieSet == nil ) end test_ResolveQueueRequestByLocalConfig_debug_expiredtoken() - + local function test_ResolveQueueRequestByLocalConfig_debug_modifiedtoken() resetAllMocks() - - eventconfig = models.QueueEventConfig.create() - token = generateHashDebugValidHash("secretkey") .. "invalid-hash" - - result = knownUser.resolveQueueRequestByLocalConfig("targeturl", token, eventconfig, "customerid", "secretkey") - - assert( result.redirectUrl == "https://customerid.api2.queue-it.net/customerid/diagnostics/connector/error/?code=hash" ) + + local eventconfig = models.QueueEventConfig.create() + local token = generateHashDebugValidHash("secretkey") .. "invalid-hash" + + local result = knownUser.resolveQueueRequestByLocalConfig( + "targeturl", token, eventconfig, "customerid", "secretkey") + + assert( result.redirectUrl == + "https://customerid.api2.queue-it.net/customerid/diagnostics/connector/error/?code=hash" ) assert( iHelpers.response.debugCookieSet == nil ) end test_ResolveQueueRequestByLocalConfig_debug_modifiedtoken() local function test_ResolveQueueRequestByLocalConfig_NoDebugToken_Exception_NoCookie() resetAllMocks() - - eventconfig = models.QueueEventConfig.create() + + local eventconfig = models.QueueEventConfig.create() eventconfig.cookieDomain = "cookieDomain" eventconfig.layoutName = "layoutName" eventconfig.culture = "culture" @@ -1653,96 +1720,98 @@ function KnownUserTest() userInQueueServiceMock.validateQueueRequestRaiseException = true pcall(function() - knownUser.resolveQueueRequestByLocalConfig("targeturl", "queueittoken", eventconfig, "customerid", "secretkey") + knownUser.resolveQueueRequestByLocalConfig( + "targeturl", "queueittoken", eventconfig, "customerid", "secretkey") end) assert( iHelpers.response.debugCookieSet == nil ) - end + end test_ResolveQueueRequestByLocalConfig_NoDebugToken_Exception_NoCookie() local function test_cancelRequestByLocalConfig_debug() resetAllMocks() - + iHelpers.request.getHeader = function(name) if(name == "via") then return "v" end if(name == "forwarded") then return "f" end if(name == "x-forwarded-for") then return "xff" end if(name == "x-forwarded-host") then return "xfh" end if(name == "x-forwarded-proto") then return "xfp" end - return nil + return nil end iHelpers.request.getAbsoluteUri = function() return "OriginalURL" end iHelpers.request.getUserHostAddress = function() return "userIP" end - - cancelEventconfig = models.CancelEventConfig.create() + + local cancelEventconfig = models.CancelEventConfig.create() cancelEventconfig.cookieDomain = "cookieDomain" cancelEventconfig.eventId = "eventId" cancelEventconfig.queueDomain = "queueDomain" cancelEventconfig.version = 1 cancelEventconfig.actionName = "event1action" - token = generateHashDebugValidHash("secretkey") - timestamp = os.date("!%Y-%m-%dT%H:%M:%SZ") - result = knownUser.cancelRequestByLocalConfig("targeturl", token, cancelEventconfig, "customerid", "secretkey") + local token = generateHashDebugValidHash("secretkey") + local timestamp = os.date("!%Y-%m-%dT%H:%M:%SZ") + knownUser.cancelRequestByLocalConfig("targeturl", token, cancelEventconfig, "customerid", "secretkey") - expectedCookie = - "|SdkVersion=" .. userInQueueServiceMock.SDK_VERSION .. + local expectedCookie = + "|SdkVersion=" .. userInQueueServiceMock.SDK_VERSION .. "|Connector=mock-connector" .. "|Runtime=" .. _VERSION .. - "|RequestHttpHeader_Forwarded=f" .. - "|ServerUtcTime=" .. timestamp .. - "|RequestHttpHeader_XForwardedProto=xfp" .. - "|RequestHttpHeader_Via=v" .. - "|TargetUrl=targeturl" .. - "|CancelConfig=EventId:eventId&Version:1&QueueDomain:queueDomain&CookieDomain:cookieDomain&ActionName:event1action" .. - "|OriginalUrl=OriginalURL" .. - "|RequestHttpHeader_XForwardedHost=xfh" .. - "|RequestHttpHeader_XForwardedFor=xff" .. + "|RequestHttpHeader_Forwarded=f" .. + "|ServerUtcTime=" .. timestamp .. + "|RequestHttpHeader_XForwardedProto=xfp" .. + "|RequestHttpHeader_Via=v" .. + "|TargetUrl=targeturl" .. + "|CancelConfig=EventId:eventId&Version:1&QueueDomain:queueDomain&" .. + "CookieDomain:cookieDomain&ActionName:event1action" .. + "|OriginalUrl=OriginalURL" .. + "|RequestHttpHeader_XForwardedHost=xfh" .. + "|RequestHttpHeader_XForwardedFor=xff" .. "|QueueitToken=" .. token .. "|RequestIP=userIP" local cookieArray = utils.explode("|", iHelpers.response.debugCookieSet ) - for key, value in pairs(cookieArray) do + for _, value in pairs(cookieArray) do assert( utils:contains(expectedCookie, value)) - end + end end test_cancelRequestByLocalConfig_debug() local function test_CancelRequestByLocalConfig_debug_nullconfig() resetAllMocks() - + iHelpers.request.getHeader = function(name) if(name == "via") then return "v" end if(name == "forwarded") then return "f" end if(name == "x-forwarded-for") then return "xff" end if(name == "x-forwarded-host") then return "xfh" end if(name == "x-forwarded-proto") then return "xfp" end - return nil + return nil end iHelpers.request.getAbsoluteUri = function() return "OriginalURL" end - iHelpers.request.getUserHostAddress = function() return "userIP" end - - token = generateHashDebugValidHash("secretkey") - timestamp = os.date("!%Y-%m-%dT%H:%M:%SZ") - - errorMsg = "unspecified" - status = xpcall( + iHelpers.request.getUserHostAddress = function() return "userIP" end + + local token = generateHashDebugValidHash("secretkey") + local timestamp = os.date("!%Y-%m-%dT%H:%M:%SZ") + + local errorMsg = "unspecified" + xpcall( function() knownUser.cancelRequestByLocalConfig("targeturl", token, nil, "customerid", "secretkey") end, - function(err) + function(err) errorMsg = err end ) - + assert( utils.endsWith(errorMsg, "cancelConfig can not be nil.") ) - expectedCookie = + local expectedCookie = "|SdkVersion=" .. userInQueueServiceMock.SDK_VERSION .. "|Connector=mock-connector" .. "|Runtime=" .. _VERSION .. "|RequestHttpHeader_Forwarded=f" .. - "|ServerUtcTime=" .. timestamp .. + "|ServerUtcTime=" .. timestamp .. "|RequestHttpHeader_XForwardedProto=xfp" .. "|RequestHttpHeader_Via=v" .. "|TargetUrl=targeturl" .. @@ -1755,20 +1824,20 @@ function KnownUserTest() "|cancelConfig can not be nil." local cookieArray = utils.explode("|", expectedCookie) - for key, value in pairs(cookieArray) do + for _, value in pairs(cookieArray) do assert( utils:contains(iHelpers.response.debugCookieSet, value)) end end test_CancelRequestByLocalConfig_debug_nullconfig() - + local function test_CancelRequestByLocalConfig_debug_missing_customerid() resetAllMocks() - - cancelEventconfig = models.CancelEventConfig.create() - token = generateHashDebugValidHash("secretkey", true) - - result = knownUser.cancelRequestByLocalConfig("targeturl", token, cancelEventconfig, nil, "secretkey") - + + local cancelEventconfig = models.CancelEventConfig.create() + local token = generateHashDebugValidHash("secretkey", true) + + local result = knownUser.cancelRequestByLocalConfig("targeturl", token, cancelEventconfig, nil, "secretkey") + assert( result.redirectUrl == "https://api2.queue-it.net/diagnostics/connector/error/?code=setup" ) assert( iHelpers.response.debugCookieSet == nil ) end @@ -1776,12 +1845,12 @@ function KnownUserTest() local function test_CancelRequestByLocalConfig_debug_missing_secretkey() resetAllMocks() - - cancelEventconfig = models.CancelEventConfig.create() - token = generateHashDebugValidHash("secretkey", true) - - result = knownUser.cancelRequestByLocalConfig("targeturl", token, cancelEventconfig, "customerid", nil) - + + local cancelEventconfig = models.CancelEventConfig.create() + local token = generateHashDebugValidHash("secretkey", true) + + local result = knownUser.cancelRequestByLocalConfig("targeturl", token, cancelEventconfig, "customerid", nil) + assert( result.redirectUrl == "https://api2.queue-it.net/diagnostics/connector/error/?code=setup" ) assert( iHelpers.response.debugCookieSet == nil ) end @@ -1789,34 +1858,38 @@ function KnownUserTest() local function test_CancelRequestByLocalConfig_debug_expiredtoken() resetAllMocks() - - cancelEventconfig = models.CancelEventConfig.create() - token = generateHashDebugValidHash("secretkey", true) - - result = knownUser.cancelRequestByLocalConfig("targeturl", token, cancelEventconfig, "customerid", "secretkey") - - assert( result.redirectUrl == "https://customerid.api2.queue-it.net/customerid/diagnostics/connector/error/?code=timestamp" ) + + local cancelEventconfig = models.CancelEventConfig.create() + local token = generateHashDebugValidHash("secretkey", true) + + local result = knownUser.cancelRequestByLocalConfig( + "targeturl", token, cancelEventconfig, "customerid", "secretkey") + + assert( result.redirectUrl == + "https://customerid.api2.queue-it.net/customerid/diagnostics/connector/error/?code=timestamp" ) assert( iHelpers.response.debugCookieSet == nil ) end test_CancelRequestByLocalConfig_debug_expiredtoken() - + local function test_CancelRequestByLocalConfig_debug_modifiedtoken() resetAllMocks() - - cancelEventconfig = models.CancelEventConfig.create() - token = generateHashDebugValidHash("secretkey") .. "invalid-hash" - - result = knownUser.cancelRequestByLocalConfig("targeturl", token, cancelEventconfig, "customerid", "secretkey") - - assert( result.redirectUrl == "https://customerid.api2.queue-it.net/customerid/diagnostics/connector/error/?code=hash" ) + + local cancelEventconfig = models.CancelEventConfig.create() + local token = generateHashDebugValidHash("secretkey") .. "invalid-hash" + + local result = knownUser.cancelRequestByLocalConfig( + "targeturl", token, cancelEventconfig, "customerid", "secretkey") + + assert( result.redirectUrl == + "https://customerid.api2.queue-it.net/customerid/diagnostics/connector/error/?code=hash" ) assert( iHelpers.response.debugCookieSet == nil ) end test_CancelRequestByLocalConfig_debug_modifiedtoken() local function test_cancelRequestByLocalConfig_NoDebugToken_Exception_NoCookie() resetAllMocks() - - cancelEventconfig = models.CancelEventConfig.create() + + local cancelEventconfig = models.CancelEventConfig.create() cancelEventconfig.cookieDomain = "cookieDomain" cancelEventconfig.eventId = "eventId" cancelEventconfig.queueDomain = "queueDomain" diff --git a/SDK/Tests/QueueUrlParamsTest.lua b/SDK/Tests/QueueUrlParamsTest.lua index 15e4bfe..6f8e340 100644 --- a/SDK/Tests/QueueUrlParamsTest.lua +++ b/SDK/Tests/QueueUrlParamsTest.lua @@ -1,8 +1,10 @@ local qitHelpers = require("QueueITHelpers") -function test_ExtractQueueParams() - queueITToken = "e_testevent1~q_6cf23f10-aca7-4fa2-840e-e10f56aecb44~ts_1486645251~ce_True~cv_3~rt_Queue~h_cb7b7b53fa20e708cb59a5a2696f248cba3b2905d92e12ee5523c298adbef298" - result = qitHelpers.QueueUrlParams.extractQueueParams(queueITToken) +local function test_ExtractQueueParams() + local queueITToken = + "e_testevent1~q_6cf23f10-aca7-4fa2-840e-e10f56aecb44~ts_1486645251~" .. + "ce_True~cv_3~rt_Queue~h_cb7b7b53fa20e708cb59a5a2696f248cba3b2905d92e12ee5523c298adbef298" + local result = qitHelpers.QueueUrlParams.extractQueueParams(queueITToken) assert(result.eventId == "testevent1") assert(result.timeStamp == 1486645251) assert(result.extendableCookie == true) @@ -10,14 +12,16 @@ function test_ExtractQueueParams() assert(result.cookieValidityMinutes == 3) assert(result.queueId == "6cf23f10-aca7-4fa2-840e-e10f56aecb44") assert(result.hashCode == "cb7b7b53fa20e708cb59a5a2696f248cba3b2905d92e12ee5523c298adbef298") - assert(result.queueITTokenWithoutHash == "e_testevent1~q_6cf23f10-aca7-4fa2-840e-e10f56aecb44~ts_1486645251~ce_True~cv_3~rt_Queue") + assert(result.queueITTokenWithoutHash == + "e_testevent1~q_6cf23f10-aca7-4fa2-840e-e10f56aecb44~ts_1486645251~ce_True~cv_3~rt_Queue") end test_ExtractQueueParams() -function test_ExtractQueueParams_NotValidToken() - queueITToken = "ts_sasa~cv_adsasa~ce_falwwwse~q_944c1f44-60dd-4e37-aabc-f3e4bb1c8895~h_218b734e-d5be-4b60-ad66-9b1b326266e2" - queueitTokenWithoutHash = "ts_sasa~cv_adsasa~ce_falwwwse~q_944c1f44-60dd-4e37-aabc-f3e4bb1c8895" - result = qitHelpers.QueueUrlParams.extractQueueParams(queueITToken) +local function test_ExtractQueueParams_NotValidToken() + local queueITToken = + "ts_sasa~cv_adsasa~ce_falwwwse~q_944c1f44-60dd-4e37-aabc-f3e4bb1c8895~h_218b734e-d5be-4b60-ad66-9b1b326266e2" + local queueitTokenWithoutHash = "ts_sasa~cv_adsasa~ce_falwwwse~q_944c1f44-60dd-4e37-aabc-f3e4bb1c8895" + local result = qitHelpers.QueueUrlParams.extractQueueParams(queueITToken) assert(result.eventId == "") assert(result.timeStamp == 0) assert(result.extendableCookie == false) @@ -29,9 +33,9 @@ function test_ExtractQueueParams_NotValidToken() end test_ExtractQueueParams_NotValidToken() -function test_ExtractQueueParams_Using_QueueitToken_With_No_Values() - queueITToken = "e~q~ts~ce~rt~h" - result = qitHelpers.QueueUrlParams.extractQueueParams(queueITToken) +local function test_ExtractQueueParams_Using_QueueitToken_With_No_Values() + local queueITToken = "e~q~ts~ce~rt~h" + local result = qitHelpers.QueueUrlParams.extractQueueParams(queueITToken) assert(result.eventId == "") assert(result.timeStamp == 0) assert(result.extendableCookie == false) @@ -43,8 +47,8 @@ function test_ExtractQueueParams_Using_QueueitToken_With_No_Values() end test_ExtractQueueParams_Using_QueueitToken_With_No_Values() -function test_TryExtractQueueParams_Using_Partial_QueueitToken_Expect_Null() - queueParameter = qitHelpers.QueueUrlParams.extractQueueParams("") +local function test_TryExtractQueueParams_Using_Partial_QueueitToken_Expect_Null() + local queueParameter = qitHelpers.QueueUrlParams.extractQueueParams("") assert(queueParameter == nil) end test_TryExtractQueueParams_Using_Partial_QueueitToken_Expect_Null() \ No newline at end of file diff --git a/SDK/Tests/UserInQueueServiceTest.lua b/SDK/Tests/UserInQueueServiceTest.lua index 22cec37..3def269 100644 --- a/SDK/Tests/UserInQueueServiceTest.lua +++ b/SDK/Tests/UserInQueueServiceTest.lua @@ -9,16 +9,23 @@ local userInQueueStateCookieRepositoryMock = require("UserInQueueStateCookieRepo userInQueueStateCookieRepositoryMock.returnThisState = {} userInQueueStateCookieRepositoryMock.getState = function(eventId, cookieValidityMinutes, secretKey, validateTime) - userInQueueStateCookieRepositoryMock.getStateCall = { eventId=eventId, cookieValidityMinutes=cookieValidityMinutes, secretKey=secretKey, validateTime=validateTime } + userInQueueStateCookieRepositoryMock.getStateCall = { + eventId=eventId, cookieValidityMinutes=cookieValidityMinutes, secretKey=secretKey, validateTime=validateTime + } return userInQueueStateCookieRepositoryMock.returnThisState end -userInQueueStateCookieRepositoryMock.store = function(eventId, queueId, fixedCookieValidityMinutes, cookieDomain, redirectType, secretKey) - userInQueueStateCookieRepositoryMock.storeCall = { eventId=eventId, queueId=queueId, fixedCookieValidityMinutes=fixedCookieValidityMinutes, cookieDomain=cookieDomain, redirectType=redirectType, secretKey=secretKey} +userInQueueStateCookieRepositoryMock.store = function( + eventId, queueId, fixedCookieValidityMinutes, cookieDomain, redirectType, secretKey) + + userInQueueStateCookieRepositoryMock.storeCall = { + eventId=eventId, queueId=queueId, fixedCookieValidityMinutes=fixedCookieValidityMinutes, + cookieDomain=cookieDomain, redirectType=redirectType, secretKey=secretKey + } end userInQueueStateCookieRepositoryMock.cancelQueueCookie = function(eventId, cookieDomain) - userInQueueStateCookieRepositoryMock.cancelQueueCookieCall = { eventId=eventId, cookieDomain=cookieDomain} + userInQueueStateCookieRepositoryMock.cancelQueueCookieCall = { eventId=eventId, cookieDomain=cookieDomain} end userInQueueStateCookieRepositoryMock.reset = function() @@ -27,16 +34,18 @@ userInQueueStateCookieRepositoryMock.reset = function() userInQueueStateCookieRepositoryMock.cancelQueueCookieCall = {} end -iHelpers.response.setCookie = function(name, value, expire, domain) +iHelpers.response.setCookie = function(_, _, _, _) end iHelpers.system.getConnectorName = function() return "mock-connector" end -- END Mocks -function UserInQueueServiceTest() - local function generateHash(eventId, queueId, timestamp, extendableCookie, cookieValidityMinutes, redirectType, secretKey) - local token = 'e_' .. eventId .. '~ts_' .. timestamp .. '~ce_' .. extendableCookie .. '~q_' .. queueId +local function UserInQueueServiceTest() + local function generateHash( + eventId, queueId, timestamp, extendableCookie, cookieValidityMinutes, redirectType, secretKey) + + local token = 'e_' .. eventId .. '~ts_' .. timestamp .. '~ce_' .. extendableCookie .. '~q_' .. queueId if (cookieValidityMinutes ~= nil) then token = token .. '~cv_' .. cookieValidityMinutes end @@ -46,10 +55,11 @@ function UserInQueueServiceTest() return token .. '~h_' .. iHelpers.hash.hmac_sha256_encode(token, secretKey) end - - local function test_validateQueueRequest_ValidState_ExtendableCookie_NoCookieExtensionFromConfig_DoNotRedirectDoNotStoreCookieWithExtension() + + local function test_validateQueueRequest_ValidState_ExtCookie_NoCookieExtFromCfg_NoRedirectNotStoreCookieWithExt() userInQueueStateCookieRepositoryMock.reset() - userInQueueStateCookieRepositoryMock.returnThisState = userInQueueStateCookieRepositoryMock.StateInfo.create(true, true, "queueId", nil, "idle") + userInQueueStateCookieRepositoryMock.returnThisState = + userInQueueStateCookieRepositoryMock.StateInfo.create(true, true, "queueId", nil, "idle") local eventConfig = models.QueueEventConfig.create() eventConfig.eventId = "e1" @@ -58,12 +68,12 @@ function UserInQueueServiceTest() eventConfig.cookieValidityMinute = 10 eventConfig.extendCookieValidity = false eventConfig.actionName = "QueueAction" - + local result = userInQueueService.validateQueueRequest("url", "token", eventConfig, "customerid", "key") - + assert( result:doRedirect() == false ) assert( result.queueId == "queueId" ) - + assert( next(userInQueueStateCookieRepositoryMock.storeCall) == nil ) assert( userInQueueStateCookieRepositoryMock.getStateCall.eventId == "e1" ) assert( userInQueueStateCookieRepositoryMock.getStateCall.cookieValidityMinutes == 10 ) @@ -72,12 +82,13 @@ function UserInQueueServiceTest() assert( next(userInQueueStateCookieRepositoryMock.cancelQueueCookieCall) == nil ) assert( result.actionName == eventConfig.actionName ) end - test_validateQueueRequest_ValidState_ExtendableCookie_NoCookieExtensionFromConfig_DoNotRedirectDoNotStoreCookieWithExtension() + test_validateQueueRequest_ValidState_ExtCookie_NoCookieExtFromCfg_NoRedirectNotStoreCookieWithExt() - local function test_validateQueueRequest_ValidState_ExtendableCookie_CookieExtensionFromConfig_DoNotRedirectDoStoreCookieWithExtension() + local function test_validateQueueRequest_ValidState_ExtCookie_CookieExtFromCfg_NoRedirectStoreCookieWithExtension() userInQueueStateCookieRepositoryMock.reset() - userInQueueStateCookieRepositoryMock.returnThisState = userInQueueStateCookieRepositoryMock.StateInfo.create(true, true, "queueId", nil, "disabled") - + userInQueueStateCookieRepositoryMock.returnThisState = + userInQueueStateCookieRepositoryMock.StateInfo.create(true, true, "queueId", nil, "disabled") + local eventConfig = models.QueueEventConfig.create() eventConfig.eventId = "e1" eventConfig.queueDomain = "testDomain.com" @@ -85,13 +96,13 @@ function UserInQueueServiceTest() eventConfig.cookieValidityMinute = 10 eventConfig.extendCookieValidity = true eventConfig.actionName = "QueueAction" - + local result = userInQueueService.validateQueueRequest("url", "token", eventConfig, "customerid", "key") - + assert( result:doRedirect() == false ) assert( result.eventId == 'e1' ) - assert( result.queueId == "queueId" ) - + assert( result.queueId == "queueId" ) + assert( next(userInQueueStateCookieRepositoryMock.storeCall) ~= nil ) assert( userInQueueStateCookieRepositoryMock.storeCall.eventId == "e1" ) assert( userInQueueStateCookieRepositoryMock.storeCall.queueId == "queueId" ) @@ -102,34 +113,36 @@ function UserInQueueServiceTest() assert( next(userInQueueStateCookieRepositoryMock.cancelQueueCookieCall) == nil ) assert( result.actionName == eventConfig.actionName ) end - test_validateQueueRequest_ValidState_ExtendableCookie_CookieExtensionFromConfig_DoNotRedirectDoStoreCookieWithExtension() - + test_validateQueueRequest_ValidState_ExtCookie_CookieExtFromCfg_NoRedirectStoreCookieWithExtension() + local function test_validateQueueRequest_ValidState_NoExtendableCookie_DoNotRedirectDoNotStoreCookieWithExtension() userInQueueStateCookieRepositoryMock.reset() - userInQueueStateCookieRepositoryMock.returnThisState = userInQueueStateCookieRepositoryMock.StateInfo.create(true, true, "queueId", 3, "idle") - + userInQueueStateCookieRepositoryMock.returnThisState = + userInQueueStateCookieRepositoryMock.StateInfo.create(true, true, "queueId", 3, "idle") + local eventConfig = models.QueueEventConfig.create() eventConfig.eventId = "e1" eventConfig.queueDomain = "testDomain" eventConfig.cookieValidityMinute = 10 eventConfig.extendCookieValidity = true eventConfig.actionName = "QueueAction" - + local result = userInQueueService.validateQueueRequest("url", "token", eventConfig, "customerid", "key") - + assert( result:doRedirect() == false ) assert( result.eventId == 'e1' ) - assert( result.queueId == "queueId" ) + assert( result.queueId == "queueId" ) assert( result.actionName == eventConfig.actionName ) assert( next(userInQueueStateCookieRepositoryMock.storeCall) == nil ) assert( next(userInQueueStateCookieRepositoryMock.cancelQueueCookieCall) == nil ) end test_validateQueueRequest_ValidState_NoExtendableCookie_DoNotRedirectDoNotStoreCookieWithExtension() - + local function test_validateQueueRequest_NoCookie_TampredToken_RedirectToErrorPageWithHashError_DoNotStoreCookie() userInQueueStateCookieRepositoryMock.reset() - userInQueueStateCookieRepositoryMock.returnThisState = userInQueueStateCookieRepositoryMock.StateInfo.create(false, false, nil, nil, nil) - + userInQueueStateCookieRepositoryMock.returnThisState = + userInQueueStateCookieRepositoryMock.StateInfo.create(false, false, nil, nil, nil) + local key = "4e1db821-a825-49da-acd0-5d376f2068db" local eventConfig = models.QueueEventConfig.create() eventConfig.eventId = "e1" @@ -139,11 +152,11 @@ function UserInQueueServiceTest() eventConfig.version = 11 eventConfig.actionName = "QueueAction" local url = "http://test.test.com?b=h" - + local token = generateHash('e1','queueId', os.time() + (3 * 60), 'False', nil, 'idle', key) token = token:gsub("False", "True") - local expectedErrorUrl = "https://testDomain.com/error/hash/?c=testCustomer&e=e1" + local expectedErrorUrl = "https://testDomain.com/error/hash/?c=testCustomer&e=e1" .. "&ver=" .. userInQueueService.SDK_VERSION .. "&kupver=mock-connector" .. "&cver=11" @@ -152,24 +165,25 @@ function UserInQueueServiceTest() .. "&t=" .. utils.urlEncode(url) local result = userInQueueService.validateQueueRequest(url, token, eventConfig, "testCustomer", key) - + assert( next(userInQueueStateCookieRepositoryMock.storeCall) == nil ) assert( result:doRedirect() ) assert( result.eventId == 'e1' ) - + local tsPart = result.redirectUrl:gmatch("&ts=[^&]*")() local timestamp = tsPart:gsub("&ts=", "") assert( os.time() - timestamp < 100 ) local urlWithoutTimeStamp = result.redirectUrl:gsub(tsPart, "") assert( urlWithoutTimeStamp == expectedErrorUrl ) - assert( next(userInQueueStateCookieRepositoryMock.cancelQueueCookieCall) == nil ) + assert( next(userInQueueStateCookieRepositoryMock.cancelQueueCookieCall) == nil ) end test_validateQueueRequest_NoCookie_TampredToken_RedirectToErrorPageWithHashError_DoNotStoreCookie() - local function test_validateQueueRequest_NoCookie_ExpiredTimeStampInToken_RedirectToErrorPageWithTimeStampError_DoNotStoreCookie() + local function test_validateQueueRequest_NoCookie_ExpiredTSInToken_RedirectToErrorPageWithTSError_DoNotStoreCookie() userInQueueStateCookieRepositoryMock.reset() - userInQueueStateCookieRepositoryMock.returnThisState = userInQueueStateCookieRepositoryMock.StateInfo.create(false, false, nil, nil, nil) - + userInQueueStateCookieRepositoryMock.returnThisState = + userInQueueStateCookieRepositoryMock.StateInfo.create(false, false, nil, nil, nil) + local key = "4e1db821-a825-49da-acd0-5d376f2068db" local eventConfig = models.QueueEventConfig.create() eventConfig.eventId = "e1" @@ -179,10 +193,10 @@ function UserInQueueServiceTest() eventConfig.version = 11 eventConfig.actionName = "QueueAction" local url = "http://test.test.com?b=h" - + local token = generateHash('e1','queueId', os.time() - (3 * 60), 'False', nil, 'queue', key) - - local expectedErrorUrl = "https://testDomain.com/error/timestamp/?c=testCustomer&e=e1" + + local expectedErrorUrl = "https://testDomain.com/error/timestamp/?c=testCustomer&e=e1" .. "&ver=" .. userInQueueService.SDK_VERSION .. "&kupver=mock-connector" .. "&cver=11" @@ -191,11 +205,11 @@ function UserInQueueServiceTest() .. "&t=" .. utils.urlEncode(url) local result = userInQueueService.validateQueueRequest(url, token, eventConfig, "testCustomer", key) - + assert( next(userInQueueStateCookieRepositoryMock.storeCall) == nil ) assert( result:doRedirect() ) assert( result.eventId == 'e1' ) - + local tsPart = result.redirectUrl:gmatch("&ts=[^&]*")() local timestamp = tsPart:gsub("&ts=", "") assert( os.time() - timestamp < 100 ) @@ -203,12 +217,13 @@ function UserInQueueServiceTest() assert( urlWithoutTimeStamp == expectedErrorUrl ) assert( next(userInQueueStateCookieRepositoryMock.cancelQueueCookieCall) == nil ) end - test_validateQueueRequest_NoCookie_ExpiredTimeStampInToken_RedirectToErrorPageWithTimeStampError_DoNotStoreCookie() - - local function test_validateQueueRequest_NoCookie_EventIdMismatch_RedirectToErrorPageWithEventIdMissMatchError_DoNotStoreCookie() + test_validateQueueRequest_NoCookie_ExpiredTSInToken_RedirectToErrorPageWithTSError_DoNotStoreCookie() + + local function test_validateQueueRequest_NoCookie_EventMismatch_RedirectToErrorPageWithEventError_DontStoreCookie() userInQueueStateCookieRepositoryMock.reset() - userInQueueStateCookieRepositoryMock.returnThisState = userInQueueStateCookieRepositoryMock.StateInfo.create(false, false, nil, nil, nil) - + userInQueueStateCookieRepositoryMock.returnThisState = + userInQueueStateCookieRepositoryMock.StateInfo.create(false, false, nil, nil, nil) + local key = "4e1db821-a825-49da-acd0-5d376f2068db" local eventConfig = models.QueueEventConfig.create() eventConfig.eventId = "e2" @@ -218,23 +233,23 @@ function UserInQueueServiceTest() eventConfig.version = 11 eventConfig.actionName = "QueueAction" local url = "http://test.test.com?b=h" - + local token = generateHash('e1', 'queueId', os.time() - (3 * 60), 'False', nil, 'queue', key) - - local expectedErrorUrl = "https://testDomain.com/error/eventid/?c=testCustomer&e=e2" + + local expectedErrorUrl = "https://testDomain.com/error/eventid/?c=testCustomer&e=e2" .. "&ver=" .. userInQueueService.SDK_VERSION .. "&kupver=mock-connector" .. "&cver=11" .. "&man=" .. eventConfig.actionName .. "&queueittoken=" .. token .. "&t=" .. utils.urlEncode(url) - + local result = userInQueueService.validateQueueRequest(url, token, eventConfig, "testCustomer", key) - + assert( next(userInQueueStateCookieRepositoryMock.storeCall) == nil ) assert( result:doRedirect() ) assert( result.eventId == 'e2' ) - + local tsPart = result.redirectUrl:gmatch("&ts=[^&]*")() local timestamp = tsPart:gsub("&ts=", "") assert( os.time() - timestamp < 100 ) @@ -242,26 +257,27 @@ function UserInQueueServiceTest() assert( urlWithoutTimeStamp == expectedErrorUrl ) assert( next(userInQueueStateCookieRepositoryMock.cancelQueueCookieCall) == nil ) end - test_validateQueueRequest_NoCookie_EventIdMismatch_RedirectToErrorPageWithEventIdMissMatchError_DoNotStoreCookie() - + test_validateQueueRequest_NoCookie_EventMismatch_RedirectToErrorPageWithEventError_DontStoreCookie() + local function test_validateQueueRequest_NoCookie_ValidToken_ExtendableCookie_DoNotRedirect_StoreExtendableCookie() userInQueueStateCookieRepositoryMock.reset() - userInQueueStateCookieRepositoryMock.returnThisState = userInQueueStateCookieRepositoryMock.StateInfo.create(false, false, nil, nil, nil) - + userInQueueStateCookieRepositoryMock.returnThisState = + userInQueueStateCookieRepositoryMock.StateInfo.create(false, false, nil, nil, nil) + local key = "4e1db821-a825-49da-acd0-5d376f2068db" local eventConfig = models.QueueEventConfig.create() eventConfig.eventId = "e1" eventConfig.queueDomain = "testDomain.com" eventConfig.cookieValidityMinute = 10 - eventConfig.cookieDomain = "testDomain" - eventConfig.extendCookieValidity = true + eventConfig.cookieDomain = "testDomain" + eventConfig.extendCookieValidity = true eventConfig.version = 11 eventConfig.actionName = "QueueAction" local url = "http://test.test.com?b=h" - + local token = generateHash('e1', 'queueId', os.time() + (3 * 60), 'true', nil, 'queue', key) - + local result = userInQueueService.validateQueueRequest(url, token, eventConfig, "testCustomer", key) assert( result:doRedirect() == false ) assert( result.eventId == 'e1' ) @@ -279,23 +295,24 @@ function UserInQueueServiceTest() end test_validateQueueRequest_NoCookie_ValidToken_ExtendableCookie_DoNotRedirect_StoreExtendableCookie() - local function test_validateQueueRequest_NoCookie_ValidToken_CookieValidityMinuteFromToken_DoNotRedirect_StoreNonExtendableCookie() + local function test_validateQueueRequest_NoCookie_ValidToken_CookieValMinToken_NoRedirect_StoreNonExtendableCookie() userInQueueStateCookieRepositoryMock.reset() - userInQueueStateCookieRepositoryMock.returnThisState = userInQueueStateCookieRepositoryMock.StateInfo.create(false, false, nil, nil, nil) - + userInQueueStateCookieRepositoryMock.returnThisState = + userInQueueStateCookieRepositoryMock.StateInfo.create(false, false, nil, nil, nil) + local key = "4e1db821-a825-49da-acd0-5d376f2068db" local eventConfig = models.QueueEventConfig.create() eventConfig.eventId = "e1" eventConfig.queueDomain = "testDomain.com" eventConfig.cookieValidityMinute = 30 - eventConfig.cookieDomain = "testDomain" - eventConfig.extendCookieValidity = true + eventConfig.cookieDomain = "testDomain" + eventConfig.extendCookieValidity = true eventConfig.version = 11 eventConfig.actionName = "QueueAction" local url = "http://test.test.com?b=h" local token = generateHash('e1', 'queueId', os.time() + (3 * 60), 'false', 3, 'DirectLink', key) - + local result = userInQueueService.validateQueueRequest(url, token, eventConfig, "testCustomer", key) assert( result:doRedirect() == false ) assert( result.eventId == 'e1' ) @@ -312,12 +329,13 @@ function UserInQueueServiceTest() assert( userInQueueStateCookieRepositoryMock.storeCall.secretKey == key ) assert( next(userInQueueStateCookieRepositoryMock.cancelQueueCookieCall) == nil ) end - test_validateQueueRequest_NoCookie_ValidToken_CookieValidityMinuteFromToken_DoNotRedirect_StoreNonExtendableCookie() + test_validateQueueRequest_NoCookie_ValidToken_CookieValMinToken_NoRedirect_StoreNonExtendableCookie() local function test_NoCookie_NoValidToken_WithoutToken_RedirectToQueue() userInQueueStateCookieRepositoryMock.reset() - userInQueueStateCookieRepositoryMock.returnThisState = userInQueueStateCookieRepositoryMock.StateInfo.create(false, false, nil, nil, nil) - + userInQueueStateCookieRepositoryMock.returnThisState = + userInQueueStateCookieRepositoryMock.StateInfo.create(false, false, nil, nil, nil) + local key = "4e1db821-a825-49da-acd0-5d376f2068db" local eventConfig = models.QueueEventConfig.create() eventConfig.eventId = "e1" @@ -329,10 +347,10 @@ function UserInQueueServiceTest() eventConfig.layoutName = 'testlayout' eventConfig.actionName = "Queue Action (._~-) !*|'\"" local url = "http://test.test.com?b=h" - + local token = "" - - local expectedRedirectUrl = "https://testDomain.com/?c=testCustomer&e=e1" + + local expectedRedirectUrl = "https://testDomain.com/?c=testCustomer&e=e1" .. "&ver=" .. userInQueueService.SDK_VERSION .. "&kupver=mock-connector" .. "&cver=11" @@ -340,9 +358,9 @@ function UserInQueueServiceTest() .. "&cid=en-US" .. "&l=testlayout" .. "&t=" .. utils.urlEncode(url) - + local result = userInQueueService.validateQueueRequest(url, token, eventConfig, "testCustomer", key) - + assert( next(userInQueueStateCookieRepositoryMock.storeCall) == nil ) assert( result:doRedirect() ) assert( result.eventId == 'e1' ) @@ -354,7 +372,8 @@ function UserInQueueServiceTest() local function test_ValidateRequest_NoCookie_WithoutToken_RedirectToQueue_NotargetUrl() userInQueueStateCookieRepositoryMock.reset() - userInQueueStateCookieRepositoryMock.returnThisState = userInQueueStateCookieRepositoryMock.StateInfo.create(false, false, nil, nil, nil) + userInQueueStateCookieRepositoryMock.returnThisState = + userInQueueStateCookieRepositoryMock.StateInfo.create(false, false, nil, nil, nil) local key = "4e1db821-a825-49da-acd0-5d376f2068db" local eventConfig = models.QueueEventConfig.create() @@ -363,22 +382,21 @@ function UserInQueueServiceTest() eventConfig.cookieValidityMinute = 10 eventConfig.extendCookieValidity = false eventConfig.version = 10 - eventConfig.culture = null + eventConfig.culture = nil eventConfig.layoutName = 'testlayout' - eventConfig.actionName = "QueueAction" - local url = "http://test.test.com?b=h" - + eventConfig.actionName = "QueueAction" + local token = "" - + local expectedRedirectUrl = "https://testDomain.com/?c=testCustomer&e=e1" .. "&ver=" .. userInQueueService.SDK_VERSION .. "&kupver=mock-connector" .. "&cver=10" .. "&man=" .. eventConfig.actionName - .. "&l=testlayout" - - local result = userInQueueService.validateQueueRequest(null, token, eventConfig, "testCustomer", key) - + .. "&l=testlayout" + + local result = userInQueueService.validateQueueRequest(nil, token, eventConfig, "testCustomer", key) + assert( next(userInQueueStateCookieRepositoryMock.storeCall) == nil ) assert( result:doRedirect() ) assert( result.eventId == 'e1' ) @@ -387,11 +405,12 @@ function UserInQueueServiceTest() assert( next(userInQueueStateCookieRepositoryMock.cancelQueueCookieCall) == nil ) end test_ValidateRequest_NoCookie_WithoutToken_RedirectToQueue_NotargetUrl() - + local function test_validateQueueRequest_InvalidCookie_InvalidToken_CancelCookie() userInQueueStateCookieRepositoryMock.reset() - userInQueueStateCookieRepositoryMock.returnThisState = userInQueueStateCookieRepositoryMock.StateInfo.create(true, false, nil, nil, nil) - + userInQueueStateCookieRepositoryMock.returnThisState = + userInQueueStateCookieRepositoryMock.StateInfo.create(true, false, nil, nil, nil) + local key = "4e1db821-a825-49da-acd0-5d376f2068db" local eventConfig = models.QueueEventConfig.create() eventConfig.eventId = "e1" @@ -403,11 +422,11 @@ function UserInQueueServiceTest() eventConfig.layoutName = 'testlayout' eventConfig.actionName = "QueueAction" local url = "http://test.test.com?b=h" - - local token = "" - - local result = userInQueueService.validateQueueRequest(url, "ts_sasa~cv_adsasa~ce_falwwwse~q_944c1f44-60dd-4e37-aabc-f3e4bb1c8895", eventConfig, "testCustomer", key) - + + local result = userInQueueService.validateQueueRequest( + url, "ts_sasa~cv_adsasa~ce_falwwwse~q_944c1f44-60dd-4e37-aabc-f3e4bb1c8895", + eventConfig, "testCustomer", key) + assert( next(userInQueueStateCookieRepositoryMock.storeCall) == nil ) assert( result:doRedirect() ) assert( result.eventId == 'e1' ) @@ -420,8 +439,9 @@ function UserInQueueServiceTest() local function test_validateQueueRequest_NoCookie_InvalidToken() userInQueueStateCookieRepositoryMock.reset() - userInQueueStateCookieRepositoryMock.returnThisState = userInQueueStateCookieRepositoryMock.StateInfo.create(false, false, nil, nil, nil) - + userInQueueStateCookieRepositoryMock.returnThisState = + userInQueueStateCookieRepositoryMock.StateInfo.create(false, false, nil, nil, nil) + local key = "4e1db821-a825-49da-acd0-5d376f2068db" local eventConfig = models.QueueEventConfig.create() eventConfig.eventId = "e1" @@ -433,11 +453,11 @@ function UserInQueueServiceTest() eventConfig.layoutName = 'testlayout' eventConfig.actionName = "QueueAction" local url = "http://test.test.com?b=h" - - local token = "" - - local result = userInQueueService.validateQueueRequest(url, "ts_sasa~cv_adsasa~ce_falwwwse~q_944c1f44-60dd-4e37-aabc-f3e4bb1c8895", eventConfig, "testCustomer", key) - + + local result = userInQueueService.validateQueueRequest( + url, "ts_sasa~cv_adsasa~ce_falwwwse~q_944c1f44-60dd-4e37-aabc-f3e4bb1c8895", + eventConfig, "testCustomer", key) + assert( next(userInQueueStateCookieRepositoryMock.storeCall) == nil ) assert( result:doRedirect() ) assert( result.eventId == 'e1' ) @@ -448,39 +468,10 @@ function UserInQueueServiceTest() end test_validateQueueRequest_NoCookie_InvalidToken() - local function test_validateQueueRequest_InvalidCookie_InvalidToken_CancelCookie() - userInQueueStateCookieRepositoryMock.reset() - userInQueueStateCookieRepositoryMock.returnThisState = userInQueueStateCookieRepositoryMock.StateInfo.create(true, false, nil, nil, nil) - - local key = "4e1db821-a825-49da-acd0-5d376f2068db" - local eventConfig = models.QueueEventConfig.create() - eventConfig.eventId = "e1" - eventConfig.queueDomain = "testDomain.com" - eventConfig.cookieValidityMinute = 10 - eventConfig.extendCookieValidity = true - eventConfig.version = 11 - eventConfig.culture = 'en-US' - eventConfig.layoutName = 'testlayout' - eventConfig.actionName = "QueueAction" - local url = "http://test.test.com?b=h" - - local token = "" - - local result = userInQueueService.validateQueueRequest(url, "ts_sasa~cv_adsasa~ce_falwwwse~q_944c1f44-60dd-4e37-aabc-f3e4bb1c8895", eventConfig, "testCustomer", key) - - assert( next(userInQueueStateCookieRepositoryMock.storeCall) == nil ) - assert( result:doRedirect() ) - assert( result.eventId == 'e1' ) - assert( result.queueId == nil ) - assert( result.actionName == eventConfig.actionName ) - assert( utils.startsWith(result.redirectUrl, "https://testDomain.com/error/hash/?c=testCustomer&e=e1") ) - assert( next(userInQueueStateCookieRepositoryMock.cancelQueueCookieCall) ~= nil ) - end - test_validateQueueRequest_InvalidCookie_InvalidToken_CancelCookie() - local function test_validateCancelRequest() userInQueueStateCookieRepositoryMock.reset() - userInQueueStateCookieRepositoryMock.returnThisState = userInQueueStateCookieRepositoryMock.StateInfo.create(true, true, "queueid", 3, "idle") + userInQueueStateCookieRepositoryMock.returnThisState = + userInQueueStateCookieRepositoryMock.StateInfo.create(true, true, "queueid", 3, "idle") local key = "4e1db821-a825-49da-acd0-5d376f2068db" local eventConfig = models.CancelEventConfig.create() @@ -488,40 +479,38 @@ function UserInQueueServiceTest() eventConfig.queueDomain = "testDomain.com" eventConfig.cookieDomain = "testdomain" eventConfig.version = 10 - eventConfig.actionName = "CancelAction" + eventConfig.actionName = "CancelAction" local url = "http://test.test.com?b=h" - - local token = "" - - local expectedUrl = "https://testDomain.com/cancel/testCustomer/e1/?c=testCustomer&e=e1" + + local expectedUrl = "https://testDomain.com/cancel/testCustomer/e1/?c=testCustomer&e=e1" .. "&ver=" .. userInQueueService.SDK_VERSION .. "&kupver=mock-connector" - .. "&cver=10&man=" .. eventConfig.actionName + .. "&cver=10&man=" .. eventConfig.actionName .. "&r=" .. utils.urlEncode(url) - + local result = userInQueueService.validateCancelRequest(url, eventConfig, "testCustomer", key) - + assert( next(userInQueueStateCookieRepositoryMock.storeCall) == nil ) assert( result:doRedirect() ) assert( result.eventId == 'e1' ) assert( result.queueId == "queueid" ) assert( result.actionName == eventConfig.actionName ) assert( result.redirectUrl == expectedUrl ) - assert( next(userInQueueStateCookieRepositoryMock.cancelQueueCookieCall) ~= nil ) + assert( next(userInQueueStateCookieRepositoryMock.cancelQueueCookieCall) ~= nil ) end test_validateCancelRequest() local function test_getIgnoreActionResult() userInQueueStateCookieRepositoryMock.reset() local result = userInQueueService.getIgnoreActionResult("IgnoreAction") - + assert( result:doRedirect() == false ) assert( result.eventId == nil ) assert( result.queueId == nil ) assert( result.redirectUrl == nil ) - assert( result.actionType == "Ignore" ) - assert( result.actionName == "IgnoreAction" ) + assert( result.actionType == "Ignore" ) + assert( result.actionName == "IgnoreAction" ) end - test_getIgnoreActionResult() + test_getIgnoreActionResult() end UserInQueueServiceTest() \ No newline at end of file diff --git a/SDK/Tests/UserInQueueStateCookieRepositoryTest.lua b/SDK/Tests/UserInQueueStateCookieRepositoryTest.lua index 0677ed9..7a80a84 100644 --- a/SDK/Tests/UserInQueueStateCookieRepositoryTest.lua +++ b/SDK/Tests/UserInQueueStateCookieRepositoryTest.lua @@ -17,29 +17,30 @@ iHelpers.response.setCookie = function(name, value, expire, domain) end -- END Mocks -function UserInQueueStateCookieRepositoryTest() +local function UserInQueueStateCookieRepositoryTest() local function generateHash(eventId, queueId, fixedCookieValidityMinutes, redirectType, issueTime, secretKey) - return iHelpers.hash.hmac_sha256_encode(eventId .. queueId .. utils.toString(fixedCookieValidityMinutes) .. redirectType .. issueTime, secretKey) + return iHelpers.hash.hmac_sha256_encode( + eventId .. queueId .. utils.toString(fixedCookieValidityMinutes) .. redirectType .. issueTime, secretKey) end - + local function test_store_hasValidState_ExtendableCookie_CookieIsSaved() mockCookies = { } -- reset - eventId = "event1" - secretKey = "4e1deweb821-a82ew5-49da-acdqq0-5d3476f2068db" - cookieDomain = ".test.com" - queueId = "queueId" - cookieValidity = 10 - + local eventId = "event1" + local secretKey = "4e1deweb821-a82ew5-49da-acdqq0-5d3476f2068db" + local cookieDomain = ".test.com" + local queueId = "queueId" + local cookieValidity = 10 + userInQueueStateCookieRepository.store(eventId, queueId, nil, cookieDomain, "Queue", secretKey) - state = userInQueueStateCookieRepository.getState(eventId, cookieValidity, secretKey, true) - + local state = userInQueueStateCookieRepository.getState(eventId, cookieValidity, secretKey, true) + assert( state.isValid ) assert( state.queueId == queueId ) assert( state:isStateExtendable() ) assert( state.redirectType == "Queue" ) - - cookieKey = userInQueueStateCookieRepository.getCookieKey(eventId) + + local cookieKey = userInQueueStateCookieRepository.getCookieKey(eventId) assert( mockCookies[cookieKey] ~= nil ) assert( tonumber(mockCookies[cookieKey].expire) - os.time() - 24 * 60 * 60 < 100 ) assert( mockCookies[cookieKey].domain == cookieDomain ) @@ -49,22 +50,22 @@ function UserInQueueStateCookieRepositoryTest() local function test_store_hasValidState_nonExtendableCookie_CookieIsSaved() mockCookies = { } -- reset - eventId = "event1" - secretKey = "4e1deweb821-a82ew5-49da-acdqq0-5d3476f2068db" - cookieDomain = ".test.com" - queueId = "queueId" - cookieValidity = 3 - + local eventId = "event1" + local secretKey = "4e1deweb821-a82ew5-49da-acdqq0-5d3476f2068db" + local cookieDomain = ".test.com" + local queueId = "queueId" + local cookieValidity = 3 + userInQueueStateCookieRepository.store(eventId, queueId, cookieValidity, cookieDomain, "Idle", secretKey) - state = userInQueueStateCookieRepository.getState(eventId, cookieValidity, secretKey, true) - + local state = userInQueueStateCookieRepository.getState(eventId, cookieValidity, secretKey, true) + assert( state.isValid ) assert( state.queueId == queueId ) assert( state:isStateExtendable() == false ) assert( state.redirectType == "Idle" ) assert( state.fixedCookieValidityMinutes == 3 ) - - cookieKey = userInQueueStateCookieRepository.getCookieKey(eventId) + + local cookieKey = userInQueueStateCookieRepository.getCookieKey(eventId) assert( mockCookies[cookieKey] ~= nil ) assert( tonumber(mockCookies[cookieKey].expire) - os.time() - 24 * 60 * 60 < 100 ) assert( mockCookies[cookieKey].domain == cookieDomain ) @@ -74,20 +75,20 @@ function UserInQueueStateCookieRepositoryTest() local function test_store_hasValidState_tamperedCookie_stateIsNotValid_isCookieExtendable() mockCookies = { } -- reset - eventId = "event1" - secretKey = "4e1deweb821-a82ew5-49da-acdqq0-5d3476f2068db" - cookieDomain = ".test.com" - queueId = "queueId" - cookieValidity = 10 - + local eventId = "event1" + local secretKey = "4e1deweb821-a82ew5-49da-acdqq0-5d3476f2068db" + local cookieDomain = ".test.com" + local queueId = "queueId" + local cookieValidity = 10 + userInQueueStateCookieRepository.store(eventId, queueId, 3, cookieDomain, "Idle", secretKey) - state = userInQueueStateCookieRepository.getState(eventId, cookieValidity, secretKey, true) + local state = userInQueueStateCookieRepository.getState(eventId, cookieValidity, secretKey, true) assert( state.isValid ) - - cookieKey = userInQueueStateCookieRepository.getCookieKey(eventId) - oldCookieValue = mockCookies[cookieKey].value + + local cookieKey = userInQueueStateCookieRepository.getCookieKey(eventId) + local oldCookieValue = mockCookies[cookieKey].value mockCookies[cookieKey].value = oldCookieValue:gsub("FixedValidityMins=3", "FixedValidityMins=10") - state2 = userInQueueStateCookieRepository.getState(eventId, cookieValidity, secretKey, true) + local state2 = userInQueueStateCookieRepository.getState(eventId, cookieValidity, secretKey, true) assert( state2.isValid == false ) assert( state:isStateExtendable() == false ) end @@ -95,132 +96,130 @@ function UserInQueueStateCookieRepositoryTest() local function test_store_hasValidState_tamperedCookie_stateIsNotValid_eventId() mockCookies = { } -- reset - - eventId = "event1" - secretKey = "4e1deweb821-a82ew5-49da-acdqq0-5d3476f2068db" - cookieDomain = ".test.com" - queueId = "queueId" - cookieValidity = 10 - + + local eventId = "event1" + local secretKey = "4e1deweb821-a82ew5-49da-acdqq0-5d3476f2068db" + local cookieDomain = ".test.com" + local queueId = "queueId" + local cookieValidity = 10 + userInQueueStateCookieRepository.store(eventId, queueId, 3, cookieDomain, "Idle", secretKey) - state = userInQueueStateCookieRepository.getState(eventId, cookieValidity, secretKey, true) + local state = userInQueueStateCookieRepository.getState(eventId, cookieValidity, secretKey, true) assert( state.isValid ) - - cookieKey = userInQueueStateCookieRepository.getCookieKey(eventId) - oldCookieValue = mockCookies[cookieKey].value + + local cookieKey = userInQueueStateCookieRepository.getCookieKey(eventId) + local oldCookieValue = mockCookies[cookieKey].value mockCookies[cookieKey].value = oldCookieValue:gsub("EventId=event1", "EventId=event2") - state2 = userInQueueStateCookieRepository.getState(eventId, cookieValidity, secretKey, true) + local state2 = userInQueueStateCookieRepository.getState(eventId, cookieValidity, secretKey, true) assert( state2.isValid == false ) assert( state:isStateExtendable() == false ) end test_store_hasValidState_tamperedCookie_stateIsNotValid_eventId() - + local function test_store_hasValidState_expiredCookie_stateIsNotValid() mockCookies = { } -- reset - - eventId = "event1" - secretKey = "4e1deweb821-a82ew5-49da-acdqq0-5d3476f2068db" - cookieDomain = ".test.com" - queueId = "queueId" - cookieValidity = -1 - + + local eventId = "event1" + local secretKey = "4e1deweb821-a82ew5-49da-acdqq0-5d3476f2068db" + local cookieDomain = ".test.com" + local queueId = "queueId" + local cookieValidity = -1 + userInQueueStateCookieRepository.store(eventId, queueId, nil, cookieDomain, "Idle", secretKey) - state = userInQueueStateCookieRepository.getState(eventId, cookieValidity, secretKey, true) + local state = userInQueueStateCookieRepository.getState(eventId, cookieValidity, secretKey, true) assert( state.isValid == false ) end test_store_hasValidState_expiredCookie_stateIsNotValid() local function test_store_hasValidState_differentEventId_stateIsNotValid() mockCookies = { } -- reset - - eventId = "event1" - secretKey = "4e1deweb821-a82ew5-49da-acdqq0-5d3476f2068db" - cookieDomain = ".test.com" - queueId = "queueId" - cookieValidity = 10 + + local eventId = "event1" + local secretKey = "4e1deweb821-a82ew5-49da-acdqq0-5d3476f2068db" + local cookieDomain = ".test.com" + local queueId = "queueId" + local cookieValidity = 10 userInQueueStateCookieRepository.store(eventId, queueId, nil, cookieDomain, "Queue", secretKey) - state = userInQueueStateCookieRepository.getState(eventId, cookieValidity, secretKey, true) + local state = userInQueueStateCookieRepository.getState(eventId, cookieValidity, secretKey, true) assert( state.isValid ) - - state2 = userInQueueStateCookieRepository.getState("event2", cookieValidity, secretKey, true) + + local state2 = userInQueueStateCookieRepository.getState("event2", cookieValidity, secretKey, true) assert( state2.isValid == false ) end test_store_hasValidState_differentEventId_stateIsNotValid() - + local function test_hasValidState_noCookie_stateIsNotValid() mockCookies = { } -- reset - - eventId = "event1" - secretKey = "4e1deweb821-a82ew5-49da-acdqq0-5d3476f2068db" - cookieDomain = ".test.com" - queueId = "queueId" - cookieKey = "key" - cookieValidity = 10 - - state = userInQueueStateCookieRepository.getState(eventId, cookieValidity, secretKey, true) - assert( state.isValid == false ) + + local eventId = "event1" + local secretKey = "4e1deweb821-a82ew5-49da-acdqq0-5d3476f2068db" + local cookieValidity = 10 + + local state = userInQueueStateCookieRepository.getState(eventId, cookieValidity, secretKey, true) + assert( state.isValid == false ) end test_hasValidState_noCookie_stateIsNotValid() local function test_hasValidState_invalidCookie_stateIsNotValid() mockCookies = { } -- reset - - eventId = "event1" - secretKey = "4e1deweb821-a82ew5-49da-acdqq0-5d3476f2068db" - cookieDomain = ".test.com" - queueId = "queueId" - cookieValidity = 10 + + local eventId = "event1" + local secretKey = "4e1deweb821-a82ew5-49da-acdqq0-5d3476f2068db" + local cookieDomain = ".test.com" + local queueId = "queueId" + local cookieValidity = 10 userInQueueStateCookieRepository.store(eventId, queueId, 20, cookieDomain, "Queue", secretKey) - state = userInQueueStateCookieRepository.getState(eventId, cookieValidity, secretKey, true) + local state = userInQueueStateCookieRepository.getState(eventId, cookieValidity, secretKey, true) assert( state.isValid ) - - cookieKey = userInQueueStateCookieRepository.getCookieKey(eventId) + + local cookieKey = userInQueueStateCookieRepository.getCookieKey(eventId) mockCookies[cookieKey].value = "IsCookieExtendable=ooOOO&Expires=|||&QueueId=000&Hash=23232" + local state2 = userInQueueStateCookieRepository.getState(eventId, cookieValidity, secretKey, true) assert( state2.isValid == false ) end test_hasValidState_invalidCookie_stateIsNotValid() local function test_cancelQueueCookie() mockCookies = { } -- reset - - eventId = "event1" - secretKey = "4e1deweb821-a82ew5-49da-acdqq0-5d3476f2068db" - cookieDomain = ".test.com" - queueId = "queueId" - cookieValidity = 20 - + + local eventId = "event1" + local secretKey = "4e1deweb821-a82ew5-49da-acdqq0-5d3476f2068db" + local cookieDomain = ".test.com" + local queueId = "queueId" + local cookieValidity = 20 + userInQueueStateCookieRepository.store(eventId, queueId, 20, cookieDomain, "Queue", secretKey) - state = userInQueueStateCookieRepository.getState(eventId, cookieValidity, secretKey, true) + local state = userInQueueStateCookieRepository.getState(eventId, cookieValidity, secretKey, true) assert( state.isValid ) - + userInQueueStateCookieRepository.cancelQueueCookie(eventId, cookieDomain) - state2 = userInQueueStateCookieRepository.getState(eventId, cookieValidity, secretKey, true) + local state2 = userInQueueStateCookieRepository.getState(eventId, cookieValidity, secretKey, true) assert( state2.isValid == false ) - - cookieKey = userInQueueStateCookieRepository.getCookieKey(eventId) + + local cookieKey = userInQueueStateCookieRepository.getCookieKey(eventId) assert( mockCookies[cookieKey] ~= nil ) assert( tonumber(mockCookies[cookieKey].expire) == 1 ) assert( mockCookies[cookieKey].domain == cookieDomain ) assert( mockCookies[cookieKey].value == "deleted" ) end test_cancelQueueCookie() - + local function test_extendQueueCookie_cookieExist() mockCookies = { } -- reset - - eventId = "event1" - secretKey = "4e1deweb821-a82ew5-49da-acdqq0-5d3476f2068db" - cookieDomain = ".test.com" - queueId = "queueId" - cookieKey = userInQueueStateCookieRepository.getCookieKey(eventId) - + + local eventId = "event1" + local secretKey = "4e1deweb821-a82ew5-49da-acdqq0-5d3476f2068db" + local cookieDomain = ".test.com" + local queueId = "queueId" + local cookieKey = userInQueueStateCookieRepository.getCookieKey(eventId) + userInQueueStateCookieRepository.store(eventId, queueId, nil, cookieDomain, "Queue", secretKey) userInQueueStateCookieRepository.reissueQueueCookie(eventId, 12, cookieDomain, secretKey) - - state = userInQueueStateCookieRepository.getState(eventId, 5, secretKey, true) + + local state = userInQueueStateCookieRepository.getState(eventId, 5, secretKey, true) assert( state.isValid ) assert( state.queueId == queueId ) assert( state:isStateExtendable() ) @@ -231,70 +230,77 @@ function UserInQueueStateCookieRepositoryTest() local function test_extendQueueCookie_cookieDoesNotExist() mockCookies = { } -- reset - - eventId = "event1" - secretKey = "4e1deweb821-a82ew5-49da-acdqq0-5d3476f2068db" - cookieDomain = ".test.com" - queueId = "queueId" - + + local eventId = "event1" + local secretKey = "4e1deweb821-a82ew5-49da-acdqq0-5d3476f2068db" + local cookieDomain = ".test.com" + local queueId = "queueId" + userInQueueStateCookieRepository.store("event2", queueId, 20, cookieDomain, "Queue", secretKey) userInQueueStateCookieRepository.reissueQueueCookie(eventId, 12, cookieDomain, secretKey) - - cookieKey = userInQueueStateCookieRepository.getCookieKey("event2") + + local cookieKey = userInQueueStateCookieRepository.getCookieKey("event2") assert( mockCookies[cookieKey] ~= nil ) end test_extendQueueCookie_cookieDoesNotExist() - + local function test_getState_validCookieFormat_extendable() mockCookies = { } -- reset - eventId = "event1" - secretKey = "4e1deweb821-a82ew5-49da-acdqq0-5d3476f2068db" - cookieDomain = ".test.com" - queueId = "queueId" - issueTime = os.time() - hash = generateHash(eventId, queueId, nil, "queue", issueTime, secretKey) + local eventId = "event1" + local secretKey = "4e1deweb821-a82ew5-49da-acdqq0-5d3476f2068db" + local cookieDomain = ".test.com" + local queueId = "queueId" + local issueTime = os.time() + local hash = generateHash(eventId, queueId, nil, "queue", issueTime, secretKey) - cookieKey = userInQueueStateCookieRepository.getCookieKey(eventId) - iHelpers.response.setCookie(cookieKey, "EventId=" .. eventId .. "&QueueId=" .. queueId .. "&RedirectType=queue&IssueTime=" .. issueTime .. "&Hash=" .. hash, os.time() + (24*60*60), cookieDomain) - state = userInQueueStateCookieRepository.getState(eventId, 10, secretKey, true) + local cookieKey = userInQueueStateCookieRepository.getCookieKey(eventId) + iHelpers.response.setCookie( + cookieKey, "EventId=" .. eventId .. "&QueueId=" .. queueId .. "&RedirectType=queue&IssueTime=" .. + issueTime .. "&Hash=" .. hash, os.time() + (24*60*60), cookieDomain) + local state = userInQueueStateCookieRepository.getState(eventId, 10, secretKey, true) assert( state:isStateExtendable() ) assert( state.isValid ) - assert( state.isFound ) + assert( state.isFound ) assert( state.queueId == queueId ) assert( state.redirectType == "queue" ) end test_getState_validCookieFormat_extendable() - + local function test_getState_oldCookie_invalid_expiredCookie_extendable() - eventId = "event1" - secretKey = "4e1deweb821-a82ew5-49da-acdqq0-5d3476f2068db" - cookieDomain = ".test.com" - queueId = "queueId" - cookieKey = userInQueueStateCookieRepository.getCookieKey(eventId) - issueTime = os.time() - (11*60) - hash = generateHash(eventId, queueId, nil, "queue", issueTime, secretKey) + local eventId = "event1" + local secretKey = "4e1deweb821-a82ew5-49da-acdqq0-5d3476f2068db" + local cookieDomain = ".test.com" + local queueId = "queueId" + local cookieKey = userInQueueStateCookieRepository.getCookieKey(eventId) + local issueTime = os.time() - (11*60) + local hash = generateHash(eventId, queueId, nil, "queue", issueTime, secretKey) - iHelpers.response.setCookie(cookieKey, "EventId=" .. eventId .. "&QueueId=" .. queueId .. "&RedirectType=queue&IssueTime=" .. issueTime .. "&Hash=" .. hash, os.time() + (24*60*60), cookieDomain) - state = userInQueueStateCookieRepository.getState(eventId, 10, secretKey, true) + iHelpers.response.setCookie( + cookieKey, "EventId=" .. eventId .. "&QueueId=" .. queueId .. "&RedirectType=queue&IssueTime=" .. + issueTime .. "&Hash=" .. hash, os.time() + (24*60*60), cookieDomain) + local state = userInQueueStateCookieRepository.getState(eventId, 10, secretKey, true) assert(state.isValid == false ) assert(state.isFound ) end test_getState_oldCookie_invalid_expiredCookie_extendable() - + local function test_getState_oldCookie_invalid_expiredCookie_nonExtendable() - eventId = "event1" - secretKey = "4e1deweb821-a82ew5-49da-acdqq0-5d3476f2068db" - cookieDomain = ".test.com" - queueId = "queueId" - issueTime = os.time() - (4*60) - hash = generateHash(eventId, queueId, 3, "idle", issueTime, secretKey) + local eventId = "event1" + local secretKey = "4e1deweb821-a82ew5-49da-acdqq0-5d3476f2068db" + local cookieDomain = ".test.com" + local queueId = "queueId" + local issueTime = os.time() - (4*60) + local hash = generateHash(eventId, queueId, 3, "idle", issueTime, secretKey) - cookieKey = userInQueueStateCookieRepository.getCookieKey(eventId) - iHelpers.response.setCookie(cookieKey, "EventId=" .. eventId .. "&QueueId=" .. queueId .. "&FixedValidityMins=3&RedirectType=idle&IssueTime=" .. issueTime .. "&Hash=" .. hash, os.time() + (24*60*60), cookieDomain) - state = userInQueueStateCookieRepository.getState(eventId, 10, secretKey, true) + local cookieKey = userInQueueStateCookieRepository.getCookieKey(eventId) + iHelpers.response.setCookie( + cookieKey, "EventId=" .. eventId .. "&QueueId=" .. queueId .. + "&FixedValidityMins=3&RedirectType=idle&IssueTime=" .. issueTime .. + "&Hash=" .. hash, os.time() + (24*60*60), cookieDomain) + local state = userInQueueStateCookieRepository.getState(eventId, 10, secretKey, true) assert( state.isValid == false ) assert( state.isFound ) @@ -302,16 +308,19 @@ function UserInQueueStateCookieRepositoryTest() test_getState_oldCookie_invalid_expiredCookie_nonExtendable() local function test_getState_validCookieFormat_nonExtendable() - eventId = "event1" - secretKey = "4e1deweb821-a82ew5-49da-acdqq0-5d3476f2068db" - cookieDomain = ".test.com" - queueId = "queueId" - issueTime = os.time() - hash = generateHash(eventId, queueId, 3, "idle", issueTime, secretKey) - - cookieKey = userInQueueStateCookieRepository.getCookieKey(eventId) - iHelpers.response.setCookie(cookieKey, "EventId=" .. eventId .. "&QueueId=" .. queueId .. "&FixedValidityMins=3&RedirectType=idle&IssueTime=" .. issueTime .. "&Hash=" .. hash, os.time() + (24*60*60), cookieDomain) - state = userInQueueStateCookieRepository.getState(eventId, 10, secretKey, true) + local eventId = "event1" + local secretKey = "4e1deweb821-a82ew5-49da-acdqq0-5d3476f2068db" + local cookieDomain = ".test.com" + local queueId = "queueId" + local issueTime = os.time() + local hash = generateHash(eventId, queueId, 3, "idle", issueTime, secretKey) + + local cookieKey = userInQueueStateCookieRepository.getCookieKey(eventId) + iHelpers.response.setCookie( + cookieKey, "EventId=" .. eventId .. "&QueueId=" .. queueId .. + "&FixedValidityMins=3&RedirectType=idle&IssueTime=" .. issueTime .. + "&Hash=" .. hash, os.time() + (24*60*60), cookieDomain) + local state = userInQueueStateCookieRepository.getState(eventId, 10, secretKey, true) assert( state:isStateExtendable() == false ) assert( state.isValid ) @@ -319,19 +328,19 @@ function UserInQueueStateCookieRepositoryTest() assert( state.queueId == queueId ) assert( state.redirectType == "idle" ) end - test_getState_validCookieFormat_nonExtendable() + test_getState_validCookieFormat_nonExtendable() local function test_getState_noCookie() mockCookies = { } -- reset - eventId = "event1" - secretKey = "4e1deweb821-a82ew5-49da-acdqq0-5d3476f2068db" - - state = userInQueueStateCookieRepository.getState(eventId, 10, secretKey, true) + local eventId = "event1" + local secretKey = "4e1deweb821-a82ew5-49da-acdqq0-5d3476f2068db" + + local state = userInQueueStateCookieRepository.getState(eventId, 10, secretKey, true) assert( state.isFound == false ) assert( state.isValid == false ) end - test_getState_noCookie() + test_getState_noCookie() end UserInQueueStateCookieRepositoryTest() \ No newline at end of file diff --git a/SDK/Tests/ValidationHelpersTest.lua b/SDK/Tests/ValidationHelpersTest.lua index 11fab69..4bd4911 100644 --- a/SDK/Tests/ValidationHelpersTest.lua +++ b/SDK/Tests/ValidationHelpersTest.lua @@ -1,95 +1,108 @@ local validatorHelpers = require("ValidatorHelpers") local iHelpers = require("KnownUserImplementationHelpers") -function UrlValidatorHelperTest_evaluate() - triggerPart = {} - +local function UrlValidatorHelperTest_evaluate() + local triggerPart = {} + triggerPart["UrlPart"] = "PageUrl" triggerPart["Operator"] = "Contains" triggerPart["IsIgnoreCase"] = true triggerPart["IsNegative"] = false triggerPart["ValueToCompare"] = "http://test.tesdomain.com:8080/test?q=1" - assert( validatorHelpers.UrlValidatorHelper.evaluate(triggerPart, "http://test.tesdomain.com:8080/test?q=2") == false ) + assert( validatorHelpers.UrlValidatorHelper.evaluate( + triggerPart, "http://test.tesdomain.com:8080/test?q=2") == false ) triggerPart["UrlPart"] = "PageUrl" triggerPart["Operator"] = "Contains" triggerPart["IsIgnoreCase"] = true triggerPart["IsNegative"] = false - triggerPart["ValueToCompare"] = "%http://test.tesdomain.com:8080/test/resource.lua?queue-event1-nodomain?q=%().+-*?[]^$" - assert( validatorHelpers.UrlValidatorHelper.evaluate(triggerPart, "%http://test.tesdomain.com:8080/test/resource.lua?queue-event1-nodomain?q=%().+-*?[]^$") ) + triggerPart["ValueToCompare"] = + "%http://test.tesdomain.com:8080/test/resource.lua?queue-event1-nodomain?q=%().+-*?[]^$" + assert( validatorHelpers.UrlValidatorHelper.evaluate( + triggerPart, "%http://test.tesdomain.com:8080/test/resource.lua?queue-event1-nodomain?q=%().+-*?[]^$") ) triggerPart["UrlPart"] = "PageUrl" triggerPart["Operator"] = "Equals" triggerPart["IsIgnoreCase"] = true triggerPart["IsNegative"] = false - triggerPart["ValueToCompare"] = "%http://test.tesdomain.com:8080/test/resource.lua?queue-event1-nodomain?q=%().+-*?[]^$" - assert( validatorHelpers.UrlValidatorHelper.evaluate(triggerPart, "%http://test.tesdomain.com:8080/test/resource.lua?queue-event1-nodomain?q=%().+-*?[]^$") ) + triggerPart["ValueToCompare"] = + "%http://test.tesdomain.com:8080/test/resource.lua?queue-event1-nodomain?q=%().+-*?[]^$" + assert( validatorHelpers.UrlValidatorHelper.evaluate( + triggerPart, "%http://test.tesdomain.com:8080/test/resource.lua?queue-event1-nodomain?q=%().+-*?[]^$") ) triggerPart["ValueToCompare"] = "/Test/t1" triggerPart["UrlPart"] = "PagePath" triggerPart["Operator"]= "Equals" triggerPart["IsIgnoreCase"] = true - triggerPart["IsNegative"] = false - assert( validatorHelpers.UrlValidatorHelper.evaluate(triggerPart, "http://test.tesdomain.com:8080/test/t1?q=2&y02&v=%().+-*?[]^$") ) + triggerPart["IsNegative"] = false + assert( validatorHelpers.UrlValidatorHelper.evaluate( + triggerPart, "http://test.tesdomain.com:8080/test/t1?q=2&y02&v=%().+-*?[]^$") ) triggerPart["ValueToCompare"] = "/Test/t1" triggerPart["UrlPart"] = "PagePath" triggerPart["Operator"]= "Equals" triggerPart["IsIgnoreCase"] = true - triggerPart["IsNegative"] = false - assert( validatorHelpers.UrlValidatorHelper.evaluate(triggerPart, "http://test.tesdomain.com:8080/test/t1?q=2&y02&v=%().+-*[]^$") ) + triggerPart["IsNegative"] = false + assert( validatorHelpers.UrlValidatorHelper.evaluate( + triggerPart, "http://test.tesdomain.com:8080/test/t1?q=2&y02&v=%().+-*[]^$") ) triggerPart["ValueToCompare"] = "/Test/t1" triggerPart["UrlPart"] = "PagePath" triggerPart["Operator"]= "Equals" triggerPart["IsIgnoreCase"] = true - triggerPart["IsNegative"] = false - assert( validatorHelpers.UrlValidatorHelper.evaluate(triggerPart, "http://test.tesdomain.com:8080/test/t1") ) + triggerPart["IsNegative"] = false + assert( validatorHelpers.UrlValidatorHelper.evaluate( + triggerPart, "http://test.tesdomain.com:8080/test/t1") ) triggerPart["ValueToCompare"] = "" triggerPart["UrlPart"] = "PagePath" triggerPart["Operator"]= "Equals" triggerPart["IsIgnoreCase"] = true - triggerPart["IsNegative"] = false - assert( validatorHelpers.UrlValidatorHelper.evaluate(triggerPart, "http://test.tesdomain.com:8080") ) + triggerPart["IsNegative"] = false + assert( validatorHelpers.UrlValidatorHelper.evaluate( + triggerPart, "http://test.tesdomain.com:8080") ) triggerPart["UrlPart"] = "HostName" triggerPart["ValueToCompare"] = "test.tesdomain.com:8080" triggerPart["Operator"]= "Contains" triggerPart["IsIgnoreCase"] = true triggerPart["IsNegative"] = false - assert( validatorHelpers.UrlValidatorHelper.evaluate(triggerPart, "http://m.test.tesdomain.com:8080/test?q=2") ) + assert( validatorHelpers.UrlValidatorHelper.evaluate( + triggerPart, "http://m.test.tesdomain.com:8080/test?q=2") ) triggerPart["UrlPart"] = "HostName" triggerPart["ValueToCompare"] = "test.tesdomain.com:8080" triggerPart["Operator"]= "Contains" triggerPart["IsIgnoreCase"] = true triggerPart["IsNegative"] = true - assert( validatorHelpers.UrlValidatorHelper.evaluate(triggerPart,"http://m.test.tesdomain.com:8080/test?q=2") == false ) + assert( validatorHelpers.UrlValidatorHelper.evaluate( + triggerPart,"http://m.test.tesdomain.com:8080/test?q=2") == false ) triggerPart["UrlPart"] = "HostName" triggerPart["ValuesToCompare"] = { "balablaba","test.tesdomain.com:8080" } triggerPart["Operator"]= "Contains" triggerPart["IsIgnoreCase"] = true triggerPart["IsNegative"] = false - assert( validatorHelpers.UrlValidatorHelper.evaluate(triggerPart,"http://m.test.tesdomain.com:8080/test?q=2") ) - + assert( validatorHelpers.UrlValidatorHelper.evaluate( + triggerPart,"http://m.test.tesdomain.com:8080/test?q=2") ) + triggerPart["ValuesToCompare"] = { "ssss_SSss", "/Test/t1" } triggerPart["UrlPart"] = "PagePath" triggerPart["Operator"]= "EqualsAny" triggerPart["IsIgnoreCase"] = true triggerPart["IsNegative"] = false - assert( validatorHelpers.UrlValidatorHelper.evaluate(triggerPart, "http://test.tesdomain.com:8080/test/t1?q=2&y02") ) + assert( validatorHelpers.UrlValidatorHelper.evaluate( + triggerPart, "http://test.tesdomain.com:8080/test/t1?q=2&y02") ) end UrlValidatorHelperTest_evaluate() -function CookieValidatorHelperTest_evaluate() - iHelpers.request.getUnescapedCookieValue = function(name) - if (name=="c1") then - return "hhh" - end - end - triggerPart = {} +local function CookieValidatorHelperTest_evaluate() + iHelpers.request.getUnescapedCookieValue = function(name) + if (name=="c1") then + return "hhh" + end + end + local triggerPart = {} triggerPart["CookieName"] = "c1" triggerPart["Operator"] = "Contains" triggerPart["IsIgnoreCase"] = true @@ -97,12 +110,12 @@ function CookieValidatorHelperTest_evaluate() triggerPart["ValueToCompare"] = "1" assert( validatorHelpers.CookieValidatorHelper.evaluate(triggerPart, iHelpers.request) == false ) - iHelpers.request.getUnescapedCookieValue = function(name) - if (name=="c2") then - return "ddd" + iHelpers.request.getUnescapedCookieValue = function(name) + if (name=="c2") then + return "ddd" end - if (name=="c1") then - return "1" + if (name=="c1") then + return "1" end end triggerPart = {} @@ -111,12 +124,12 @@ function CookieValidatorHelperTest_evaluate() triggerPart["ValueToCompare"] = "1" assert( validatorHelpers.CookieValidatorHelper.evaluate(triggerPart, iHelpers.request) == false ) - iHelpers.request.getUnescapedCookieValue = function(name) - if (name=="c2") then - return "ddd" + iHelpers.request.getUnescapedCookieValue = function(name) + if (name=="c2") then + return "ddd" end - if (name=="c1") then - return "1" + if (name=="c1") then + return "1" end end triggerPart = {} @@ -127,12 +140,12 @@ function CookieValidatorHelperTest_evaluate() triggerPart["IsIgnoreCase"] = true assert( validatorHelpers.CookieValidatorHelper.evaluate(triggerPart, iHelpers.request) ) - iHelpers.request.getUnescapedCookieValue = function(name) - if (name=="c2") then - return "ddd" + iHelpers.request.getUnescapedCookieValue = function(name) + if (name=="c2") then + return "ddd" end - if (name=="c1") then - return "1" + if (name=="c1") then + return "1" end end triggerPart = {} @@ -143,12 +156,12 @@ function CookieValidatorHelperTest_evaluate() triggerPart["IsIgnoreCase"] = true assert( validatorHelpers.CookieValidatorHelper.evaluate(triggerPart, iHelpers.request) == false ) - iHelpers.request.getUnescapedCookieValue = function(name) - if (name=="c2") then - return "ddd" + iHelpers.request.getUnescapedCookieValue = function(name) + if (name=="c2") then + return "ddd" end - if (name=="c1") then - return "cookie value value value" + if (name=="c1") then + return "cookie value value value" end end triggerPart = {} @@ -159,14 +172,14 @@ function CookieValidatorHelperTest_evaluate() triggerPart["IsNegative"] = false assert( validatorHelpers.CookieValidatorHelper.evaluate(triggerPart, iHelpers.request) ) - iHelpers.request.getUnescapedCookieValue = function(name) - if (name=="c2") then - return "ddd" + iHelpers.request.getUnescapedCookieValue = function(name) + if (name=="c2") then + return "ddd" end - if (name=="c1") then - return "1" + if (name=="c1") then + return "1" end - end + end triggerPart = {} triggerPart["CookieName"] = "c1" triggerPart["Operator"] = "EqualsAny" @@ -177,13 +190,15 @@ function CookieValidatorHelperTest_evaluate() end CookieValidatorHelperTest_evaluate() -function UserAgentValidatorHelperTest_evaluate() - triggerPart = {} +local function UserAgentValidatorHelperTest_evaluate() + local triggerPart = {} triggerPart["Operator"] = "Contains" triggerPart["IsIgnoreCase"] = false triggerPart["IsNegative"] = false triggerPart["ValueToCompare"] = "googlebot" - iHelpers.request.getHeader = function(name) if (name == "user-agent") then return "Googlebot sample useraagent" end end + iHelpers.request.getHeader = function(name) + if (name == "user-agent") then return "Googlebot sample useraagent" end + end assert( validatorHelpers.UserAgentValidatorHelper.evaluate(triggerPart, iHelpers.request) == false ) triggerPart = {} @@ -191,7 +206,9 @@ function UserAgentValidatorHelperTest_evaluate() triggerPart["ValueToCompare"] = "googlebot" triggerPart["IsIgnoreCase"] = true triggerPart["IsNegative"] = true - iHelpers.request.getHeader = function(name) if (name == "user-agent") then return "oglebot sample useraagent" end end + iHelpers.request.getHeader = function(name) + if (name == "user-agent") then return "oglebot sample useraagent" end + end assert( validatorHelpers.UserAgentValidatorHelper.evaluate(triggerPart, iHelpers.request) ) triggerPart = {} @@ -223,13 +240,15 @@ function UserAgentValidatorHelperTest_evaluate() triggerPart["ValuesToCompare"] = { "googlebot" } triggerPart["IsIgnoreCase"] = true triggerPart["IsNegative"] = true - iHelpers.request.getHeader = function(name) if (name == "user-agent") then return "oglebot sample useraagent" end end + iHelpers.request.getHeader = function(name) + if (name == "user-agent") then return "oglebot sample useraagent" end + end assert( validatorHelpers.UserAgentValidatorHelper.evaluate(triggerPart, iHelpers.request) ) end UserAgentValidatorHelperTest_evaluate() -function HttpHeaderValidatorHelperTest_evaluate() - triggerPart = {} +local function HttpHeaderValidatorHelperTest_evaluate() + local triggerPart = {} triggerPart["Operator"] = "Contains" triggerPart["IsIgnoreCase"] = false triggerPart["IsNegative"] = false @@ -240,7 +259,9 @@ function HttpHeaderValidatorHelperTest_evaluate() triggerPart["Operator"] = "Contains" triggerPart["IsIgnoreCase"] = false triggerPart["IsNegative"] = false - iHelpers.request.getHeader = function(name) if (name=="c2") then return "t1" end if (name=="c3") then return "t1" end end + iHelpers.request.getHeader = function(name) + if (name=="c2") then return "t1" end if (name=="c3") then return "t1" end + end assert( validatorHelpers.HttpHeaderValidatorHelper.evaluate(triggerPart, iHelpers.request) == false ) triggerPart = {} @@ -249,7 +270,9 @@ function HttpHeaderValidatorHelperTest_evaluate() triggerPart["IsNegative"] = true triggerPart["ValueToCompare"] = "t1" triggerPart["HttpHeaderName"] = "c1" - iHelpers.request.getHeader = function(name) if (name=="c2") then return "t1" end if (name=="c3") then return "t1" end end + iHelpers.request.getHeader = function(name) + if (name=="c2") then return "t1" end if (name=="c3") then return "t1" end + end assert( validatorHelpers.HttpHeaderValidatorHelper.evaluate(triggerPart, iHelpers.request) ) triggerPart = {} @@ -258,7 +281,11 @@ function HttpHeaderValidatorHelperTest_evaluate() triggerPart["IsNegative"] = true triggerPart["ValueToCompare"] = "t1" triggerPart["HttpHeaderName"] = "C1" - iHelpers.request.getHeader = function(name) if (name=="c2") then return "t1" end if (name=="c3") then return "t1" end if (name=="c1") then return "test t1 test " end end + iHelpers.request.getHeader = function(name) + if (name=="c2") then return "t1" end + if (name=="c3") then return "t1" end + if (name=="c1") then return "test t1 test " end + end assert( validatorHelpers.HttpHeaderValidatorHelper.evaluate(triggerPart, iHelpers.request) == false ) triggerPart = {} @@ -267,7 +294,11 @@ function HttpHeaderValidatorHelperTest_evaluate() triggerPart["IsNegative"] = false triggerPart["ValueToCompare"] = "t1" triggerPart["HttpHeaderName"] = "C1" - iHelpers.request.getHeader = function(name) if (name=="c2") then return "t1" end if (name=="c3") then return "t1" end if (name=="c1") then return "test T1 test " end end + iHelpers.request.getHeader = function(name) + if (name=="c2") then return "t1" end + if (name=="c3") then return "t1" end + if (name=="c1") then return "test T1 test " end + end assert( validatorHelpers.HttpHeaderValidatorHelper.evaluate(triggerPart, iHelpers.request) ) triggerPart = {} @@ -276,7 +307,11 @@ function HttpHeaderValidatorHelperTest_evaluate() triggerPart["IsNegative"] = false triggerPart["ValuesToCompare"] = { "blabalabala","t1","t2" } triggerPart["HttpHeaderName"] = "C1" - iHelpers.request.getHeader = function(name) if (name=="c2") then return "t1" end if (name=="c3") then return "t1" end if (name=="c1") then return "test T1 test " end end + iHelpers.request.getHeader = function(name) + if (name=="c2") then return "t1" end + if (name=="c3") then return "t1" end + if (name=="c1") then return "test T1 test " end + end assert( validatorHelpers.HttpHeaderValidatorHelper.evaluate(triggerPart, iHelpers.request) ) triggerPart = {} @@ -285,7 +320,11 @@ function HttpHeaderValidatorHelperTest_evaluate() triggerPart["IsNegative"] = true triggerPart["ValuesToCompare"] = { "bla","bla", "t1" } triggerPart["HttpHeaderName"] = "c1" - iHelpers.request.getHeader = function(name) if (name=="c2") then return "t1" end if (name=="c3") then return "t1" end if (name=="c1") then return "t1" end end + iHelpers.request.getHeader = function(name) + if (name=="c2") then return "t1" end + if (name=="c3") then return "t1" end + if (name=="c1") then return "t1" end + end assert( validatorHelpers.HttpHeaderValidatorHelper.evaluate(triggerPart, iHelpers.request) == false) end HttpHeaderValidatorHelperTest_evaluate() \ No newline at end of file diff --git a/SDK/Tests/_RUNALL.lua b/SDK/Tests/_RUNALL.lua index 44c2767..d701335 100644 --- a/SDK/Tests/_RUNALL.lua +++ b/SDK/Tests/_RUNALL.lua @@ -4,7 +4,7 @@ package.path = "Helpers/?/?.lua;" .. package.path package.path = "SDK/Tests/?.lua;" .. package.path -- implement helpers for unit test usage -iHelpers = require("KnownUserImplementationHelpers") +local iHelpers = require("KnownUserImplementationHelpers") iHelpers.hash.hmac_sha256_encode = function(message, key) local sha2 = require("sha2") return sha2.hmac(sha2.sha256, key, message) diff --git a/SDK/UserInQueueService.lua b/SDK/UserInQueueService.lua index ef855c4..7dcd6ff 100644 --- a/SDK/UserInQueueService.lua +++ b/SDK/UserInQueueService.lua @@ -5,17 +5,17 @@ local utils = require("Utils") local userInQueueStateCookieRepository = require("UserInQueueStateCookieRepository") local svc = { - SDK_VERSION = "v3-lua-" .. "3.6.3", + SDK_VERSION = "v3-lua-" .. "3.6.4", TokenValidationResult = { create = function(isValid, errorCode) local model = { isValid = isValid; errorCode = errorCode; } - - return model + + return model end - } + } } -- Private functions @@ -35,7 +35,7 @@ local function getQueryString(customerId, eventId, configVersion, actionName, cu if (utils.toString(culture) ~= "") then table.insert(queryStringList, "cid=" .. utils.urlEncode(culture)) end - + if (utils.toString(layoutName) ~= "") then table.insert(queryStringList, "l=" .. utils.urlEncode(layoutName)) end @@ -57,12 +57,13 @@ local function getQueueResult(targetUrl, config, customerId) tparam = "&t=" .. utils.urlEncode(targetUrl) end - local query = getQueryString(customerId, config.eventId, config.version, + local query = getQueryString(customerId, config.eventId, config.version, config.actionName, config.culture, config.layoutName) .. tparam local redirectUrl = generateRedirectUrl(config.queueDomain, "", query) - - return models.RequestValidationResult.create(models.ActionTypes.QueueAction, config.eventId, nil, redirectUrl, nil, config.actionName) + + return models.RequestValidationResult.create( + models.ActionTypes.QueueAction, config.eventId, nil, redirectUrl, nil, config.actionName) end local function getErrorResult(customerId, targetUrl, config, qParams, errorCode) @@ -70,15 +71,17 @@ local function getErrorResult(customerId, targetUrl, config, qParams, errorCode) if (utils.toString(targetUrl) ~= "") then tParam = "&t=" .. utils.urlEncode(targetUrl) end - - local query = getQueryString(customerId, config.eventId, config.version, config.actionName, config.culture, config.layoutName) + + local query = getQueryString( + customerId, config.eventId, config.version, config.actionName, config.culture, config.layoutName) .. "&queueittoken=" .. qParams.queueITToken .. "&ts=" .. os.time() .. tParam local redirectUrl = generateRedirectUrl(config.queueDomain, "error/" .. errorCode .. "/", query) - return models.RequestValidationResult.create(models.ActionTypes.QueueAction, config.eventId, nil, redirectUrl, nil, config.actionName) + return models.RequestValidationResult.create( + models.ActionTypes.QueueAction, config.eventId, nil, redirectUrl, nil, config.actionName) end local function getValidTokenResult(config, queueParams, secretKey) @@ -89,7 +92,9 @@ local function getValidTokenResult(config, queueParams, secretKey) utils.toString(config.cookieDomain), queueParams.redirectType, secretKey) - return models.RequestValidationResult.create(models.ActionTypes.QueueAction, config.eventId, queueParams.queueId, nil, queueParams.redirectType, config.actionName) + return models.RequestValidationResult.create( + models.ActionTypes.QueueAction, config.eventId, queueParams.queueId, + nil, queueParams.redirectType, config.actionName) end local function validateToken(config, queueParams, secretKey) @@ -111,7 +116,7 @@ end -- END Private functions -svc.validateQueueRequest = function(targetUrl, queueitToken, config, customerId, secretKey) +svc.validateQueueRequest = function(targetUrl, queueitToken, config, customerId, secretKey) local state = userInQueueStateCookieRepository.getState(config.eventId, config.cookieValidityMinute, secretKey, true) if (state.isValid) then @@ -123,28 +128,30 @@ svc.validateQueueRequest = function(targetUrl, queueitToken, config, customerId, utils.toString(config.cookieDomain), state.redirectType, secretKey) - end - local result = models.RequestValidationResult.create(models.ActionTypes.QueueAction, config.eventId, state.queueId, nil, state.redirectType, config.actionName) + end + local result = models.RequestValidationResult.create( + models.ActionTypes.QueueAction, config.eventId, state.queueId, nil, state.redirectType, config.actionName) return result end - + local queueParams = qitHelpers.QueueUrlParams.extractQueueParams(queueitToken) local requestValidationResult local isTokenValid = false if (queueParams ~= nil) then - tokenValidationResult = validateToken(config, queueParams, secretKey) + local tokenValidationResult = validateToken(config, queueParams, secretKey) isTokenValid = tokenValidationResult.isValid if(isTokenValid) then requestValidationResult = getValidTokenResult(config, queueParams, secretKey) else - requestValidationResult = getErrorResult(customerId, targetUrl, config, queueParams, tokenValidationResult.errorCode); + requestValidationResult = getErrorResult( + customerId, targetUrl, config, queueParams, tokenValidationResult.errorCode); end else requestValidationResult = getQueueResult(targetUrl, config, customerId); - end + end if (state.isFound and not isTokenValid) then userInQueueStateCookieRepository.cancelQueueCookie(config.eventId, config.cookieDomain); @@ -156,21 +163,24 @@ end svc.validateCancelRequest = function(targetUrl, cancelConfig, customerId, secretKey) --we do not care how long cookie is valid while canceling cookie local state = userInQueueStateCookieRepository.getState(cancelConfig.eventId, -1, secretKey, false) - if (state.isValid) then + if (state.isValid) then local uriPath = "cancel/" .. customerId .. "/" .. cancelConfig.eventId .. "/" userInQueueStateCookieRepository.cancelQueueCookie(cancelConfig.eventId, cancelConfig.cookieDomain) - + local rParam = "" if (utils.toString(targetUrl) ~= "") then rParam = "&r=" .. utils.urlEncode(targetUrl) end - local query = getQueryString(customerId, cancelConfig.eventId, cancelConfig.version, cancelConfig.actionName, nil, nil) .. rParam + local query = getQueryString( + customerId, cancelConfig.eventId, cancelConfig.version, cancelConfig.actionName, nil, nil) .. rParam local redirectUrl = generateRedirectUrl(cancelConfig.queueDomain, uriPath, query) - - return models.RequestValidationResult.create(models.ActionTypes.CancelAction, cancelConfig.eventId, - state.queueId, redirectUrl, state.redirectType, cancelConfig.actionName) + + return models.RequestValidationResult.create( + models.ActionTypes.CancelAction, cancelConfig.eventId, + state.queueId, redirectUrl, state.redirectType, cancelConfig.actionName) else - return models.RequestValidationResult.create(models.ActionTypes.CancelAction, cancelConfig.eventId, nil, nil, nil, cancelConfig.actionName) + return models.RequestValidationResult.create( + models.ActionTypes.CancelAction, cancelConfig.eventId, nil, nil, nil, cancelConfig.actionName) end end @@ -178,7 +188,7 @@ svc.extendQueueCookie = function(eventId, cookieValidityMinutes, cookieDomain, s userInQueueStateCookieRepository.reissueQueueCookie(eventId, cookieValidityMinutes, cookieDomain, secretKey) end -svc.getIgnoreActionResult = function(actionName) +svc.getIgnoreActionResult = function(actionName) return models.RequestValidationResult.create(models.ActionTypes.IgnoreAction, nil, nil, nil, nil, actionName) end diff --git a/SDK/UserInQueueStateCookieRepository.lua b/SDK/UserInQueueStateCookieRepository.lua index 38230bc..f6a9c7a 100644 --- a/SDK/UserInQueueStateCookieRepository.lua +++ b/SDK/UserInQueueStateCookieRepository.lua @@ -7,25 +7,27 @@ local function generateHash(eventId, queueId, fixedCookieValidityMinutes, redire return iHelpers.hash.hmac_sha256_encode(message, secretKey) end -local function createCookieValue(eventId, queueId, fixedCookieValidityMinutes, redirectType, secretKey) +local function createCookieValue(eventId, queueId, fixedCookieValidityMinutes, redirectType, secretKey) local issueTime = os.time() local hashValue = generateHash(eventId, queueId, fixedCookieValidityMinutes, redirectType, issueTime, secretKey) - + local fixedCookieValidityMinutesPart = "" if (fixedCookieValidityMinutes ~= "") then fixedCookieValidityMinutesPart = "&FixedValidityMins=" .. fixedCookieValidityMinutes - end - - local cookieValue = "EventId=" .. eventId .. "&QueueId=" .. queueId .. fixedCookieValidityMinutesPart .. "&RedirectType=" .. redirectType .. "&IssueTime=" .. issueTime .. "&Hash=" .. hashValue + end + + local cookieValue = "EventId=" .. eventId .. + "&QueueId=" .. queueId .. fixedCookieValidityMinutesPart .. + "&RedirectType=" .. redirectType .. "&IssueTime=" .. issueTime .. "&Hash=" .. hashValue return cookieValue end local function getCookieNameValueMap(cookieValue) - local result = { } - + local result = { } + local cookieNameValues = utils.explode("&", cookieValue) - - for i, cookieNameValue in pairs(cookieNameValues) do + + for _, cookieNameValue in pairs(cookieNameValues) do local arr = utils.explode("=", cookieNameValue) if(arr[1] ~= nil and arr[2] ~= nil) then result[arr[1]] = arr[2] @@ -51,14 +53,14 @@ local function isCookieValid(secretKey, cookieNameValueMap, eventId, cookieValid if (cookieNameValueMap["Hash"] == nil) then return false end - + local fixedCookieValidityMinutes = "" if (cookieNameValueMap["FixedValidityMins"] ~= nil) then - fixedCookieValidityMinutes = cookieNameValueMap["FixedValidityMins"] + fixedCookieValidityMinutes = cookieNameValueMap["FixedValidityMins"] end - + local hashValue = generateHash( - cookieNameValueMap["EventId"], + cookieNameValueMap["EventId"], cookieNameValueMap["QueueId"], fixedCookieValidityMinutes, cookieNameValueMap["RedirectType"], @@ -66,7 +68,7 @@ local function isCookieValid(secretKey, cookieNameValueMap, eventId, cookieValid secretKey) if (hashValue ~= cookieNameValueMap["Hash"]) then - return false + return false end if (string.lower(eventId) ~= string.lower(cookieNameValueMap["EventId"])) then @@ -79,17 +81,17 @@ local function isCookieValid(secretKey, cookieNameValueMap, eventId, cookieValid validity = tonumber(fixedCookieValidityMinutes) end - local expirationTime = cookieNameValueMap["IssueTime"] + (validity*60) - if (expirationTime < os.time()) then + local expirationTime = cookieNameValueMap["IssueTime"] + (validity*60) + if (expirationTime < os.time()) then return false end - end + end return true end -- END Private functions -local repo = { +local repo = { StateInfo = { create = function(isFound, isValid, queueId, fixedCookieValidityMinutes, redirectType) local model = { @@ -102,12 +104,12 @@ local repo = { return self.isValid and self.fixedCookieValidityMinutes == nil end } - return model + return model end } } -repo.getCookieKey = function(eventId) +repo.getCookieKey = function(eventId) return "QueueITAccepted-SDFrts345E-V3_" .. eventId end @@ -123,7 +125,7 @@ repo.getState = function(eventId, cookieValidityMinutes, secretKey, validateTime return repo.StateInfo.create(false, false, nil, nil, nil) end local cookieNameValueMap = getCookieNameValueMap(iHelpers.request.getUnescapedCookieValue(cookieKey)) - + if (isCookieValid(secretKey, cookieNameValueMap, eventId, cookieValidityMinutes, validateTime) == false) then return repo.StateInfo.create(true, false, nil, nil, nil) end @@ -134,8 +136,8 @@ repo.getState = function(eventId, cookieValidityMinutes, secretKey, validateTime end return repo.StateInfo.create( - true, - true, + true, + true, cookieNameValueMap["QueueId"], fixedCookieValidityMinutes, cookieNameValueMap["RedirectType"] @@ -155,7 +157,7 @@ repo.reissueQueueCookie = function(eventId, cookieValidityMinutes, cookieDomain, return end local cookieNameValueMap = getCookieNameValueMap(iHelpers.request.getUnescapedCookieValue(cookieKey)) - + if (isCookieValid(secretKey, cookieNameValueMap, eventId, cookieValidityMinutes, true) == false) then return end @@ -165,10 +167,10 @@ repo.reissueQueueCookie = function(eventId, cookieValidityMinutes, cookieDomain, end local cookieValue = createCookieValue( - eventId, - cookieNameValueMap["QueueId"], - fixedCookieValidityMinutes, - cookieNameValueMap["RedirectType"], + eventId, + cookieNameValueMap["QueueId"], + fixedCookieValidityMinutes, + cookieNameValueMap["RedirectType"], secretKey) iHelpers.response.setCookie(cookieKey, cookieValue, os.time() + (24 * 60 * 60), cookieDomain) @@ -176,7 +178,8 @@ end repo.store = function(eventId, queueId, fixedCookieValidityMinutes, cookieDomain, redirectType, secretKey) local cookieKey = repo.getCookieKey(eventId) - local cookieValue = createCookieValue(eventId, queueId, utils.toString(fixedCookieValidityMinutes), redirectType, secretKey) + local cookieValue = createCookieValue( + eventId, queueId, utils.toString(fixedCookieValidityMinutes), redirectType, secretKey) iHelpers.response.setCookie(cookieKey, cookieValue, os.time() + (24 * 60 * 60), cookieDomain) end diff --git a/SDK/Utils.lua b/SDK/Utils.lua index 6bb00cb..a91a7af 100644 --- a/SDK/Utils.lua +++ b/SDK/Utils.lua @@ -1,10 +1,10 @@ -local utils = +local utils = { toString = function(v) - if (v == nil) then + if (v == nil) then return "" end - + local vType = type(v) if (vType == "string" or vType == "number") then @@ -36,7 +36,7 @@ local utils = return str end, explode = function(sep, inputstr) - local t = {} ; i = 1 + local t = {}; local i = 1; for str in string.gmatch(inputstr, "([^" .. sep .. "]+)") do t[i] = str i = i + 1 @@ -62,10 +62,10 @@ local utils = text = text:gsub("%[", "%%[") text = text:gsub("%]", "%%]") text = text:gsub("%^", "%%^") - text = text:gsub("%$", "%%$") + text = text:gsub("%$", "%%$") return text end, - contains = function(self, text, match) + contains = function(self, text, match) match = self.escapeMagicChars(match) return string.find(text, match) ~= nil end, diff --git a/SDK/ValidatorHelpers.lua b/SDK/ValidatorHelpers.lua index bb8c503..dd1a9d1 100644 --- a/SDK/ValidatorHelpers.lua +++ b/SDK/ValidatorHelpers.lua @@ -1,34 +1,33 @@ local utils = require("Utils") -local iHelpers = require("KnownUserImplementationHelpers") local comparisonOperatorHelper = require("ComparisonOperatorHelper") local model = { UrlValidatorHelper = { evaluate = function(triggerPart, url) -- Private functions - local function getUrlPart(urlPart, url) + local function getUrlPart(_urlPart, _url) -- Private functions - local function getHostNameFromUrl(url) - return utils.toString(url:match('^%w+://([^/]+)')) + local function getHostNameFromUrl(__url) + return utils.toString(__url:match('^%w+://([^/]+)')) end - - local function getPathFromUrl(url) - pathAndQuery = utils.toString(url:match('^%w+://[^/]+(.*)')) - query = utils.toString(url:match('%?+.*')) - path = pathAndQuery:gsub(utils.escapeMagicChars(query), "") - + + local function getPathFromUrl(__url) + local pathAndQuery = utils.toString(__url:match('^%w+://[^/]+(.*)')) + local query = utils.toString(__url:match('%?+.*')) + local path = pathAndQuery:gsub(utils.escapeMagicChars(query), "") + return path end -- END Private functions - if (urlPart == "PagePath") then - return getPathFromUrl(url) + if (_urlPart == "PagePath") then + return getPathFromUrl(_url) end - if (urlPart == "PageUrl") then - return url + if (_urlPart == "PageUrl") then + return _url end - if (urlPart == "HostName") then - return getHostNameFromUrl(url) + if (_urlPart == "HostName") then + return getHostNameFromUrl(_url) end return "" @@ -36,17 +35,17 @@ local model = { -- END Private functions if (triggerPart == nil or - triggerPart["Operator"] == nil or - triggerPart["IsNegative"] == nil or - triggerPart["IsIgnoreCase"] == nil or - triggerPart["UrlPart"] == nil) then + triggerPart["Operator"] == nil or + triggerPart["IsNegative"] == nil or + triggerPart["IsIgnoreCase"] == nil or + triggerPart["UrlPart"] == nil) then return false end return comparisonOperatorHelper.evaluate( - triggerPart["Operator"], - triggerPart["IsNegative"], - triggerPart["IsIgnoreCase"], + triggerPart["Operator"], + triggerPart["IsNegative"], + triggerPart["IsIgnoreCase"], getUrlPart(triggerPart["UrlPart"], url), triggerPart["ValueToCompare"], triggerPart["ValuesToCompare"]) @@ -55,10 +54,10 @@ local model = { CookieValidatorHelper = { evaluate = function(triggerPart, request) if (triggerPart == nil or - triggerPart["Operator"] == nil or - triggerPart["IsNegative"] == nil or - triggerPart["IsIgnoreCase"] == nil or - triggerPart["CookieName"] == nil) then + triggerPart["Operator"] == nil or + triggerPart["IsNegative"] == nil or + triggerPart["IsIgnoreCase"] == nil or + triggerPart["CookieName"] == nil) then return false end @@ -67,11 +66,11 @@ local model = { if (cookieName ~= nil and request.getUnescapedCookieValue(cookieName) ~= nil) then cookieValue = request.getUnescapedCookieValue(cookieName) end - + return comparisonOperatorHelper.evaluate( - triggerPart["Operator"], - triggerPart["IsNegative"], - triggerPart["IsIgnoreCase"], + triggerPart["Operator"], + triggerPart["IsNegative"], + triggerPart["IsIgnoreCase"], cookieValue, triggerPart["ValueToCompare"], triggerPart["ValuesToCompare"]) @@ -80,9 +79,9 @@ local model = { UserAgentValidatorHelper = { evaluate = function(triggerPart, request) if (triggerPart == nil or - triggerPart["Operator"] == nil or - triggerPart["IsNegative"] == nil or - triggerPart["IsIgnoreCase"] == nil) then + triggerPart["Operator"] == nil or + triggerPart["IsNegative"] == nil or + triggerPart["IsIgnoreCase"] == nil) then return false end @@ -92,9 +91,9 @@ local model = { end return comparisonOperatorHelper.evaluate( - triggerPart["Operator"], - triggerPart["IsNegative"], - triggerPart["IsIgnoreCase"], + triggerPart["Operator"], + triggerPart["IsNegative"], + triggerPart["IsIgnoreCase"], headerValue, triggerPart["ValueToCompare"], triggerPart["ValuesToCompare"]) @@ -103,10 +102,10 @@ local model = { HttpHeaderValidatorHelper = { evaluate = function(triggerPart, request) if (triggerPart == nil or - triggerPart["Operator"] == nil or - triggerPart["IsNegative"] == nil or - triggerPart["IsIgnoreCase"] == nil or - triggerPart["HttpHeaderName"] == nil) then + triggerPart["Operator"] == nil or + triggerPart["IsNegative"] == nil or + triggerPart["IsIgnoreCase"] == nil or + triggerPart["HttpHeaderName"] == nil) then return false end @@ -117,9 +116,9 @@ local model = { end return comparisonOperatorHelper.evaluate( - triggerPart["Operator"], - triggerPart["IsNegative"], - triggerPart["IsIgnoreCase"], + triggerPart["Operator"], + triggerPart["IsNegative"], + triggerPart["IsIgnoreCase"], headerValue, triggerPart["ValueToCompare"], triggerPart["ValuesToCompare"])