Delete function picks up CSRF value as path
Sorry for the massive code but I figured just put everything related out there. The fix might be easy.
I'm using a filemanager app django-fileman and I'm trying to get it work. So the problems are the move to basket and delete functions. But I will show the delete function here because they probably have the same problem and are very similar functions. In the app you can choose a set of files and then click delete and it should delete all the selected files.
I copy pasted the code from django csrf documentation into my script.js document ready section. It got my copy/cut function working but not the delete. Still picks up the csrf value as path.
Question: Why does it pick up the csrf value still? How can I fix this in the easiest way?
(Using Django 1.3, but still have csrfResponseMMiddleware
in use if it is of issue)
I have the app working fully. But I have to add csrf_exempt
to the functions as well as the function that lists the files. Like so:
views.py
@permission_required('fileman.can_fm_list')
@rightPath(True)
@csrf_exempt
def ls(request, path=None):
""" Render file list """
path = toString(path)
dirlist = []
filelist = []
for f in os.listdir(path):
f = toString(f)
file = File(f, "%s/%s" % (path, f))
if os.path.isdir(os.path.join(path, f)):
file.isdir = 1
file.size = "Dir"
dirlist.append(file)
else:
file.isdir = 0
file.size = os.path.getsize(os.path.join(path, f))
filelist.append(file)
dirlist.sort()
filelist.sort()
buffer = listBuffer(request)
for item in buffer:
item.append(os.path.basename(item[0]))
anonymous = False
return render_to_response('list.html',
{"pwd": path,
"dirlist": dirlist,
"filelist": filelist,
"buffer": buffer,
"anonymous": anonymous,
"availableSpace": availableSpace(path),
"forbiddenFolder": os.path.basename(path),
},
context_instance=RequestContext(request))
Deletes a set of chosen files or folders.
@permission_required('fileman.can_fm_destruct')
@csrf_exempt
def destraction2(request):
if request.POST:
if request.GET.has_key('next'):
next = request.GET['next']
else:
next = ''
for key in request.POST.keys():
try:
fmoper.remove(request.POST[key])
except Exception, msg:
return raise_error(request, [str(msg)])
if request.is_ajax():
return json({"status": "success"})
return HttpResponseRedirect('/fm/list/%s' % next)
else:
return raise_error(request,
[_(u"Empty form.")])
fmoper.remove
def remove(path):
if os.path.isdir(path):
return shutil.rmtree(path)
else:
return os.remove(path)
script.js
script.js (Code related to a delete function of files or folders)
function destButton(element, path){
element.html('<a href="#" ' +
'onclick="return dest_one(this, \''+nameFromPath(path)+'\', ' +
'\''+path+'\');" title="'+gettext("Destroy")+'">' +
'<img src="'+url_media+'/deletered.png"WIDTH=18 HEIGHT=18 alt="'+gettext("Destroy")+'"> </a>');
return 0;
}
...
function dest(){
if(confirm(gettext("Huomio! Operaatiota ei voi peruuttaa! \nOletko varma että haluat poistaa pysyvästi valitut?"))){
$("#fileListForm").attr("action", url_destraction+"?next="+pwd);
$("#fileListFo开发者_StackOverflow中文版rm").submit();
}
return 0;
}
...
function onSuccessRemove(data){
if(data.status=="success"){
currentE.fadeOut("slow", function(){
currentE.remove();
});
}
else {
alert(gettext("Error.\nServer reports:\n")+data.msg);
}
return 0;
}
...
# The document ready
// Ready!
$(document).ready(function(){
$("#filelist > tbody > tr:nth-child(odd)").addClass("odd");
$("#filelist > tbody > tr > td > .dir").each(function(){
$(this).dblclick(function(){
window.location=url_home+pwd+"/"+$(this).text();
});
});
$("#filelist > tbody > tr > td > .file").each(function(){
$(this).dblclick(function(){
window.location=url_view+pwd+"/"+$(this).text();
});
});
$('.block > h2').each(function(){ $(this).click(function(){
$('.block > .content').hide();
$(this).parent().children(".content").toggle();
}); });
$("#filelist > tbody > tr > td > .file").each(function(){
$(this).attr("onclick", 'fileClick($(this).text())');
});
$("#download").hide();
$("#clipboard").hide();
$.clipboardReady(function(){}, { swfpath: url_media+"/jquery.clipboard.swf" });
// Copied from django documentation
$(document).ajaxSend(function(event, xhr, settings) {
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var 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
var protocol = document.location.protocol;
var sr_origin = '//' + host;
var 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'));
}
});
});
Perhaps unsurprisingly the following code is processing the csrf token cookie:
if (!safeMethod(settings.type) && sameOrigin(settings.url)) {
xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
}
});
Try using your own cookie name, and if you need a request header, use your own name for that too.
精彩评论