Django Posts Not Working: - ajax

I am using Django 1.2.3 to develop a site. My ajax get requests work fine but the post requests work in development mode (127.0.0.1:8000) but not when I push the site into production using apache + nginx.
Here is an example
urls.py:
(r'api/newdoc/$', 'mysite.documents.views.newdoc'),
views.py
def newdoc(request):
# only process POST request
if request.is_ajax():
data= dict(request.POST)
# save data to db
return HttpResponse(simplejson.dumps([True]))
in javascript:
$.post("/api/newdoc/", {data : mydata}, function(data) { alert(data);}, "json");
my alert is never called .... this is a problem because i want to sanitize this data via a django form and the post requests do not seem to making it to the server (in production only).
what am i doing wrong?
UPDATES:
solution: crsf tokens need to be pushed ajax post requests (not gets) as of django 1.3
also, per the link provide below, the following javascript
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
// Only send the token to relative URLs i.e. locally.
xhr.setRequestHeader("X-CSRFToken",
$("#csrfmiddlewaretoken").val());
}
}
});
needs to be changed as follows:
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
// Only send the token to relative URLs i.e. locally.
xhr.setRequestHeader("X-CSRFToken",
$('input[name="csrfmiddlewaretoken"]').val());
}
}
});
the way the csrf token gets rendered in the form must have changed between 1.25 - 1.3??
regardless, it works. thanks for all your help everyone

Can you directly access your javascript files from the production server? Which Django version are you using in production? If you are using 1.2.5+ in production, you will need to push the csrf token to the server during an AJAX post operation.
See the release notes in 1.2.5 and CSRF
To check your Django version:
import django
django.get_version()
Print the above in your production site or from the shell in your production server while making sure you are using the proper Python path.

Your code appears fine with a cursory glance, but I'll show you an example of my ajax form processing code in a hope it'll help with figuring out the error that's occurring. Though, what #dmitry commented should be your first debugging step - use firebug or the inspector to see if the ajax call returns an error.
// js (jQuery 1.5)
$(form).submit(function(event) {
event.preventDefault();
$.post(post_url, $(form).serialize())
.success(function(data, status, jqxhr) {
if (data.success) { // form was valid
$(form)
// other irrelevant code
.siblings('span')
.removeClass('error')
.html('Form Successful');
} else { // form was invalid
$(form).siblings('span').addClass('error').html('Error Occurred');
}
})
.error(function(jqxhr, status, error) { // server error
$(form).siblings('span').addClass('error').html("Error: " + error);
});
});
// django
class AjaxFormView(FormView):
def ajax_response(self, context, success=True):
html = render_to_string(self.template_name, context)
response = simplejson.dumps({'success': success, 'html': html})
return HttpResponse(response, content_type="application/json", mimetype='application/json')
// view deriving from AjaxFormView
def form_valid(self, form):
registration = form.save()
if self.request.is_ajax():
context = {'competition': registration.competition }
return self.ajax_response(context, success=True)
return HttpResponseRedirect(registration.competition.get_absolute_url())
def form_invalid(self, form):
if self.request.is_ajax():
context = { 'errors': 'Error Occurred'}
return self.ajax_response(context, success=False)
return render_to_response(self.template_name, {'errors':form.errors})
Actually, comparing the above to your code, you may need to set the content_type in your django view so that jQuery can understand and process the response. Note that the above is using django 1.3 class-based views, but the logic should be familiar regardless. I use context.success to signal if the form processing passed or failed - since a valid response (json) of any kind will signal the jQuery.post that the request was successful.

Related

How to use Auth::check or Auth::user between different domains?

