def __getQueueITTokenValidationResult(self, targetUrl, eventId, config, queueParams, customerId, secretKey): calculatedHash = QueueitHelpers.hmacSha256Encode( queueParams.queueITTokenWithoutHash, secretKey) if (calculatedHash.upper() != queueParams.hashCode.upper()): return self.__getVaidationErrorResult(customerId, targetUrl, config, queueParams, "hash") if (queueParams.eventId.upper() != eventId.upper()): return self.__getVaidationErrorResult( customerId, targetUrl, config, queueParams, "eventid") if (queueParams.timeStamp < QueueitHelpers.getCurrentTime()): return self.__getVaidationErrorResult( customerId, targetUrl, config, queueParams, "timestamp") cookieDomain = "" if (not Utils.isNilOrEmpty(config.cookieDomain)): cookieDomain = config.cookieDomain self.userInQueueStateRepository.store( config.eventId, queueParams.queueId, queueParams.cookieValidityMinutes, cookieDomain, queueParams.redirectType, secretKey) return RequestValidationResult(ActionTypes.QUEUE, config.eventId, queueParams.queueId, None, queueParams.redirectType)
def verify(customer_id, secret_key, queueit_token): diagnostics = ConnectorDiagnostics() q_params = QueueUrlParams.extractQueueParams(queueit_token) if q_params is None: return diagnostics if q_params.redirectType is None: return diagnostics if q_params.redirectType != "debug": return diagnostics if Utils.isNilOrEmpty(customer_id) or Utils.isNilOrEmpty(secret_key): diagnostics.__setStateWithSetupError() return diagnostics expected_hash = QueueitHelpers.hmacSha256Encode( q_params.queueITTokenWithoutHash, secret_key) if q_params.hashCode != expected_hash: diagnostics.__setStateWithTokenError(customer_id, "hash") return diagnostics if q_params.timeStamp < QueueitHelpers.getCurrentTime(): diagnostics.__setStateWithTokenError(customer_id, "timestamp") return diagnostics diagnostics.isEnabled = True return diagnostics
def __validateToken(self, config, queue_params, secret_key): calculated_hash = QueueitHelpers.hmacSha256Encode( queue_params.queueITTokenWithoutHash, secret_key) if calculated_hash.upper() != queue_params.hashCode.upper(): return TokenValidationResult(False, "hash") if queue_params.eventId.upper() != config.eventId.upper(): return TokenValidationResult(False, "eventid") if queue_params.timeStamp < QueueitHelpers.getCurrentTime(): return TokenValidationResult(False, "timestamp") return TokenValidationResult(True, None)
def reissueQueueCookie(self, eventId, cookieValidityMinutes, cookieDomain, secretKey): cookieKey = UserInQueueStateCookieRepository.getCookieKey(eventId) cookieValue = self.httpContextProvider.getCookie(cookieKey) if (cookieValue == None): return cookieNameValueMap = UserInQueueStateCookieRepository.__getCookieNameValueMap( cookieValue) if (not UserInQueueStateCookieRepository.__isCookieValid( secretKey, cookieNameValueMap, eventId, cookieValidityMinutes, True)): return fixedCookieValidityMinutes = "" if ("FixedValidityMins" in cookieNameValueMap): fixedCookieValidityMinutes = cookieNameValueMap[ "FixedValidityMins"] cookieValue = UserInQueueStateCookieRepository.__createCookieValue( eventId, cookieNameValueMap["QueueId"], fixedCookieValidityMinutes, cookieNameValueMap["RedirectType"], secretKey) self.httpContextProvider.setCookie( cookieKey, cookieValue, QueueitHelpers.getCookieExpirationDate(), cookieDomain)
def validateCancelRequest(self, targetUrl, cancelConfig, customerId, secretKey): state = self.userInQueueStateRepository.getState( cancelConfig.eventId, -1, secretKey, False) if (state.isValid): self.userInQueueStateRepository.cancelQueueCookie( cancelConfig.eventId, cancelConfig.cookieDomain) targetUrlParam = "" if (not Utils.isNilOrEmpty(targetUrl)): targetUrlParam = "&r=" + QueueitHelpers.urlEncode( targetUrl) query = self.__getQueryString(customerId, cancelConfig.eventId, cancelConfig.version, None, None) + targetUrlParam domainAlias = cancelConfig.queueDomain if (not domainAlias.endswith("/")): domainAlias = domainAlias + "/" redirectUrl = "https://" + domainAlias + "cancel/" + customerId + "/" + cancelConfig.eventId + "/?" + query return RequestValidationResult(ActionTypes.CANCEL, cancelConfig.eventId, state.queueId, redirectUrl, state.redirectType) else: return RequestValidationResult( ActionTypes.CANCEL, cancelConfig.eventId, None, None, None)
def reissueQueueCookie(self, event_id, cookie_validity_minutes, cookie_domain, is_cookie_http_only, is_cookie_secure, secret_key): cookie_key = UserInQueueStateCookieRepository.getCookieKey(event_id) cookie_value = self.httpContextProvider.getCookie(cookie_key) if cookie_value is None: return cookie_name_value_map = UserInQueueStateCookieRepository.__getCookieNameValueMap(cookie_value) if (not UserInQueueStateCookieRepository.__isCookieValid( secret_key, cookie_name_value_map, event_id, cookie_validity_minutes, True)): return fixed_cookie_validity_minutes = "" if "FixedValidityMins" in cookie_name_value_map: fixed_cookie_validity_minutes = cookie_name_value_map[ "FixedValidityMins"] cookie_value = UserInQueueStateCookieRepository.__createCookieValue( event_id, cookie_name_value_map["QueueId"], fixed_cookie_validity_minutes, cookie_name_value_map["RedirectType"], secret_key) self.httpContextProvider.setCookie( cookie_key, cookie_value, QueueitHelpers.getCookieExpirationDate(), cookie_domain, is_cookie_http_only, is_cookie_secure)
def store(self, eventId, queueId, fixedCookieValidityMinutes, cookieDomain, redirectType, secretKey): cookieKey = UserInQueueStateCookieRepository.getCookieKey(eventId) cookieValue = UserInQueueStateCookieRepository.__createCookieValue( eventId, queueId, Utils.toString(fixedCookieValidityMinutes), redirectType, secretKey) self.httpContextProvider.setCookie( cookieKey, cookieValue, QueueitHelpers.getCookieExpirationDate(), cookieDomain)
def __resolveQueueRequestByLocalConfig(target_url, queueit_token, queue_config, customer_id, secret_key, http_context_provider, debug_entries, is_debug): if is_debug: debug_entries["SdkVersion"] = UserInQueueService.SDK_VERSION debug_entries["Connector"] = http_context_provider.getProviderName( ) debug_entries["Runtime"] = KnownUser.__getRunTime() debug_entries["TargetUrl"] = target_url debug_entries["QueueitToken"] = queueit_token debug_entries[ "OriginalUrl"] = http_context_provider.getOriginalRequestUrl() if queue_config is None: debug_entries["QueueConfig"] = "NULL" else: debug_entries["QueueConfig"] = queue_config.toString() KnownUser.__logMoreRequestDetails(debug_entries, http_context_provider) if Utils.isNilOrEmpty(customer_id): raise KnownUserError("customerId can not be none or empty.") if Utils.isNilOrEmpty(secret_key): raise KnownUserError("secretKey can not be none or empty.") if queue_config is None: raise KnownUserError("queueConfig can not be none.") if Utils.isNilOrEmpty(queue_config.eventId): raise KnownUserError( "queueConfig.eventId can not be none or empty.") if Utils.isNilOrEmpty(queue_config.queueDomain): raise KnownUserError( "queueConfig.queueDomain can not be none or empty.") minutes = QueueitHelpers.convertToInt( queue_config.cookieValidityMinute) if minutes <= 0: raise KnownUserError( "queueConfig.cookieValidityMinute should be integer greater than 0." ) if not isinstance(queue_config.extendCookieValidity, bool): raise KnownUserError( "queueConfig.extendCookieValidity should be valid boolean.") user_in_queue_service = KnownUser.__getUserInQueueService( http_context_provider) result = user_in_queue_service.validateQueueRequest( target_url, queueit_token, queue_config, customer_id, secret_key) result.isAjaxResult = KnownUser.__isQueueAjaxCall( http_context_provider) return result
def __getErrorResult(self, customer_id, target_url, config, q_params, error_code): time_stamp = str(QueueitHelpers.getCurrentTime()) target_url_param = "" if not Utils.isNilOrEmpty(target_url): target_url_param = "&t={}".format( QueueitHelpers.urlEncode(target_url)) query_string = self.__getQueryString(customer_id, config.eventId, config.version, config.actionName, config.culture, config.layoutName) query = "{}&queueittoken={}&ts={}{}".format(query_string, q_params.queueITToken, time_stamp, target_url_param) redirect_url = self.__generateRedirectUrl( config.queueDomain, "error/{}/".format(error_code), query) return RequestValidationResult(ActionTypes.QUEUE, config.eventId, None, redirect_url, None, config.actionName)
def __getVaidationErrorResult(self, customerId, targetUrl, config, qParams, errorCode): targetUrlParam = "" if (not Utils.isNilOrEmpty(targetUrl)): targetUrlParam = "&t=" + QueueitHelpers.urlEncode( targetUrl) query = self.__getQueryString( customerId, config.eventId, config.version, config.culture, config.layoutName ) + "&queueittoken=" + qParams.queueITToken + "&ts=" + str( QueueitHelpers.getCurrentTime()) + targetUrlParam domainAlias = config.queueDomain if (not domainAlias.endswith("/")): domainAlias = domainAlias + "/" redirectUrl = "https://" + domainAlias + "error/" + errorCode + "/?" + query return RequestValidationResult(ActionTypes.QUEUE, config.eventId, None, redirectUrl, None)
def getUrlPart(url_part, url): try: uri = QueueitHelpers.urlParse(url) if url_part == "PagePath": return uri.path elif url_part == "PageUrl": return url elif url_part == "HostName": return uri.hostname return '' except: return ''
def __createCookieValue(eventId, queueId, fixedCookieValidityMinutes, redirectType, secretKey): issueTime = Utils.toString(QueueitHelpers.getCurrentTime()) hashValue = UserInQueueStateCookieRepository.__generateHash( eventId, queueId, fixedCookieValidityMinutes, redirectType, issueTime, secretKey) fixedCookieValidityMinutesPart = "" if (not Utils.isNilOrEmpty(fixedCookieValidityMinutes)): fixedCookieValidityMinutesPart = "&FixedValidityMins=" + fixedCookieValidityMinutes cookieValue = "EventId=" + eventId + "&QueueId=" + queueId + fixedCookieValidityMinutesPart + "&RedirectType=" + redirectType + "&IssueTime=" + issueTime + "&Hash=" + hashValue return cookieValue
def store(self, event_id, queue_id, fixed_cookie_validity_minutes, cookie_domain, is_cookie_http_only, is_cookie_secure, redirect_type, secret_key): cookie_key = UserInQueueStateCookieRepository.getCookieKey(event_id) cookie_value = UserInQueueStateCookieRepository.__createCookieValue( event_id, queue_id, Utils.toString(fixed_cookie_validity_minutes), redirect_type, secret_key) self.httpContextProvider.setCookie( cookie_key, cookie_value, QueueitHelpers.getCookieExpirationDate(), cookie_domain, is_cookie_http_only, is_cookie_secure)
def __getQueueResult(self, target_url, config, customer_id): target_url_param = "" if not Utils.isNilOrEmpty(target_url): target_url_param = "&t={}".format( QueueitHelpers.urlEncode(target_url)) query_string = self.__getQueryString(customer_id, config.eventId, config.version, config.actionName, config.culture, config.layoutName) query = "{}{}".format(query_string, target_url_param) redirect_url = self.__generateRedirectUrl(config.queueDomain, "", query) return RequestValidationResult(ActionTypes.QUEUE, config.eventId, None, redirect_url, None, config.actionName)
def __resolveQueueRequestByLocalConfig(targetUrl, queueitToken, queueConfig, customerId, secretKey, httpContextProvider, debugEntries): isDebug = KnownUser.__getIsDebug(queueitToken, secretKey) if (isDebug): debugEntries["TargetUrl"] = targetUrl debugEntries["QueueitToken"] = queueitToken debugEntries[ "OriginalUrl"] = httpContextProvider.getOriginalRequestUrl() if (queueConfig == None): debugEntries["QueueConfig"] = "NULL" else: debugEntries["QueueConfig"] = queueConfig.toString() KnownUser.__logMoreRequestDetails(debugEntries, httpContextProvider) if (Utils.isNilOrEmpty(customerId)): raise KnownUserError("customerId can not be none or empty.") if (Utils.isNilOrEmpty(secretKey)): raise KnownUserError("secretKey can not be none or empty.") if (queueConfig == None): raise KnownUserError("queueConfig can not be none.") if (Utils.isNilOrEmpty(queueConfig.eventId)): raise KnownUserError( "queueConfig.eventId can not be none or empty.") if (Utils.isNilOrEmpty(queueConfig.queueDomain)): raise KnownUserError( "queueConfig.queueDomain can not be none or empty.") minutes = QueueitHelpers.convertToInt(queueConfig.cookieValidityMinute) if (minutes <= 0): raise KnownUserError( "queueConfig.cookieValidityMinute should be integer greater than 0." ) if (queueConfig.extendCookieValidity != True and queueConfig.extendCookieValidity != False): raise KnownUserError( "queueConfig.extendCookieValidity should be valid boolean.") userInQueueService = KnownUser.__getUserInQueueService( httpContextProvider) result = userInQueueService.validateQueueRequest( targetUrl, queueitToken, queueConfig, customerId, secretKey) result.isAjaxResult = KnownUser.__isQueueAjaxCall(httpContextProvider) return result
def setCookie(self, name, value, expire, domain): if (str(domain) == ""): domain = None if (value is not None): value = QueueitHelpers.urlEncode(value) self.response.set_cookie(name, value, max_age=None, expires=expire, path='/', domain=domain, secure=None, httponly=False)
def setCookie(self, name, value, expire, domain, is_http_only, is_secure): if str(domain) == "": domain = None if value is not None: value = QueueitHelpers.urlEncode(value) self.response.set_cookie(name, value, max_age=None, expires=expire, path='/', domain=domain, secure=is_secure, httponly=is_http_only)
def __getQueryString(self, customerId, eventId, configVersion, culture, layoutName): queryStringList = [] queryStringList.append( "c=" + QueueitHelpers.urlEncode(customerId)) queryStringList.append( "e=" + QueueitHelpers.urlEncode(eventId)) queryStringList.append("ver=v3-py_" + self.httpContextProvider.getProviderName() + "-" + self.SDK_VERSION) if (configVersion is None): configVersion = "-1" queryStringList.append("cver=" + str(configVersion)) if (not Utils.isNilOrEmpty(culture)): queryStringList.append( "cid=" + QueueitHelpers.urlEncode(culture)) if (not Utils.isNilOrEmpty(layoutName)): queryStringList.append( "l=" + QueueitHelpers.urlEncode(layoutName)) return "&".join(queryStringList)
def __getInQueueRedirectResult(self, targetUrl, config, customerId): targetUrlParam = "" if (not Utils.isNilOrEmpty(targetUrl)): targetUrlParam = "&t=" + QueueitHelpers.urlEncode( targetUrl) domainAlias = config.queueDomain if (not domainAlias.endswith("/")): domainAlias = domainAlias + "/" qs = self.__getQueryString(customerId, config.eventId, config.version, config.culture, config.layoutName) redirectUrl = "https://" + domainAlias + "?" + qs + targetUrlParam return RequestValidationResult(ActionTypes.QUEUE, config.eventId, None, redirectUrl, None)
def __getIsDebug(queueitToken, secretKey): qParams = QueueUrlParams.extractQueueParams(queueitToken) if (qParams == None): return False redirectType = qParams.redirectType if (redirectType == None): return False if (redirectType.upper() == "DEBUG"): calculatedHash = QueueitHelpers.hmacSha256Encode( qParams.queueITTokenWithoutHash, secretKey) valid = qParams.hashCode == calculatedHash return valid return False
def __isCookieValid(secretKey, cookieNameValueMap, eventId, cookieValidityMinutes, validateTime): try: if ("EventId" not in cookieNameValueMap): return False if ("QueueId" not in cookieNameValueMap): return False if ("RedirectType" not in cookieNameValueMap): return False if ("IssueTime" not in cookieNameValueMap): return False if ("Hash" not in cookieNameValueMap): return False fixedCookieValidityMinutes = "" if ("FixedValidityMins" in cookieNameValueMap): fixedCookieValidityMinutes = cookieNameValueMap[ "FixedValidityMins"] hashValue = UserInQueueStateCookieRepository.__generateHash( cookieNameValueMap["EventId"], cookieNameValueMap["QueueId"], fixedCookieValidityMinutes, cookieNameValueMap["RedirectType"], cookieNameValueMap["IssueTime"], secretKey) if (hashValue != cookieNameValueMap["Hash"]): return False if (eventId.upper() != cookieNameValueMap["EventId"].upper()): return False if (validateTime): validity = cookieValidityMinutes if (not Utils.isNilOrEmpty(fixedCookieValidityMinutes)): validity = int(fixedCookieValidityMinutes) expirationTime = int( cookieNameValueMap["IssueTime"]) + (validity * 60) if (expirationTime < QueueitHelpers.getCurrentTime()): return False return True except: return False
def extendQueueCookie(eventId, cookieValidityMinute, cookieDomain, secretKey, httpContextProvider): if (Utils.isNilOrEmpty(eventId)): raise KnownUserError("eventId can not be none or empty.") if (Utils.isNilOrEmpty(secretKey)): raise KnownUserError("secretKey can not be none or empty.") minutes = QueueitHelpers.convertToInt(cookieValidityMinute) if (minutes <= 0): raise KnownUserError( "cookieValidityMinute should be integer greater than 0.") userInQueueService = KnownUser.__getUserInQueueService( httpContextProvider) userInQueueService.extendQueueCookie(eventId, cookieValidityMinute, cookieDomain, secretKey)
def __isCookieValid(secret_key, cookie_name_value_map, event_id, cookie_validity_minutes, validate_time): try: if "EventId" not in cookie_name_value_map: return False if "QueueId" not in cookie_name_value_map: return False if "RedirectType" not in cookie_name_value_map: return False if "IssueTime" not in cookie_name_value_map: return False if "Hash" not in cookie_name_value_map: return False fixed_cookie_validity_minutes = "" if "FixedValidityMins" in cookie_name_value_map: fixed_cookie_validity_minutes = cookie_name_value_map["FixedValidityMins"] hash_value = UserInQueueStateCookieRepository.__generateHash( cookie_name_value_map["EventId"], cookie_name_value_map["QueueId"], fixed_cookie_validity_minutes, cookie_name_value_map["RedirectType"], cookie_name_value_map["IssueTime"], secret_key) if hash_value != cookie_name_value_map["Hash"]: return False if event_id.upper() != cookie_name_value_map["EventId"].upper(): return False if validate_time: validity = cookie_validity_minutes if not Utils.isNilOrEmpty(fixed_cookie_validity_minutes): validity = int(fixed_cookie_validity_minutes) expiration_time = int(cookie_name_value_map["IssueTime"]) + (validity * 60) if expiration_time < QueueitHelpers.getCurrentTime(): return False return True except: return False
def __logMoreRequestDetails(debug_entries, http_context_provider): debug_entries[ "ServerUtcTime"] = QueueitHelpers.getCurrentTimeAsIso8601Str() debug_entries["RequestIP"] = http_context_provider.getRequestIp() debug_entries[ "RequestHttpHeader_Via"] = http_context_provider.getHeader("via") debug_entries[ "RequestHttpHeader_Forwarded"] = http_context_provider.getHeader( "forwarded") debug_entries[ "RequestHttpHeader_XForwardedFor"] = http_context_provider.getHeader( "x-forwarded-for") debug_entries[ "RequestHttpHeader_XForwardedHost"] = http_context_provider.getHeader( "x-forwarded-host") debug_entries[ "RequestHttpHeader_XForwardedProto"] = http_context_provider.getHeader( "x-forwarded-proto")
def validateCancelRequest(self, target_url, cancel_config, customer_id, secret_key): state = self.userInQueueStateRepository.getState( cancel_config.eventId, -1, secret_key, False) if state.isValid: self.userInQueueStateRepository.cancelQueueCookie( cancel_config.eventId, cancel_config.cookieDomain, cancel_config.isCookieHttpOnly, cancel_config.isCookieSecure) target_url_param = "" if not Utils.isNilOrEmpty(target_url): target_url_param = "&r={}".format( QueueitHelpers.urlEncode(target_url)) query_string = self.__getQueryString(customer_id, cancel_config.eventId, cancel_config.version, cancel_config.actionName, None, None) query = "{}{}".format(query_string, target_url_param) uri_path = "cancel/{}/{}".format(customer_id, cancel_config.eventId) if state.queueId: uri_path = "{}/{}".format(uri_path, state.queueId) redirect_url = self.__generateRedirectUrl( cancel_config.queueDomain, uri_path, query) return RequestValidationResult(ActionTypes.CANCEL, cancel_config.eventId, state.queueId, redirect_url, state.redirectType, cancel_config.actionName) else: return RequestValidationResult(ActionTypes.CANCEL, cancel_config.eventId, None, None, None, cancel_config.actionName)
def extendQueueCookie(event_id, cookie_validity_minute, cookie_domain, is_cookie_http_only, is_cookie_secure, secret_key, http_context_provider): if Utils.isNilOrEmpty(event_id): raise KnownUserError("eventId can not be none or empty.") if Utils.isNilOrEmpty(secret_key): raise KnownUserError("secretKey can not be none or empty.") minutes = QueueitHelpers.convertToInt(cookie_validity_minute) if minutes <= 0: raise KnownUserError( "cookieValidityMinute should be integer greater than 0.") user_in_queue_service = KnownUser.__getUserInQueueService( http_context_provider) user_in_queue_service.extendQueueCookie(event_id, cookie_validity_minute, cookie_domain, is_cookie_http_only, is_cookie_secure, secret_key)
def __getQueryString(self, customer_id, event_id, config_version, action_name, culture, layout_name): query_string_list = [ "c=" + QueueitHelpers.urlEncode(customer_id), "e=" + QueueitHelpers.urlEncode(event_id), "ver=" + self.SDK_VERSION, "kupver=" + QueueitHelpers.urlEncode( self.httpContextProvider.getProviderName()) ] if config_version is None: config_version = "-1" query_string_list.append("cver=" + str(config_version)) query_string_list.append("man=" + QueueitHelpers.urlEncode(action_name)) if not Utils.isNilOrEmpty(culture): query_string_list.append("cid=" + QueueitHelpers.urlEncode(culture)) if not Utils.isNilOrEmpty(layout_name): query_string_list.append("l=" + QueueitHelpers.urlEncode(layout_name)) return "&".join(query_string_list)
def getAjaxRedirectUrl(self): if (not Utils.isNilOrEmpty(self.redirectUrl)): return QueueitHelpers.urlEncode(self.redirectUrl) return ""
def __generateHash(event_id, queue_id, fixed_cookie_validity_minutes, redirect_type, issue_time, secret_key): return QueueitHelpers.hmacSha256Encode( event_id + queue_id + fixed_cookie_validity_minutes + redirect_type + issue_time, secret_key)
def getCookie(self, name): value = self.request.COOKIES.get(name) if value is not None: value = QueueitHelpers.urlDecode(value) return value