Opened 12 years ago

Last modified 12 years ago

#18826 closed Cleanup/optimization

A bit changed JavaScript for CSRF with async JS — at Initial Version

Reported by: panco Owned by: nobody
Component: Documentation Version: 1.4
Severity: Normal Keywords: ajax, csrf
Cc: lrekucki@… Triage Stage: Design decision needed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

Recently I've found use for the code found at https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax
and as I can't sleep well if my JS doesn't pass some of the basic JSlint standards I've changed the snippet a bit:

jQuery(document).ajaxSend(function (event, xhr, settings) {
	function getCookie(name) {
		var cookieValue = null, cookies = [], i = 0, j = 0, cookie = {};
		if (document.cookie && document.cookie !== '') {
			cookies = document.cookie.split(';');
			for (j = cookies.length; i < j; i += 1) {
				cookie = jQuery.trim(cookies[i]);
				// Does this cookie string begin with the name we want?
				if (cookie.substring(0, name.length + 1) === (name + '=')) {
					cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
					break;
				}
			}
		}
		return cookieValue;
	}

	function sameOrigin(url) {
		// url could be relative or scheme relative or absolute
		var host = document.location.host, // host + port
			protocol = document.location.protocol,
			sr_origin = '//' + host,
			origin = protocol + sr_origin;
		// Allow absolute or scheme relative URLs to same origin
		return (url === origin || url.slice(0, origin.length + 1) === origin + '/') || (url === sr_origin || url.slice(0, sr_origin.length + 1) === sr_origin + '/') || // or any other URL that isn't scheme relative or absolute i.e relative.
			!(/^(\/\/|http:|https:).*/.test(url));
	}

	function safeMethod(method) {
		return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
	}

	if (!safeMethod(settings.type) && sameOrigin(settings.url)) {
		xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
	}
});
  • "===" instead of "=="
  • all vars at the beginning of the function (and all the changes that brings forth)

I realize these changes are very small, but I think since this is a simple copy/paste snippet it should be of the highest quality possible (there's room for improvement still).
I'm using it and it performs as intended.

Change History (0)

Note: See TracTickets for help on using tickets.
Back to Top