I've got a question regarding Laravel framework (vers. 5.2) and the authentication. I have 2 domains which represent a software. let's call them https://azure.mydomain.com and https://azuresoftware.mydomain.com.
The Laravel application is hosted on the domain https://azuresoftware.mydomain.com. https://azure.mydomain.com is just a CMS framework which is providing some information about the website.
Now I want to display different menus, if the user is logged in or not on https://azure.mydomain.com. I thought, I can do a fetch request to https://azuresoftware.mydomain.com/ and use the Laravel methods Auth::check() to check if the user is already logged in or not. I know that this is a CORS fetch request, but this is not the issue. I've allowed in the IIS webserver requests from https://azure.mydomain.com. The request works fine and also just a simple request. But actually Auth::check() is always returning false, even when I'm logged in on the software side.
This is my code so far:
<script>
fetch('https://azuresoftware.mydomain.com/checkLogin', {
method: 'GET',
headers: {
'Content-Type': 'text/plain'
}
})
.then(function(res) {
return res.json()
})
.then(function(data) {
if(data.isLoggedIn) {
// do some stuff...
}
else
{
// do some other stuff...
}
});
</script>
routes.php:
Route::group(['middleware' => 'web'], function () {
...
Route::get('checkLogin', function() {
return json_encode(['isLoggedIn'=>\Auth::check()]);
});
...
I'm sure, I forgot something essential, why it is not working this way.
This is due to the fact that AJAX calls only send cookies if the url you're calling is on the same domain as your calling script.
See Cross domain POST request is not sending cookie Ajax Jquery for more information.

Django CSRF Token Missing Only in Production

I am getting a missing CSRF_Token error that only occurs in production mode on my server. However everything works great when I am running it from my computer terminal using the runserver command. I've read through many of the other questions pertaining to this with no luck. It seems that my case is slightly different than others, since it works locally but not in production.
I get the error when submitting an Ajax form that submits to the "submit" in views.py. Does anybody know what could be causing this? Also, looking at my cookies in Production mode, the CSRF_Token is not even there to begin with. Locally it is. Thanks for any help.
Here is my views.py
from django.shortcuts import render
from django.http import HttpResponse
def index(request):
return render(request, 'index.html')
def submit(request):
#Receive Request
inputone = request.POST['randominfo']
inputtwo = request.POST['randominfo2']
#Some more code here that setups response.
#Deleted since Im posting to StackOverflow
return response
Code Pertaining to the Ajax Submit
$(function () {
$.ajaxSetup({
headers: { "X-CSRFToken": getCookie("csrftoken") }
});
});
function getCookie(c_name)
{
if (document.cookie.length > 0)
{
c_start = document.cookie.indexOf(c_name + "=");
if (c_start != -1)
{
c_start = c_start + c_name.length + 1;
c_end = document.cookie.indexOf(";", c_start);
if (c_end == -1) c_end = document.cookie.length;
return unescape(document.cookie.substring(c_start,c_end));
}
}
return "";
}
function submitAjax(event){
$.ajax({
type:'POST',
url:'/submit/',
data:{
randominfo:document.getElementById('Random').innerHTML,
randominfo2:document.getElementById('Random2').innerHTML,
},
dateType: 'json',
success:function() {
# Url here
}
})
};
Solution that fixed this problem.
Adding "from django.views.decorators.csrf import ensure_csrf_cookie" in views.py and then "#ensure_csrf_cookie" above the view that returns the html file that contained the ajax form
The error ocurs because you are not setting the csrf token, to prevent this we have to check some details
First of all, you have to set the csrf token to your form, in your html you have to set some as follow:
<form id="id" name="form">
{% csrf_token %}
<!-- Form body here -->
</form>
Second the approach to set the csrf cookie to your request header is ok, i only suggest that instead you set your data field one by one, use method serialize of jquery
data: $("#your-form-id").serialize()
I would like to recommend you to read this post about ajax request with django that is very helpful
There are 2 things you can do:
1.) Submit a CSRF token in your ajax call. You have to use a getCookie() javascript function to get it. Luckily the django documentation has some code you can copy and paste.
javascript
$.ajax({
type:'POST',
url:'/submit/',
data:{
randominfo:document.getElementById('Random').innerHTML,
randominfo2:document.getElementById('Random2').innerHTML,
'csrfmiddlewaretoken': getCookie('csrftoken'), // add this
...
2.) Disable csrf for your /submit view. You can do this with a decorator. Note that this is less secure so make sure there's no confidential data.
views.py:
from django.views.decorators.csrf import csrf_exempt
...
#csrf_exempt
def your_submit_view(request):
#view code

Express.js res.render not redirecting, just displayed in console

This time I want to use res.render to display html as success of DB update. I did it several times, but this time it doesn't work. It's not render html file, just displayed on chrome's console.
I think it caused because of async problem or duplicated response. I tried to many ways but I couldn't solve it, so pointers appreciated.
The code is related when the user paid service, increase user's level.
Get Access Token => Validate => res.render
app.post('/payment/validate', function(req, res, next){
// Get access token
request.post({
url : 'https://payment-company/get/token'
}, function(err, response, body) {
if(!err & response.statusCode == 200) {
var result = JSON.parse(body);
var accessToken = result.response.access_token;
// Validate payment (compare paid and would be paid)
request.get({
headers : { 'Authorization' : accessToken }
url : 'https://payment-company/find/paymentid'
}, function (err, response, body) {
if (!err && response.statusCode == 200){
var result = JSON.parse(body);
if (result.response.amount == req.body.price){
Members.findOne({id : req.user.id}, function(err, member){
// If no problem, update user level
member.level = 2;
member.save(function(err, result){
if (err) return next();
res.render('payment.view.result.ejs',
{
title : 'Success !',
description : 'level up.'
});
});
});
}
} else {
...
}
});
}
})
});
sorry to verbose code I tried to shorten code, No problem until res.render, res.render will work but it's not display page instead it just send html code to chrome's console.
Looks like there's a bit of a misunderstanding of how these requests work. What I think you intend:
Browser makes a GET request, server responds with an HTML document, the browser renders it
User takes an action
Browser makes a POST request, server responds with an HTML document, the browser renders it
What you've started coded on the frontend is an alternate method:
You make a POST request via AJAX, server responds with some JSON, you modify the current document with JavaScript to let the user know

How to implement CSRF protection in Ajax calls using express.js (looking for complete example)?

I am trying to implement CSRF protection in an app built using node.js using the express.js framework. The app makes abundant use of Ajax post calls to the server. I understand that the connect framework provides CSRF middleware, but I am not sure how to implement it in the scope of client-side Ajax post requests.
There are bits and pieces about this in other Questions posted here in stackoverflow, but I have yet to find a reasonably complete example of how to implement it from both the client and server sides.
Does anyone have a working example they care to share on how to implement this? Most of the examples I have seen, assume you are rendering the form on the server-side and then sending it (along with the embedded csrf_token form field) to the client-side. In my app, all content is rendered on the client-side (including templates) via Backbone.js. All the server does is provide values in JSON format, which are utilized by various Models in Backbone.js on the client-side. By my understanding I would need to retrieve the csrf_token via ajax first before it can be used. However, I am concerned this may be problematic from a security standpoint. Is this a valid concern?
It can be done by adding meta tag for CSRF token and then pass CSRF token with every Ajax request
Server
Add CSRF middleware
app.use(express.csrf());
app.use(function (req, res, next) {
res.locals.token = req.session._csrf;
next();
});
You can pass a CSRF token to the client side via, say, a meta tag. For ex, in Jade
meta(name="csrf-token", content="#{token}")
Client
jQuery has a feature called ajaxPrefilter, which lets you provide a callback to be invoked every Ajax request. Then set a header using ajaxPrefilter.
var CSRF_HEADER = 'X-CSRF-Token';
var setCSRFToken = function (securityToken) {
jQuery.ajaxPrefilter(function (options, _, xhr) {
if (!xhr.crossDomain) {
xhr.setRequestHeader(CSRF_HEADER, securityToken);
}
});
};
setCSRFToken($('meta[name="csrf-token"]').attr('content'));
server.js
...
// All Cookies/Sessions/BodyParser go first
app.use(express.csrf());
...
// Get the request
app.post('/ajax', function(req, res){
res.render('somelayout', {csrf_token: req.session._csrf});
});
In somelayout.jade
input(type='hidden', name='_csrf', value=csrf_token)
The CSRF middleware only generates the csrf token once per session, so it will probably not change for the duration of a user's visit.
Also, it doesn't check for the token on GET and HEAD requests. As long as the token is in the request (header, body, or query), you're good. That's pretty much all there is to it.
Since you are using Backbone.js for your application, I am assuming that it is a SPA and you initially load an index.html file, then make any other requests are made via ajax calls. If so, you can add a small snippet of JS code to your index.html file to hold the crsf token for any future ajax calls.
For example:
index.html (using Handlebars for templating...)
<!DOCTYPE html>
<html>
<head>
...
<script type="text/javascript">
$( function() {
window.Backbone.csrf = "{{csrfToken}}";
});
</script>
</head>
<body>
...
</body>
</html>
When you render the index.html file, give it the csrf token that the express framework generated here: req.session._csrf
When you use Backbone.js, it sets a global variable called Backbone. All that the previous function is doing is seting a property called csrf to the global Backbone object. And when you make an ajax call to POST data, simply add the Backbone.csrf variable to the data as _csrf that is being sent via the ajax call.
In Server:
app.use(function (req, res) {
res.locals._csrf = req.csrfToken();
res.locals.csrf_form_html = '<input type="hidden" name="_csrf" value="' + req.csrfToken() + '" >';
req.next();
});
In Client: (swig template)
var csrf = {{ _csrf|json|safe }};
$.ajaxSetup({
headers: {
'X-CSRF-Token': csrf
}
});
$.post("/create", data, function(result) {
console.log(result);
}).fail(function(){
console.log(arguments);
});
1. Add csrf protection middleware:
app.use(csrf({cookie: true}));
// csrf middleware
app.use(function (req, res, next) {
res.cookie('X-CSRF-Token', req.csrfToken());
// this line below is for using csrfToken value in normal forms (as a hidden input)
res.locals.csrfToken = req.csrfToken();
next();
});
// routing setup goes here
2. Add a beforeSend callback using $.ajaxSetup: (add this somewhere before all your ajax calls)
$.ajaxSetup({
beforeSend: function (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;
}
if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
// Only send the token to relative URLs i.e. locally.
xhr.setRequestHeader("X-CSRF-Token", getCookie('X-CSRF-Token'));
}
}
});
3. That's it! now you can send ajax requests and you don't need to add anything in headers or as a request parameter to pass through csrf.

Chrome gives "XMLHttpRequest Exception 101" in some cases when doing an Ajax request

I have a JavaScript application that works like this:
Uploads a file, receives the uploaded file ID as a response
This is done using the BlueImp uploader
Uses the file ID to refer to the file in subsequent requests, in this case to receive a preview of the uploaded file.
This is the code for the file upload 'complete' handler. It's originally written in Coffee Script (http://pastebin.com/708Cf9tu).
var completeHandler = function(e, data) {
var url;
if (data.textStatus !== 'success') {
alert("Noe gikk galt. Debug informasjon er logget i konsollen");
console.group('Upload failure');
console.error(data.textStatus);
console.error(data.result);
console.groupEnd('Upload failure');
selectButton.removeClass('disabled');
uploadButton.removeClass('disabled loading');
uploadButton.html('Last opp');
return;
}
self.fileUploadResponse = data.result;
url = "" + config.api_root + "/" + config.api_path_tabulardatafilepreview;
return $.ajax(url, {
type: 'POST',
dataType: 'json',
async: false,
data: {
'file_handle': data.result.file_handle,
'rownum': 5
},
complete: function(req, text_status) {
if (text_status !== 'success') {
alert("Noe gikk galt. Debug informasjon er logget " + "i konsollen");
console.group('Failed to receive data file preview');
console.log(text_status);
console.log(req.responseText);
console.log(req);
console.groupEnd('Failed to receive data file preview');
selectButton.removeClass('disabled');
uploadButton.removeClass('disabled loading');
uploadButton.html('Last opp');
}
self.previewData = JSON.parse(req.responseText);
return self.setStage(2);
}
});
};
This works brilliantly in FireFox, but in Chrome I just started to get an error in the second jQuery Ajax request. It now returns with status "error", with no responseText and with statusText set to "Error: NETWORK_ERR: XMLHttpRequest Exception 101". Though this doesn't happen in all cases. The uploaded file doesn't seem to have anything to do with the issue, because a 10KB csv file works, a 120KB xlsx file fails but a 1.2MB xlsx works. Additionally it's the second Ajax request that fails, and it doesn't do anything but send two small integers to the server. Why does that fail!?
Also this just started happening today. I haven't changed anything that I know of, and I have not updated Chrome.
Does anyone have a clue as to why Chrome is doing this? Can it have anything to do with an Ajax request being launched in the complete handler of a previous Ajax request?
Thanks for any guesses that can help me solve this
Turns out it's a bad idea to start lengthy processes inside Ajax event handlers. In my case, starting a new synchronous Ajax request in the event handler was the mistake. I have since made both requests asynchronous and separated the code into neat functions, and I'm no longer bothered by the exception.

Resources