Implement isSameOrigin() to simplify origin determination

This commit is contained in:
Kijin Sung 2017-03-06 15:11:45 +09:00
parent 14300cbcc3
commit e82e3fb18c
2 changed files with 17 additions and 6 deletions

View file

@ -20,9 +20,7 @@
/* Intercept jQuery AJAX calls to add CSRF headers */
$.ajaxPrefilter(function(options) {
var _u1 = $("<a>").attr("href", location.href)[0];
var _u2 = $("<a>").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 = $("<a>").attr("href", url1)[0];
var a2 = $("<a>").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
*/

View file

@ -47,9 +47,7 @@
}
// Check whether this is a cross-domain request. If so, use an alternative method.
var _u1 = $("<a>").attr("href", location.href)[0];
var _u2 = $("<a>").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);