Skip to content

Instantly share code, notes, and snippets.

@pomack
Created April 30, 2012 02:03
Show Gist options
  • Save pomack/2554893 to your computer and use it in GitHub Desktop.
Save pomack/2554893 to your computer and use it in GitHub Desktop.
decorators example
try:
from functools import wraps
except ImportError:
from django.utils.functional import wraps # Python 2.4 fallback.
from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse
from django.middleware import csrf
from django.utils.decorators import available_attrs
from phoenix.helpers.api.const import METHOD_NOT_ALLOWED_JSON_MESSAGE, NOT_AUTHENTICATED_JSON_MESSAGE, CSRF_JSON_MESSAGE, JSON_CONTENT_TYPE
__all__ = ('json_login_required',)
def json_login_required(function=None, allowed_methods=None, csrf_protected=True):
def decorator(view_func):
@wraps(view_func, assigned=available_attrs(view_func))
def _wrapped_view(request, *args, **kwargs):
if allowed_methods and request.method not in allowed_methods:
return HttpResponse(METHOD_NOT_ALLOWED_JSON_MESSAGE, content_type=JSON_CONTENT_TYPE, status=405)
if not request.user.is_authenticated():
return HttpResponse(NOT_AUTHENTICATED_JSON_MESSAGE, content_type=JSON_CONTENT_TYPE, status=401)
if csrf_protected:
request_csrf_token = request.META.get('HTTP_X_CSRFTOKEN', '')
request.META['CSRF_COOKIE'] = csrf._sanitize_token(request.COOKIES[settings.CSRF_COOKIE_NAME])
if not request.META['CSRF_COOKIE'] or not request_csrf_token or request.META['CSRF_COOKIE'] != request_csrf_token:
return HttpResponse(CSRF_JSON_MESSAGE, content_type=JSON_CONTENT_TYPE, status=401)
return view_func(request, *args, **kwargs)
return _wrapped_view
if function:
return decorator(function)
return decorator
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment