Add CORS header to the JSON endpoint to allow requests from any website

Also make the JSON view a login required view if no username is given in
the query string.
This commit is contained in:
Benjamin Dauvergne 2015-03-11 10:09:08 +01:00
parent 54f2509a68
commit 4e70852578
1 changed files with 9 additions and 3 deletions

View File

@ -12,6 +12,7 @@ from django.core import signing
from django.contrib import messages
from django.contrib.auth import get_user_model, REDIRECT_FIELD_NAME
from django.utils.translation import ugettext as _
from django.utils.decorators import method_decorator
from django_tables2 import SingleTableMixin
@ -178,10 +179,15 @@ class JSONP(Documents, View):
class JSON(JSONP):
def get(self, request):
username = request.GET.get('username')
User = get_user_model()
request.user = get_object_or_404(User, username=username)
return HttpResponse(dumps(self.get_data(request)),
if username:
User = get_user_model()
request.user = get_object_or_404(User, username=username)
elif not request.user.is_authenticated():
return method_decorator(login_required)(JSON.get)(self, request)
response = HttpResponse(dumps(self.get_data(request)),
content_type='application/json')
response['Access-Control-Allow-Origin'] = '*'
return response
home = login_required(Homepage.as_view())
document = login_required(Document.as_view())