From e82e3fb18ce5e642911f84a0ab2e1e0c12e851a2 Mon Sep 17 00:00:00 2001 From: Kijin Sung Date: Mon, 6 Mar 2017 15:11:45 +0900 Subject: [PATCH] Implement isSameOrigin() to simplify origin determination --- common/js/common.js | 19 ++++++++++++++++--- common/js/xml_handler.js | 4 +--- 2 files changed, 17 insertions(+), 6 deletions(-) diff --git a/common/js/common.js b/common/js/common.js index 52828761f..f898a409c 100644 --- a/common/js/common.js +++ b/common/js/common.js @@ -20,9 +20,7 @@ /* Intercept jQuery AJAX calls to add CSRF headers */ $.ajaxPrefilter(function(options) { - var _u1 = $("").attr("href", location.href)[0]; - var _u2 = $("").attr("href", options.url)[0]; - if (_u2.hostname && (_u1.hostname !== _u2.hostname)) return; + if (!isSameOrigin(location.href, options.url, true)) return; var token = getCSRFToken(); if (token) { if (!options.headers) options.headers = {}; @@ -453,6 +451,21 @@ function move_url(url, open_window) { return false; } +/** + * @brief Check if two URLs belong to the same origin + */ +function isSameOrigin(url1, url2, allow_relative_url2) { + var a1 = $("").attr("href", url1)[0]; + var a2 = $("").attr("href", url2)[0]; + if (!a2.hostname && allow_relative_url2) { + return true; + } + if (a1.protocol !== a2.protocol) return false; + if (a1.hostname !== a2.hostname) return false; + if (a1.port !== a2.port) return false; + return true; +} + /** * @brief Get CSRF token for the document */ diff --git a/common/js/xml_handler.js b/common/js/xml_handler.js index 75e8642a0..370aac865 100644 --- a/common/js/xml_handler.js +++ b/common/js/xml_handler.js @@ -47,9 +47,7 @@ } // Check whether this is a cross-domain request. If so, use an alternative method. - var _u1 = $("").attr("href", location.href)[0]; - var _u2 = $("").attr("href", url)[0]; - if (_u1.protocol != _u2.protocol || _u1.port != _u2.port) return send_by_form(url, params); + if (!isSameOrigin(location.href, url)) return send_by_form(url, params); // Delay the waiting message for 1 second to prevent rapid blinking. waiting_obj.css("opacity", 0.0);