Last active
April 17, 2019 20:20
-
-
Save dex4er/aa5a4bfc169ba92d56f70111471a535e to your computer and use it in GitHub Desktop.
NoCsrfForJSONGraphQLView.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from graphene_django.views import GraphQLView | |
from django.conf import settings | |
from django.utils.decorators import classonlymethod | |
from django.views.decorators.csrf import csrf_protect, csrf_exempt | |
class NoCsrfForJSONGraphQLView(GraphQLView): | |
@classonlymethod | |
def as_view(cls, **kwargs): | |
view = super(NoCsrfForJSONGraphQLView, cls).as_view(**kwargs) | |
view = csrf_exempt(view) | |
return view | |
def dispatch(self, request, *args, **kwargs): | |
super_dispatch = super(NoCsrfForJSONGraphQLView, self).dispatch | |
if request.content_type != 'application/json': | |
super_dispatch = csrf_protect(super_dispatch) | |
response = super_dispatch(request, *args, **kwargs) | |
if getattr(response, 'csrf_cookie_set', False) and response['Content-Type'] == 'application/json': | |
response.cookies.pop(settings.CSRF_COOKIE_NAME) | |
return response |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment